webSocket 使用 HttpSession 的数据配置与写法

1。前言

webSoket 无法获取 HttpSession  ,使用就更谈不上了 !!!

2解决过程

使用   configurator  注入即可

(1)

配置一个类

 1 package cn.cen2guo.clinic.websocket;
 2 
 3 
 4 import javax.servlet.http.HttpSession;
 5 import javax.websocket.HandshakeResponse;
 6 import javax.websocket.server.HandshakeRequest;
 7 import javax.websocket.server.ServerEndpointConfig;
 8 
 9 
10 /**
11  * 用于从websocket中获取用户session
12  */
13 public class HttpSessionConfigurator extends ServerEndpointConfig.Configurator  {
14 
15     @Override
16     public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
17         HttpSession httpSession = (HttpSession) request.getHttpSession();
18         sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
19     }
20 }

(2)websocket业务类注入   HttpSessionConfigurator.class

 (3)onOpen里面的额使用方法

可以用  config 来获取 ,也可以以当前会话session来获取  

测试截图:

 3 . 经验:

 当前会话session 都保存起来,这样就可以对其他会话session进行操作了

担心线程安全问题,可使用 ConcurrentMap<String, Map<String, List<Object>>> messageMap=new ConcurrentHashMap<>();  

当然,里面的泛型则根据需要自己定义  ,ConcurrentMap 的用法 与Map一样,唯一区别就是自带同步锁,线程安全

在@OnOpen方法里 将当前会话session设为全局变量,于是,在其他方法里都可以使用session获取  HttpSession   !!!

 

如 :@OnClose 方法里面 ,完美使用,

有些方法里面自带当前会话session参数  ,那么既 可以使用 已经在@onOpen记录的session  [this.session]  ,也可以使用该方法注入的session

 

.

原文地址:https://www.cnblogs.com/c2g5201314/p/12304347.html