如果对spring webSocket 的基本使用方式不了解,请参考:webSocket实现扫码登录
握手拦截器:HttpSessionHandshakeInterceptor的实现类重写beforeHandshake方法,如下
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
System.out.println("Before Handshake");
// if (request instanceof HttpServletRequest) {
// String currHttpSessionId = ((HttpServletRequest)request).getSession().getId();
// logger.debug("currHttpSessionId:{}", currHttpSessionId);
// attributes.put("currHttpSessionId", currHttpSessionId);
// }else{
// logger.warn("request不是 HttpServletRequest");//执行结果为不是HttpServletRequest
// }
//获取httpsession
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession httpSession = servletRequest.getServletRequest().getSession(false);
if (httpSession != null) {
logger.debug("HttpSessionId:"+httpSession.getId());
attributes.put("currHttpSession",httpSession);
}else{
logger.debug("httpsession is null");
}
}
return super.beforeHandshake(request, response, wsHandler, attributes);
}
如上面的代码中获取httpsession对象,并保存在attributes中。之后消息处理类中的每个方法都可以获取当前的socketsession,通过这个socketSession.getAttributes();获取这个map从中可以拿到当前长连接所关联的httpsession对象。如下:
消息处理类:TextWebSocketHandler的实现中的方法都可以使用类似下面的方法获取httpsession对象
// 连接 就绪时
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
logger.debug("[{} : {}] has be connected...", session.getUri(), session.getId());
// 获取httpsession
Map<String, Object> attributes = session.getAttributes();
System.out.println("attributesMap:" + attributes.toString());
HttpSession httpSession = (HttpSession) attributes.get("currHttpSession");
System.out.println("httpSessionId:" + httpSession.getId());
SESSION_MAP.put(session.getId(), session);
// 发送sessionId给前端
logger.info("返回id");
Msg4Ws<String> msg4Ws = new Msg4Ws<String>(10000, "ws的sessionId", session.getId());
String message = new ObjectMapper().writeValueAsString(msg4Ws); // 转为json
TextMessage returnMessage = new TextMessage(message);
session.sendMessage(returnMessage);
}
打印结果如下:
截图中发现attributes中默认会包含一个key为:HTTP.SESSION.ID的字符串正是httpsession的Id.如果项目有httpsession监听器保存了所有的httpsession,那么可以使用这个httpsessionId来获取httpsession。
原文地址:https://my.oschina.net/iyinghui/blog/1786177