Intercepteurs WebSocket
Utilisez des intercepteurs WebSocket pour effectuer le prétraitement et le post-traitement des messages et des événements de connexion.
Intercepteurs WebSocket est une leçon WebSockets & Real-Time Systems with Spring gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage WebSockets & Real-Time Systems with Spring, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours WebSockets & Real-Time Systems with Spring comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Welcome to Interceptors!
In Spring WebSockets, Interceptors act like gatekeepers or event listeners that can observe and modify the WebSocket lifecycle.
They allow you to perform actions like logging, authentication, or modifying data at specific points during a connection or message exchange.
Lifecycle Hooks
Think of the WebSocket process:
- Handshake: Initial HTTP request to upgrade to WebSocket.
- Connection: WebSocket link is established.
- Message Exchange: Data flows between client and server.
- Disconnection: WebSocket link closes.
Interceptors let you "hook" into these stages.
Intercepting the Handshake
The HandshakeInterceptor is crucial for the very first step: the WebSocket handshake.
It lets you:
- Inspect the HTTP request before the WebSocket connection is established.
- Perform authentication or authorization checks.
- Add attributes to the WebSocket session.
You can decide whether to allow the handshake to proceed.
Coding a Handshake Interceptor
Let's create a simple HandshakeInterceptor that logs when a connection attempt begins and ends. This is useful for monitoring or debugging.
Notice the beforeHandshake and afterHandshake methods.
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;
public class MyHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
System.out.println(">>> Handshake starting for: " + request.getURI());
// 'attributes' map can be used to pass data to WebSocket session
return true; // Allow handshake to proceed
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Exception exception) {
System.out.println("<<< Handshake completed for: " + request.getURI());
if (exception != null) {
System.err.println("Handshake failed: " + exception.getMessage());
}
}
}Integrating Handshake Interceptors
To make our MyHandshakeInterceptor active, we need to register it within our Spring Boot application's WebSocket configuration.
Run this code and try connecting to ws://localhost:8080/ws from a browser's developer console (e.g., new WebSocket('ws://localhost:8080/ws')) to see the logs!
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
// MyHandshakeInterceptor.java (nested for brevity)
class MyHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest req, ServerHttpResponse res,
org.springframework.web.socket.WebSocketHandler h, Map<String, Object> a) {
System.out.println(">>> Handshake: " + req.getURI());
return true;
}
@Override
public void afterHandshake(ServerHttpRequest req, ServerHttpResponse res,
org.springframework.web.socket.WebSocketHandler h, Exception e) {
System.out.println("<<< Handshake done: " + req.getURI());
}
}
// WebSocketConfig.java (nested for brevity)
@Configuration
@EnableWebSocket
class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry r) {
r.addHandler(new TextWebSocketHandler(), "/ws")
.addInterceptors(new MyHandshakeInterceptor())
.setAllowedOrigins("*");
}
}Intercepting STOMP Messages
While HandshakeInterceptor handles initial connections, ChannelInterceptor focuses on STOMP messages flowing through Spring's message broker.
These interceptors operate on the messaging channels, allowing you to inspect or modify messages before they reach their destination or after they are sent.
Coding a Channel Interceptor
A ChannelInterceptor provides methods like preSend, postSend, and afterSendCompletion.
The preSend method is commonly used to inspect or modify a message before it is sent to its destination (e.g., a STOMP topic or user queue).
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptor;
public class MyChannelInterceptor implements ChannelInterceptor {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
// Log the message or perform security checks
System.out.println("Intercepted STOMP message: " + message.getHeaders());
// You can modify the message here
return message; // Return the message to proceed
}
// Other methods like postSend, afterSendCompletion...
}Integrating Channel Interceptors
To register a ChannelInterceptor, you typically use a configuration class that extends WebSocketMessageBrokerConfigurer.
- Use
clientInboundChannel()to intercept messages coming from clients. - Use
clientOutboundChannel()to intercept messages going to clients.
This allows fine-grained control over message flow.
Common Use Cases
Interceptors are powerful for many scenarios:
- Authentication & Authorization: Validate users before connection or message delivery.
- Logging: Track connection events and message traffic.
- Session Management: Attach user-specific data to WebSocket sessions.
- Message Modification: Add headers, filter content, or transform payloads.
- Rate Limiting: Prevent abuse by limiting message frequency.
Interceptor Knowledge Check
You've learned about two main types of WebSocket interceptors in Spring. Let's see if you can distinguish their primary use cases.
Interceptors: Your WebSocket Control
Today, you learned about Spring's WebSocket Interceptors, powerful tools for controlling and observing your real-time communication.
- Handshake Interceptors: For pre-connection logic.
- Channel Interceptors: For STOMP message flow.
They are essential for building secure, robust, and observable WebSocket applications. Next, we'll explore message converter customization!
Questions Fréquemment Posées
La leçon « Intercepteurs WebSocket » est-elle gratuite ?
Oui — le texte complet de « Intercepteurs WebSocket » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours WebSockets & Real-Time Systems with Spring, passe à CoddyKit PRO. Le cours WebSockets & Real-Time Systems with Spring comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Intercepteurs WebSocket » ?
Utilisez des intercepteurs WebSocket pour effectuer le prétraitement et le post-traitement des messages et des événements de connexion. Tu pratiques WebSockets & Real-Time Systems with Spring avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer WebSockets & Real-Time Systems with Spring ?
Aucune expérience préalable n'est requise. WebSockets & Real-Time Systems with Spring sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.
Combien de temps prend la leçon « Intercepteurs WebSocket » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon WebSockets & Real-Time Systems with Spring ?
Oui. Chaque leçon WebSockets & Real-Time Systems with Spring inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Intercepteurs WebSocket
- Personnalisation des convertisseurs de messages
- Gestion des sessions utilisateur
- Messagerie ciblée vers des utilisateurs précis