Targeted Messaging to Specific Users
Send private, per-user messages over STOMP using user destinations, @SendToUser, and SimpMessagingTemplate.convertAndSendToUser.
Targeted Messaging to Specific Users is a free WebSockets & Real-Time Systems with Spring lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the WebSockets & Real-Time Systems with Spring learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Beyond Broadcasts
So far messages went to a /topic that every subscriber receives. Real apps also need private messages: a chat whisper, a personal notification, an order update for one customer.
User Destinations
Spring supports the /user destination prefix. When a client subscribes to /user/queue/notifications, Spring rewrites it to a unique, per-session queue so only that user gets the message.
Where the Principal Comes From
Targeted messaging needs to know who a session is. The Principal attached during the handshake (from Spring Security or a custom handshake handler) provides the username key.
Sending with @SendToUser
In a controller method you annotate with @SendToUser. The return value is delivered only to the user who sent the triggering message.
@MessageMapping("/private")
@SendToUser("/queue/reply")
public Note handle(Note in, Principal principal) {
return new Note("Hi " + principal.getName());
}The Client Subscription
The client subscribes to the /user-prefixed destination. Spring resolves it to that client's private queue automatically.
stompClient.subscribe('/user/queue/reply', (msg) => {
console.log('Private:', JSON.parse(msg.body));
});Pushing from Anywhere with the Template
Outside a controller (e.g. from a service or scheduled job) use SimpMessagingTemplate.convertAndSendToUser to reach a specific user by name.
messagingTemplate.convertAndSendToUser(
"alice", "/queue/notifications", new Alert("Payment received"));How Resolution Works
The UserDestinationMessageHandler maps /user/{username}/queue/x to the actual session-specific destination. You address users by name; Spring finds their active sessions.
Multiple Sessions per User
One user may be connected from a phone and a laptop. convertAndSendToUser delivers to all of that user's active sessions, so notifications appear everywhere they are logged in.
Targeting a Single Session
To reach just one device, pass headers selecting a specific simpSessionId rather than broadcasting to every session of the user.
SimpMessageHeaderAccessor h = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
h.setSessionId(sessionId);
h.setLeaveMutable(true);
messagingTemplate.convertAndSendToUser(user, "/queue/reply", body, h.getMessageHeaders());User Destinations Across a Cluster
With a single server the simple broker resolves user destinations in-memory. Across multiple nodes you need an external broker (RabbitMQ) plus a UserRegistry broadcast so a node can route to a user connected elsewhere.
Security Note
Never let a client choose another user's destination. Always derive the target from the authenticated Principal, not from client-supplied data, to prevent message hijacking.
Quick Check
Test your knowledge of per-user messaging.
Recap
You delivered private messages:
- The
/userprefix maps to per-session queues @SendToUserreplies to the originating userconvertAndSendToUserpushes to a named user from anywhere- Multiple sessions per user are reached together; target one with session headers
- Always derive the target from the authenticated
Principal
Frequently asked questions
Is the “Targeted Messaging to Specific Users” lesson free?
Yes — the full text of “Targeted Messaging to Specific Users” is free to read here on the web, and the WebSockets & Real-Time Systems with Spring course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the WebSockets & Real-Time Systems with Spring course, upgrade to CoddyKit PRO.
What will I learn in “Targeted Messaging to Specific Users”?
Send private, per-user messages over STOMP using user destinations, @SendToUser, and SimpMessagingTemplate.convertAndSendToUser. You practise WebSockets & Real-Time Systems with Spring with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start WebSockets & Real-Time Systems with Spring?
No prior experience is required. WebSockets & Real-Time Systems with Spring on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Targeted Messaging to Specific Users” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this WebSockets & Real-Time Systems with Spring lesson?
Yes. Every WebSockets & Real-Time Systems with Spring lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- WebSocket Interceptors
- Message Converters Customization
- User Session Management
- Targeted Messaging to Specific Users