SpringBoot在WebSocket长连接中获取到HttpSession
Websocket是通过http协议握手后升级成为长连接,在握手的时候,可以读取到客户端http请求的所有信息,自然也包括 HttpSession。
自定义配置类,继承 Configurator ,覆写modifyHandshake方法
ServerEndpointConfigImpl.Configurator,提供了一个modifyHandshake方法,可以在完成握手后,读取客户端的请求,以及修改对客户端的响应。HandshakeRequest 类已经提供了获取HttpSession的接口。
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.undertow.websockets.jsr.ServerEndpointConfigImpl;
public class ServerEndpointConfigurator extends ServerEndpointConfigImpl.Configurator {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerEndpointConfigurator.class);
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
// 尝试获取到当前Websocket链接的HttpSession
HttpSession httpSession = (HttpSession)request.getHttpSession();
LOGGER.info("session={}", httpSession);
if (httpSession != null) {
// session id
LOGGER.info("sessionId={}", httpSession.getId());
// 读取session域中存储的数据
L

本文介绍了如何在SpringBoot的WebSocket长连接中获取HttpSession。通过自定义Configurator配置类并覆写modifyHandshake方法,可以在WebSocket连接建立时读取到HttpSession。在@ServerEndpoint注解中指定Configurator实现类,然后通过Controller创建Session,最后在JS客户端与服务器建立连接时,可以从日志中验证HttpSession已被成功获取并读取其数据。
最低0.47元/天 解锁文章
541

被折叠的 条评论
为什么被折叠?



