zoukankan      html  css  js  c++  java
  • 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 }

    问题解决。

  • 相关阅读:
    bzoj4044/luoguP4762 [Cerc2014]Virus synthesis(回文自动机+dp)
    bzoj4032/luoguP4112 [HEOI2015]最短不公共子串(后缀自动机+序列自动机上dp)
    bzoj3926/luoguP3346 [Zjoi2015]诸神眷顾的幻想乡(trie上构建广义后缀自动机)
    bzoj3144 [HNOI2013]切糕(最小割)
    知识点简单总结——原根和指标
    uoj86 mx的组合数 (lucas定理+数位dp+原根与指标+NTT)
    rest_framework 学习笔记(一)
    Django 数据库操作
    02-Kubenetes资源
    10-Helm
  • 原文地址:https://www.cnblogs.com/hellxz/p/8063867.html
Copyright © 2011-2022 走看看