1. 程式人生 > >spring websocket 獲取httpsession

spring websocket 獲取httpsession

按照spring websocket的教材搭建了一個websocket的測試程式,但是自定義的HandshakeInterceptor 型別攔截器,始終獲取不到httpsession,如下圖,獲取到得httpsession始終為null,
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
	 
    private static Log logger = LogFactory.getLog(HandshakeInterceptor.class);
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object
                > attributes) throws Exception {
    	logger.debug("beforeHandshake start.....");
    	logger.debug(request.getClass().getName());
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            if (session != null) {
                //使用userName區分WebSocketHandler,以便定向傳送訊息
                String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);
                logger.info(userName+" login");
                attributes.put(Constants.WEBSOCKET_USERNAME,userName);
            }else{
            	logger.debug("httpsession is null");
            }
        }
        return true;
    }
 
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
    }
}

檢視瀏覽器的http請求


發現websocket的握手請求沒有攜帶cookie資訊,沒有cookie。。。  就沒有sessionId,那伺服器怎麼可能識別到是哪個httpsession呢,

所以在websocket連結後加上jsessionid,這樣伺服器就可以根據sessionid獲取到httpsession了,

http://10.10.10.107:8080//maven/webSocketServer;jsessionid=132CCDB1006D2A5CA1002368647D3672

雖然url攜帶jsessionid是個不太安全的做法,但是無奈只想到這種方式處理,姑且用之,

哪位大神有更加可靠的方式,望指點,不勝感激。

附上原始碼,程式碼在tomcat8下測試通過

原始碼下載