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了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM