java
48 lines · 8 steps
Real-time chat over STOMP WebSockets in Spring
A Spring WebSocket config plus a controller that routes STOMP messages and broadcasts presence updates to subscribed clients.
Explained by
highlit
1@Configuration
2@EnableWebSocketMessageBroker
3public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
4
5 @Override
6 public void registerStompEndpoints(StompEndpointRegistry registry) {
7 registry.addEndpoint("/ws")
8 .setAllowedOriginPatterns("https://app.example.com")
9 .withSockJS();
10 }
11
12 @Override
13 public void configureMessageBroker(MessageBrokerRegistry registry) {
14 registry.setApplicationDestinationPrefixes("/app");
15 registry.enableSimpleBroker("/topic", "/queue");
16 registry.setUserDestinationPrefix("/user");
17 }
18}
19
20@Controller
21public class ChatController {
22
23 private final SimpMessagingTemplate messagingTemplate;
24
25 public ChatController(SimpMessagingTemplate messagingTemplate) {
26 this.messagingTemplate = messagingTemplate;
27 }
28
29 @MessageMapping("/rooms/{roomId}/send")
30 public void handleMessage(@DestinationVariable String roomId,
31 @Payload ChatMessage message,
32 Principal principal) {
33 var outgoing = new ChatMessage(
34 principal.getName(),
35 message.content(),
36 Instant.now());
37
38 messagingTemplate.convertAndSend("/topic/rooms/" + roomId, outgoing);
39 }
40
41 @EventListener
42 public void onDisconnect(SessionDisconnectEvent event) {
43 var accessor = StompHeaderAccessor.wrap(event.getMessage());
44 String user = accessor.getUser() != null ? accessor.getUser().getName() : "unknown";
45 messagingTemplate.convertAndSend("/topic/presence",
46 Map.of("user", user, "status", "OFFLINE"));
47 }
48}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A message broker with destination prefixes cleanly separates client-to-server calls from server-to-client broadcasts.
- 2SimpMessagingTemplate lets any Spring bean push messages to subscribers without holding a socket reference.
- 3Listening for lifecycle events like disconnects turns raw connection state into meaningful presence signals.
Related explainers
php
<?php namespace App\Http\Controllers;
Server-Sent Events in Laravel
server-sent-events
streaming
long-polling
Advanced
9 steps
java
@Configuration @EnableRedisHttpSession(namespace = "myapp:sessions", maxInactiveIntervalInSeconds = 1800, flushMode = FlushMode.IMMEDIATE) public class SessionConfig {
Backing HTTP sessions with Redis in Spring
session-management
redis
distributed-state
Intermediate
7 steps
java
public List<User> findUsersByEmailDomain(String domain, int minAge) { String sql = """ SELECT id, username, email, age, created_at FROM users
Safe parameterized JDBC queries in Java
jdbc
sql-injection
prepared-statement
Intermediate
7 steps
java
@Configuration @EnableBatchProcessing public class CustomerImportJobConfig {
How a chunk-based CSV import job works in Spring
batch-processing
etl
csv-parsing
Intermediate
9 steps
java
@Configuration @EnableWebSecurity public class ResourceServerConfig {
Configuring a JWT resource server in Spring
oauth2
jwt
authorization
Intermediate
8 steps
java
@Configuration public class OrderConsumerConfig { @Bean
Wiring a resilient Kafka consumer in Spring
kafka
deserialization
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/real-time-chat-over-stomp-websockets-in-spring-explained-java-8fba/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.