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