Search code examples
javastompspring-websocketstomp-websocket

Stomp Interceptor not working


I am using Spring WebSockets. It works well, but I now have a case where I need to modify a message before it is sent to the web client.

Therefore I created the following Interceptor:

@Component
public class StompMappingInterceptor extends ChannelInterceptorAdapter {

  @Override
  public Message<?> preSend(Message<?> message, MessageChannel channel) {
        message = MessageBuilder.withPayload(modifyMessage(message))
                .copyHeaders(message.getHeaders())
                .build();
        return message;
    ...
}

modifyMessage()should use a MappingJackson2MessageConverter, but for testing, I am not at all modifying the message:

private Message<?> modifyMessage(Message<?> message) {
    return message;
}

However, the message is never received at the Webclient.

When I change the preSend() method to:

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
  return message;
}

then it works well, so this seems to be an issue of my preSend() method and the way I create a new message. What am I doing wrong?


Solution

  • The new message must be created as follows:

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
    
        Message<?> newMessage = MessageBuilder.createMessage(modifyMessage(message),
        headerAccessor.getMessageHeaders());
        return message;
        ...
    }
    

    The difference is that this way, the message header does NOT contain the following fields:

    • id
    • contentType
    • timestamp

    For some reason unknown to me, this prevented the web client from receiving the message.