การจัดการเซสชันผู้ใช้
นำการจัดการเซสชันผู้ใช้ขั้นสูงสำหรับ WebSockets ไปใช้ โดยเชื่อมโยงเซสชัน HTTP กับเซสชัน WebSocket
การจัดการเซสชันผู้ใช้ เป็นบทเรียน WebSockets & Real-Time Systems with Spring ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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.
คำถามที่พบบ่อย
บทเรียน “การจัดการเซสชันผู้ใช้” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การจัดการเซสชันผู้ใช้” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Real-Time Systems with Spring ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การจัดการเซสชันผู้ใช้”
นำการจัดการเซสชันผู้ใช้ขั้นสูงสำหรับ WebSockets ไปใช้ โดยเชื่อมโยงเซสชัน HTTP กับเซสชัน WebSocket คุณปฏิบัติ WebSockets & Real-Time Systems with Spring ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Real-Time Systems with Spring หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Real-Time Systems with Spring บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การจัดการเซสชันผู้ใช้” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Real-Time Systems with Spring นี้ได้ไหม
ได้ บทเรียน WebSockets & Real-Time Systems with Spring ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ตัวดักจับ WebSocket
- การปรับแต่งตัวแปลงข้อความ
- การจัดการเซสชันผู้ใช้
- การส่งข้อความเฉพาะเจาะจงถึงผู้ใช้