Video in progress

Which arguments can a `@MessageMapping("/room.{id}.send")` method take, and how do you validate the incoming payload?

The payload (with or without @Payload), @DestinationVariable, @Header/@Headers, Principal, SimpMessageHeaderAccessor and the Message itself. For validation you put @Valid or @Validated on the payload, and the error arrives as a MethodArgumentNotValidException in your @MessageExceptionHandler.

📖 Answer

The signature looks like a REST controller, just with different annotations:

@MessageMapping("/room.{id}.send")
@SendTo("/topic/room.{id}")
public ChatMessage send(@DestinationVariable long id,
                        @Valid @Payload SendRequest req,
                        @Header(name = "client-msg-id", required = false) String clientMsgId,
                        Principal user,
                        SimpMessageHeaderAccessor acc) {
    String ip = (String) acc.getSessionAttributes().get("ip");
    return chat.post(id, user.getName(), req.text(), clientMsgId);
}

record SendRequest(@NotBlank @Size(max = 2000) String text) {}

Note that the {id} inside @SendTo("/topic/room.{id}") is filled from the same destination variable.

@Header is a native STOMP header sent by the client (client-msg-id). @Headers Map<String, Object> gives all the headers, but it includes Spring's internal headers too, and the native ones sit inside nativeHeaders.

For validation to work it's enough to have Hibernate Validator on the classpath (spring-boot-starter-validation in Spring Boot); messaging builds its own validator from it. Without @Valid, @NotBlank does nothing and empty messages quietly end up in the database.

Returning the error to the client:

@MessageExceptionHandler(MethodArgumentNotValidException.class)
@SendToUser(destinations = "/queue/errors", broadcast = false)
public ErrorDto invalid(MethodArgumentNotValidException ex) {
    return ErrorDto.from(ex.getBindingResult());
}

Here MethodArgumentNotValidException is the one from the org.springframework.messaging.handler.annotation.support package, not the MVC one. If you pick the wrong import, the handler never gets called.