参考了很多帖子,然后总是报空指针异常,最后从StackOverflow上得到的答案
1. 配置WebSocket
@Configuration
public class WebSocketConfig extends HttpSessionHandshakeInterceptor {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2. 配置HttpSession
public class HttpSessionConfig extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
super.modifyHandshake(sec, request, response);
HttpSession httpSession = (HttpSession) request.getHttpSession();
sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
}
}
3. 添加过滤器
@Component
@ServletComponentScan
@WebFilter(filterName = "wsFilter", urlPatterns = "/chat")
public class WebSocketFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
((HttpServletRequest) (servletRequest)).getSession();
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
4. 编写WebSocket通信处理的代码
@ServerEndpoint(value = "/chat", configurator = HttpSessionConfig.class)
@Component
public class ChattingController {
@OnOpen
public void handleOpen(EndpointConfig config, Session session) {
//获取HttpSession对象,可以把断点打在这里看能不能获取到对象
HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
}
@OnMessage
public void handleMessage(String message, Session session) {
//todo send and store message to db
}
}
最后,页面的访问路径是`ws://xxx.xxx.xxx/chat` 而不是 `http://`
更新:ws://与http://访问后台的路径必须统一,如统一使用127.0.0.1或者localhost,否则会导致两种方式下的HttpSession不一致

本文介绍了在SpringBoot环境中结合WebSocket如何正确配置并获取HttpSession。通过配置WebSocket、HttpSession、添加过滤器以及编写WebSocket通信代码,解决在`ws://`下HttpSession为空的问题。关键在于确保ws和http的访问路径基础一致,如都使用127.0.0.1或localhost,以保持HttpSession的一致性。
678

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



