Spring
[SpringFramework]WebSocketSession에서 HttpSession 값 가져오기
regularity
2022. 8. 3. 18:47
728x90
1. 목표:
채팅페이지에 입장시 HttpSession에 저장 된 사용자ID를 WebSocketSession에서도 사용
2. 문제:
HttpSession과 WebSocketSession이 다르기때문에 기본적으로 서로의 데이터를 접근할 수 가 없음
그래서 WebSocketSession에서 getID()를 사용하면 이렇게 임의로 부여된 사용자ID 정보가 찍힌다
3. 해결책:
servlet-context에서 websocket에 handshake-interceptors라는 구문을 추가
(interceptor는 http통신에서 request, response를 가로채는 역할을 한다.) Httpsession에 있는 값을 가로채서 WebSocketSession에 똑같이 넣어주는 역할을 한다. |
<websocket:handlers>
<websocket:mapping handler="echoHandler" path="/echo" />
<websocket:handshake-interceptors>
<beans:bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor" />
</websocket:handshake-interceptors>
<websocket:sockjs />
</websocket:handlers>
4. 결과:
클라이언트가 연결 되었을 때 실행되는 메서드에서 WebSocketSession 의 getAttributes()를 사용하면 전에는 관련없는 정보만 호출되었지만, handshake-interceptors 추가한 후 ,
이렇게 HttpSession에 저장된 로그인 아이디 정보를 가져올 수 있게 되었고, [유저아이디] 정보만 필요 하기때문에
.get("userid") 를 통해 KEY값만 불러 오도록 함
"정상작동"
728x90