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 }
问题解决。
本文作者:东北小狐狸
本文链接:https://www.cnblogs.com/hellxz/p/8063867.html
版权声明:本作品采用自由转载-非商用-非衍生-保持署名 (CC BY-NC-ND 3.0)许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步