0Pricing
WebSockets & Real-Time Systems with Spring · 课时

WebSocket 拦截器

利用 WebSocket 拦截器,对消息和连接事件执行预处理与后处理。

WebSocket 拦截器 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Real-Time Systems with Spring 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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!

常见问题解答

「WebSocket 拦截器」课时是免费的吗?

是的 — 「WebSocket 拦截器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Real-Time Systems with Spring 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。

「WebSocket 拦截器」这节课中我会学到什么?

利用 WebSocket 拦截器,对消息和连接事件执行预处理与后处理。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Real-Time Systems with Spring 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Real-Time Systems with Spring 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「WebSocket 拦截器」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebSockets & Real-Time Systems with Spring 课中编写并运行代码吗?

能。每节 WebSockets & Real-Time Systems with Spring 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. WebSocket 拦截器
  2. 自定义消息转换器
  3. 用户会话管理
  4. 向特定用户定向发送消息
← 返回 WebSockets & Real-Time Systems with Spring