사용자 세션 관리
HTTP 세션을 WebSocket 세션과 연결하는 고급 WebSockets 사용자 세션 관리를 구현합니다.
사용자 세션 관리은(는) CoddyKit의 무료 WebSockets & Real-Time Systems with Spring 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Real-Time Systems with Spring 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Understanding User Sessions
In web applications, a "session" helps a server remember a user across multiple requests. It's like a temporary memory for each user.
For traditional HTTP, sessions are often managed with cookies. They allow you to store user-specific data, like login status or cart items, between page loads.
WebSockets: Session Challenges
Unlike HTTP, WebSockets establish a persistent, full-duplex connection. This connection doesn't inherently carry the same session context as an HTTP request.
This means if a user logs in via HTTP and then opens a WebSocket, the WebSocket connection won't automatically know who the user is without specific setup.
- HTTP Session: Short-lived, request-response.
- WebSocket Session: Long-lived, persistent connection.
Bridging HTTP & WebSocket Sessions
To build rich real-time applications, you often need the WebSocket connection to know about the user's HTTP session context.
For example, you might need to know if a user is authenticated, their user ID, or other profile details that were established during their initial HTTP login.
Spring provides mechanisms to "bridge" this gap during the WebSocket handshake.
The Handshake Interceptor
Spring's primary tool for linking HTTP and WebSocket sessions is the HttpSessionHandshakeInterceptor.
This interceptor runs during the WebSocket handshake, which is the initial HTTP request that upgrades to a WebSocket connection. It can copy attributes from the current HTTP session to the WebSocket session.
- What it does: Copies HTTP session attributes.
- When it runs: During the WebSocket handshake.
Configuring Session Interceptor
To use the HttpSessionHandshakeInterceptor, you need to register it within your WebSocket configuration. This tells Spring to apply the interceptor when a WebSocket connection is being established.
It's typically added in your WebSocketMessageBrokerConfigurer implementation:
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.addInterceptors(new HttpSessionHandshakeInterceptor())
.withSockJS();
}
}Accessing Linked Session Data
Once the HttpSessionHandshakeInterceptor has done its job, you can access the copied HTTP session attributes within your WebSocket message handlers.
Commonly, you'll want to access the Principal (representing the authenticated user) or other custom attributes you've stored in the HTTP session.
@Controller
public class MyWebSocketController {
@MessageMapping("/hello")
public void handleMessage(@Payload String message, Principal principal) {
String username = principal.getName();
System.out.println("Message from " + username + ": " + message);
// ... use username for user-specific logic
}
}WebSocket-Specific Data
Besides copying HTTP session data, you can also store information directly within the WebSocketSession itself. This data is specific to that particular WebSocket connection.
This is useful for managing connection-specific states, like a user's current chat room, notification preferences for this connection, or other transient data.
@EventListener
public void handleSessionConnect(SessionConnectedEvent event) {
StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
WebSocketSession session = (WebSocketSession) accessor.getSessionAttributes().get("webSocketSession");
if (session != null) {
session.getAttributes().put("customKey", "customValue");
}
System.out.println("User connected: " + accessor.getUser().getName());
}Managing Session Lifecycle
Spring allows you to listen to WebSocket session lifecycle events. This is crucial for cleaning up resources or updating user status when connections are established or closed.
You can use @EventListener with SessionConnectedEvent and SessionDisconnectEvent to react to these changes.
SessionConnectedEvent: Fired when a new STOMP session is established.SessionDisconnectEvent: Fired when a STOMP session is closed.
Runnable: Handshake Interceptor
This Spring Boot example configures a WebSocket endpoint with HttpSessionHandshakeInterceptor. When a client connects, the interceptor helps link the HTTP session (if any) to the WebSocket session.
We demonstrate a simple message handler that could access the authenticated user's Principal. If Spring Security were enabled, principal.getName() would return the logged-in username.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import java.security.Principal;
@SpringBootApplication
@EnableWebSocketMessageBroker
public class WebSocketSessionApp {
public static void main(String[] args) {
SpringApplication.run(WebSocketSessionApp.class, args);
}
@Configuration
public static class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.addInterceptors(new HttpSessionHandshakeInterceptor())
.withSockJS();
}
}
@Controller
public static class WebSocketGreetingController {
@MessageMapping("/hello")
public void greeting(Principal principal) {
if (principal != null) {
System.out.println("Message from authenticated user: " + principal.getName());
} else {
System.out.println("Message from unauthenticated user (Principal is null).");
}
}
}
}Quick Check: Handshake Interceptor
Test your understanding of the HttpSessionHandshakeInterceptor.
Recap: Session Management
We've explored how to manage user sessions in Spring WebSocket applications, particularly how to link HTTP session context to WebSocket sessions.
- The
HttpSessionHandshakeInterceptoris key for copying HTTP session attributes during the handshake. - You can access authenticated user information (
Principal) in WebSocket handlers. @EventListenerhelps manage connection and disconnection events.
Proper session management ensures your real-time features are personalized and secure for each user.
자주 묻는 질문
“사용자 세션 관리” 강의는 무료인가요?
네 — “사용자 세션 관리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Real-Time Systems with Spring 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.
“사용자 세션 관리”에서 뭘 배우나요?
HTTP 세션을 WebSocket 세션과 연결하는 고급 WebSockets 사용자 세션 관리를 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Real-Time Systems with Spring을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Real-Time Systems with Spring은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“사용자 세션 관리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Real-Time Systems with Spring 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Real-Time Systems with Spring 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.