spring中怎么利用websocket獲取HttpSession

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān) spring中怎么利用websocket獲取HttpSession,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

旅順口網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián)公司,旅順口網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為旅順口上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的旅順口做網(wǎng)站的公司定做!


一個(gè)普通網(wǎng)站,用戶登錄后,將用戶信息存在HttpSession中?,F(xiàn)在網(wǎng)站需要加入即時(shí)聊天功能,打算使用Websocket實(shí)現(xiàn),需要在Websocket中拿到HttpSession來表示用戶。

    /**
     * 交流
     * @param chatMessage
     */
    @MessageMapping("/chat")
    public void chat(HttpSession session, @RequestBody ChatMessage chatMessage) {
        User user = (User)session.get("user");    // error
        chatService.chat(user,chatMessage);
    }

普通的注入HttpSession是不行的,因?yàn)閃ebsocket連接建立后,并不會(huì)HTTP協(xié)議那樣,每次傳輸數(shù)據(jù)都會(huì)帶上sessionid。

解決思路
在Websocket連接建立階段(此時(shí)還是HTTP協(xié)議)攔截HTTP請(qǐng)求,獲取到HttpSesion并保存。

實(shí)現(xiàn)
本來想自己寫個(gè)類,但發(fā)現(xiàn)Spring Websocket已經(jīng)提供了這樣的攔截器HttpSessionHandshakeInterceptor,直接使用即可。

Websocket 代理配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/chat");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/endpoint").setAllowedOrigins("*").addInterceptors(new HttpSessionHandshakeInterceptor()).withSockJS();
    }
}

這里和普通的Websocket配置差不多,最大的區(qū)別是addInterceptors(new HttpSessionHandshakeInterceptor()),它把HttpSessionHandshakeInterceptor加入到了攔截鏈中。
我們可以看一下HttpSessionHandshakeInterceptor源碼中的相關(guān)方法

// 在握手完成前(連接建立階段)
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        HttpSession session = this.getSession(request);     
        if (session != null) {
            if (this.isCopyHttpSessionId()) {
                attributes.put("HTTP.SESSION.ID", session.getId());  // 保存 sessionid
            }

            Enumeration names = session.getAttributeNames();

            while(true) {
                String name;
                do {
                    if (!names.hasMoreElements()) {
                        return true;
                    }

                    name = (String)names.nextElement();
                } while(!this.isCopyAllAttributes() && !this.getAttributeNames().contains(name));

                attributes.put(name, session.getAttribute(name));    // 保存HttpSession中的信息
            }
        } else {
            return true;
        }
}

// 獲取HttpSession
private HttpSession getSession(ServerHttpRequest request) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest)request;
            return serverRequest.getServletRequest().getSession(this.isCreateSession());
        } else {
            return null;
        }
}


通過源碼我們可以知道,HttpSessionHandshakeInterceptor將HttpSession中的值保存到了一個(gè)Map里面,通過搜索spring的官方文檔,我發(fā)現(xiàn)可以通過注入SimpMessageHeaderAccessor在Controller方法中獲取到那些值。

    /**
     * 交流
     * @param chatMessage
     */
    @MessageMapping("/chat")
    public void chat(SimpMessageHeaderAccessor headerAccessor, @RequestBody ChatMessage chatMessage) {
        User user = (User) headerAccessor.getSessionAttributes().get("user");  // right
        chatService.chat(user,chatMessage);
    }

上述就是小編為大家分享的 spring中怎么利用websocket獲取HttpSession了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

文章題目:spring中怎么利用websocket獲取HttpSession
URL鏈接:http://muchs.cn/article28/iepojp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名軟件開發(fā)、網(wǎng)站改版網(wǎng)站內(nèi)鏈、建站公司、網(wǎng)站營銷

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

手機(jī)網(wǎng)站建設(shè)