SpringBoot整合websocket獲取http會(huì)話信息

上一篇文章中介紹過SpringBoot整合websocket技術(shù)

使用SpringBoot搭建實(shí)時(shí)通信服務(wù)

本文在此基礎(chǔ)上,介紹下在WebSocketSession會(huì)話中如何獲取到http會(huì)話信息~

獲取http會(huì)話用途

未使用前后端分離開發(fā)方案下,在WebSocketSession中如果能拿到HttpSession會(huì)話信息,就可以根據(jù)會(huì)話中的屬性值,做相應(yīng)的業(yè)務(wù)邏輯處理,比如權(quán)限控制,用戶身份識(shí)別,信息過濾等等

  • SpringBoot版本 2.4.5

使用方式

  1. 修改registerWebSocketHandlers配置,增加HttpSessionHandshakeInterceptor攔截器,用于實(shí)現(xiàn)同步HttpSession會(huì)話中的屬性信息
  2. 修改WebSocketHandler消息處理器,嘗試打印WebSocketSession中的會(huì)話信息,來觀察http會(huì)話信息是否已經(jīng)同步過來~

    3.添加設(shè)置http會(huì)話信息的Controller層映射方法

    4.編寫前端測(cè)試代碼來設(shè)置HttpSession會(huì)話信息,以及連接websocket服務(wù)
    完整代碼參考:https://github.com/netbuffer/spring-boot-websocket-demo/blob/master/src/main/resources/public/websocket.html
    <script src="/reconnecting-websocket.js"></script>
    <script type="text/javascript">
        var ws = new ReconnectingWebSocket("ws://localhost:17000/ws", null, {
            debug: true,
            automaticOpen: false,
            reconnectInterval: 3000
        });

        ws.onopen = function () {
            console.log("Connection open ...");
        }

        ws.onmessage = function (r) {
            console.log("Received Message: " + r.data);
        }

        ws.onclose = function () {
            console.log("Connection closed.");
        }

        function connect() {
            ws.open();
        }

        function set_session() {
            var key = prompt("請(qǐng)輸入key");
            var value = prompt("請(qǐng)輸入value");
            var formData = new FormData();
            formData.append('key', key);
            formData.append('value', value);
            fetch("/http/session/set", {
                body: formData,
                method: 'POST'
            })
                .then(function (response) {
                    return response;
                })
                .then(function (response) {
                    console.log(`send msg success`);
                    alert("send success");
                });
        }
    </script>
</head>
<body>
<div>
    <button onclick="connect()">connect</button>
    <button onclick="set_session()">set_session</button>
</div>

運(yùn)行效果

啟動(dòng)SpringBoot工程,訪問http://localhost:17000/websocket.html
點(diǎn)擊set_session按鈕來設(shè)置屬性值aaa/bbb



設(shè)置HttpSession會(huì)話屬性完成后,現(xiàn)在我們?cè)冱c(diǎn)擊connect按鈕,來發(fā)起websocket會(huì)話,并觀察控制臺(tái)日志輸出~

觀察結(jié)果,可以看到WebSocketSession中已經(jīng)拿到了HttpSession中的會(huì)話信息了

至此,完成了在WebSocketSession中獲取HttpSession會(huì)話信息的能力整合~


完整測(cè)試工程參考:https://github.com/netbuffer/spring-boot-websocket-demo

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容