websocket获取httpsession报NullPointerException解决办法

最近在写个websocket程序时发现了个很严重的问题,就是按照配置ServerEndpointConfig.Configurator

public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator
{
@Override
public void modifyHandshake(ServerEndpointConfig config, 
                            HandshakeRequest request, 
                            HandshakeResponse response)
{
    HttpSession httpSession = (HttpSession)request.getHttpSession();
    config.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}

的方法获取httpsession会报空指针的错误。

后来在

http://stackoverflow.com/questions/20240591/websocket-httpsession-returns-null

https://bz.apache.org/bugzilla/show_bug.cgi?id=55824

找到了解决办法。

其中有一句话:

If there is no "HTTP session under which a client is operating" then there is no requirement to create one.

非常重要,然后解决方法是建立个请求监听器
如下:
@WebListener
public class RequestListener implements ServletRequestListener {
    
    public void requestInitialized(ServletRequestEvent sre)  { 
        //将所有request请求都携带上httpSession
        ((HttpServletRequest) sre.getServletRequest()).getSession();
        
    }
    public RequestListener() {
        // TODO Auto-generated constructor stub
    }

    public void requestDestroyed(ServletRequestEvent arg0)  { 
         // TODO Auto-generated method stub
    }
}

这样子请求的时候就能获取到session了。

原文地址:https://www.cnblogs.com/weikongziqu/p/5245165.html