解决websocket.GetHttpSessionConfig.modifyHandshake中获取httpsession时为null报NullPointerException

1.报错说明

public class GetHttpSessionConfig extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        // 获取session
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        // session放入serverEndpointConfig
        sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
    }
}

在这段WebSocket的配置器代码中,在 WebSocket 连接建立时,会调用 modifyHandshake方法,并将当前的 ServerEndpointConfig、握手请求和握手响应作为参数传入该方法。

但是从request中获取HttpSession为null报空指针异常

2.错误原因

客户端连接还未创建 HttpSession,所以获取到的是null,WebSocket 的这个Api实现仅获取已创建的某些内容,如果没有则不会帮助创建的

3.解决方案

既然WebSocket的Api不会帮助我们创建session,那么我们就需要在它获取session之前为客户端创建session,即,可以使用WebListner监听器,监听的时候为请求创建session

@Component
public class RequestListener implements ServletRequestListener {
    public void requestInitialized(ServletRequestEvent sre)  {
        //将所有request请求都携带上httpSession
        ((HttpServletRequest) sre.getServletRequest()).getSession();

    }
}

上面这段代码来源于stackoverflow的这篇帖子session - Websocket - httpSession returns null - Stack Overflow

原文中使用的是@WebListener注解,但是使用@WebListener注解需要注意的是,

@WebListener注解是在容器启动时,由 Servlet 容器(tomcat/Jetty)处理,所以想让这个注解生效需要我们在web.xml中配置监听器,更为麻烦。

使用@Component将其注册为Bean,Spring会自动检测将其注册为监听器

4.apipost测试

有对websocket请求进行调试的工具,例如我习惯用的apipost就支持

猜你喜欢

转载自blog.csdn.net/m0_54250110/article/details/131149969