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 }

    问题解决。

  • 相关阅读:
    Java 匿名内部类
    【嘎】数组-搜索插入位置
    【嘎】数组-1266. 访问所有点的最小时间
    【嘎】数组-1313. 解压缩编码列表
    【嘎】数组-1431. 拥有最多糖果的孩子
    element-ui下拉多选报错Error in event handler for "handleOptionClick": "TypeError: value.push is not a function"
    【嘎】数组-有效的山脉数组
    【嘎】数组-打家劫舍
    【嘎】字符串-字符串中的第一个唯一字符
    linux
  • 原文地址:https://www.cnblogs.com/hellxz/p/8063867.html
Copyright © 2011-2022 走看看