由于WebSocket使用的协议有别于单纯的http,所以如果想要在WebSocket中直接获取HttpSession是无法获取的。需要想办法将HttpSession传入websocket中。
首先新建一个类继承Configurator
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
/**
* 该类的作用是将HttpSession注入websocket
*/
public class GetHttpSessionConfigurator extends Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig sec,
HandshakeRequest request, HandshakeResponse response) {
// TODO Auto-generated method stub
HttpSession httpSession=(HttpSession) request.getHttpSession();
sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
然后在websocket的@ServerEndpoint注解里面添加configurator属性
@ServerEndpoint(value =\"/websocket\",configurator=GetHttpSessionConfigurator.class)
最后在onOpen方法里加入参数EndpointConfig config就可以获取到HttpSession
private HttpSession httpSession;
@OnOpen
public void onOpen( Session session,EndpointConfig config)
{
httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
}
继续阅读与本文标签相同的文章
-
Mybatis之discriminator(鉴别器)详解
2026-05-18栏目: 教程
-
前端进阶|第十一天 当全局变量,块变量,函数叫了同一个名字。。
2026-05-18栏目: 教程
-
Leetcode 542:01 矩阵 01 Matrix
2026-05-18栏目: 教程
-
LeetCode 733: 图像渲染 flood-fill
2026-05-18栏目: 教程
-
Spring Cloud Alibaba 实战(二) - 关于Spring Boot你不可不知道的实情
2026-05-18栏目: 教程
