SpringBoot + WebSocket环境下获取HttpSession

参考了很多帖子,然后总是报空指针异常,最后从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,Java,WebSocket,SpringBoot)