最近在寫個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了。
