【小結】java使用Websocket擷取HttpSession出現的問題

來源:互聯網
上載者:User

標籤:server   and   socket   tde   log   listen   blog   post   point   

websocket的寫法就不多說了,主要記一記其中出現的問題

1.擷取不到httpSession

解決辦法:先重寫握手方法,將httpsession放入ServerEndpointConfig.getUserProperties()方法返回的map中

 1 import javax.servlet.http.HttpSession; 2 import javax.websocket.HandshakeResponse; 3 import javax.websocket.server.HandshakeRequest; 4 import javax.websocket.server.ServerEndpointConfig; 5 import javax.websocket.server.ServerEndpointConfig.Configurator; 6  7 /** 8  * 繼承websocket配置類,將httpsession放入ServerEndpointConfig的map中 9  * 從而達到使websocket對象可以訪問到httpsession中的對象10  */11 public class GetHttpSessionConfigurator extends Configurator{12 13     /**14      * 重寫修改握手方法15      * @param sec16      * @param request17      * @param response18      */19     @Override20     public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {21         HttpSession httpSession = (HttpSession)request.getHttpSession();22         sec.getUserProperties().put(HttpSession.class.getName(),httpSession);23     }24 }

然後在註解@ServerEndpoint加入configurator的配置

 1 @ServerEndpoint(value="/websocket",configurator=GetHttpSessionConfigurator.class) 

此時已經可以擷取到httpsession了。

然而如果我沒有登入,反而需要臨時登入這種情況呢?根據上述demo,會發現根本沒辦法串連上,一直是close狀態

下面是對這個問題的解決

2、未登入使用者串連WebSocket,一直close狀態的情況解決:

解決方案是建立個請求監聽器
 1 @WebListener 2 public class RequestListener implements ServletRequestListener { 3      4     public void requestInitialized(ServletRequestEvent sre)  {  5         //將所有request請求都攜帶上httpSession 6         ((HttpServletRequest) sre.getServletRequest()).getSession(); 7          8     } 9     public RequestListener() {10         // TODO Auto-generated constructor stub11     }12 13     public void requestDestroyed(ServletRequestEvent arg0)  { 14          // TODO Auto-generated method stub15     }16 }

問題解決。

【小結】java使用Websocket擷取HttpSession出現的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.