java使用Websocket获取HttpSession出现的问题与解决

websocket的写法就不多说了,主要记一记其中出现的问题

1.获取不到httpSession

解决办法:先重写握手方法,将httpsession放入ServerEndpointConfig.getUserProperties()方法返回的map中

 1 import javax.servlet.http.HttpSession;
 2 import javax.websocket.HandshakeResponse;
 3 import javax.websocket.server.HandshakeRequest;
 4 import javax.websocket.server.ServerEndpointConfig;
 5 import javax.websocket.server.ServerEndpointConfig.Configurator;
 6 
 7 /**
 8  * 继承websocket配置类,将httpsession放入ServerEndpointConfig的map中
 9  * 从而达到使websocket对象可以访问到httpsession中的对象
10  */
11 public class GetHttpSessionConfigurator extends Configurator{
12 
13     /**
14      * 重写修改握手方法
15      * @param sec
16      * @param request
17      * @param response
18      */
19     @Override
20     public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
21         HttpSession httpSession = (HttpSession)request.getHttpSession();
22         sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
23     }
24 }

然后在注解@ServerEndpoint加入configurator的配置

 1 @ServerEndpoint(value="/websocket",configurator=GetHttpSessionConfigurator.class) 

此时已经可以获取到httpsession了。

然而如果我没有登录,反而需要临时登录这种情况呢?根据上述demo,会发现根本没办法连接上,一直是close状态

下面是对这个问题的解决

2、未登录用户连接WebSocket,一直close状态的情况解决:

解决方法是建立个请求监听器
 1 @WebListener
 2 public class RequestListener implements ServletRequestListener {
 3     
 4     public void requestInitialized(ServletRequestEvent sre)  { 
 5         //将所有request请求都携带上httpSession
 6         ((HttpServletRequest) sre.getServletRequest()).getSession();
 7         
 8     }
 9     public RequestListener() {
10         // TODO Auto-generated constructor stub
11     }
12 
13     public void requestDestroyed(ServletRequestEvent arg0)  { 
14          // TODO Auto-generated method stub
15     }
16 }

问题解决。

posted @ 2017-12-19 09:20  东北小狐狸  阅读(10052)  评论(0编辑  收藏  举报