In Spring Boot with Spring MVC, the WebSocketHandler interface is the server-side callback contract for a WebSocket connection. Spring calls its methods when a connection opens, when a message arrives, when a transport error occurs and when the connection closes. You usually extend TextWebSocketHandler or BinaryWebSocketHandler instead of implementing the interface directly.
This article covers the servlet-based org.springframework.web.socket.WebSocketHandler. Reactive applications use a different interface with the same name, described in the WebFlux article.
The interface defines five methods:
| Method | Called when |
|---|---|
afterConnectionEstablished(WebSocketSession) | The handshake succeeded and the session is ready |
handleMessage(WebSocketSession, WebSocketMessage<?>) | A text, binary or pong message arrives |
handleTransportError(WebSocketSession, Throwable) | The transport reports an error |
afterConnectionClosed(WebSocketSession, CloseStatus) | The connection is closed by either side |
supportsPartialMessages() | Spring asks whether you accept fragmented messages |
AbstractWebSocketHandler implements the interface and splits handleMessage into handleTextMessage, handleBinaryMessage and handlePongMessage. TextWebSocketHandler and BinaryWebSocketHandler build on it and reject the unsupported message type. In practice, you override only the callbacks you need.
A chat-style handler that keeps track of sessions and broadcasts each message:
The set is concurrent because several threads call the handler at once. Sending is synchronized per session because a WebSocketSession does not allow concurrent sendMessage calls. A cleaner way is to wrap each session in ConcurrentWebSocketSessionDecorator, which adds send timeouts and a buffer limit.
Add the spring-boot-starter-websocket dependency, then implement WebSocketConfigurer:
Use setAllowedOrigins with explicit origins rather than "*". By default Spring only accepts same-origin requests, which protects against cross-site WebSocket hijacking. Add .withSockJS() only when you must support clients without native WebSocket.
The browser side uses the standard WebSocket API:
Use wss:// in production so the connection is encrypted.
handleTransportError is called for I/O problems. Close the session there with session.close(CloseStatus.SERVER_ERROR) and log the cause.handleTextMessage is treated as a failure and closes the session, so catch exceptions you can recover from.ServletServerContainerFactoryBean bean, for example setMaxTextMessageBufferSize and setMaxSessionIdleTimeout, so a client cannot hold unlimited memory.SubProtocolCapable on the handler and return the supported names.For publish and subscribe messaging, destinations and broker integration, use STOMP with @EnableWebSocketMessageBroker instead of a raw handler. A raw handler is the better choice when you control both ends and want a custom protocol.
Extend TextWebSocketHandler for text such as JSON, or BinaryWebSocketHandler for binary data. They implement the boilerplate and reject unsupported message types.
Yes, a handler registered as a bean is shared by all connections. Keep per-connection state in the session attributes or in a map keyed by session id, and make shared state thread safe.
Call session.getPrincipal(). It is populated from the HTTP handshake when Spring Security has authenticated the request.
Inject the handler bean, or a session registry it shares, and call sendMessage on the stored sessions with the per-session synchronization shown above.
WebSocketHandler is the callback interface for servlet-based WebSockets in Spring Boot. Extend TextWebSocketHandler, override afterConnectionEstablished, handleTextMessage and afterConnectionClosed, and register the handler through WebSocketConfigurer. Restrict allowed origins, guard against concurrent sends, and consider STOMP when you need brokered messaging.