7

I have a basic spring websocket application which currently sends basic data to subscribers. Currently the system uses the SimpMessageSendingOperations class as the message handler. If I call SimpMessageSendingOperations.convertAndSend(destination, object) then the object is converted and received by the subscribed clients.

I would like to be able to send a custom header to the clients. I have tried using the SimpMessageSendingOperations.convertAndSend(destination, object, headers) method to do this. However the custom header is not included in the stomp message.

Debugging through the code it looks like StompHeaderAccessor.toStompHeaderMap() method calls toNativeHeaderMap() which uses the native header and the original native header maps to build up the stomp headers.

Is there a way to get a custom header added to stomp message?

Jaimie Whiteside
  • 1,180
  • 9
  • 21

1 Answers1

7

StompHeaderAccessor extends NativeMessageHeaderAccessor which seems to be where the non-stomp headers live, except they are all stored in a single header called nativeHeaders - which itself is a map.

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public  GenericMessage<Greeting> greeting(HelloMessage message) throws Exception {      
    Map<String, List<String>> nativeHeaders = new HashMap<>();
    nativeHeaders.put("hello", Collections.singletonList("world"));

    Map<String,Object> headers = new HashMap<>();
    headers.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, nativeHeaders);

    return new GenericMessage<Greeting>(new Greeting("Hello, " + message.getName() + "!"), headers);
}

A simple interceptor server-side to wrap your custom headers to the nativeHeaders header should be enough to expose them client-side where they would be available as a map message.headers.nativeHeaders. Simmilarly, you could write a client-side interceptor to move the nativeHeaders into the regular headers - so before your client is aware of the message, all the expected headers are simply in the message.headers.

Paul Adamson
  • 2,011
  • 2
  • 18
  • 22
  • Using this I was able to add custom headers by adding a `MessagePostProcessor` parameter to the `convertAndSend` method. The logic within the overriden `postProcessMessage` then adds the native headers as suggested – Jaimie Whiteside Feb 04 '14 at 14:02
  • 1
    hi Jaimie, could you create a request in JIRA to address this? Although you have found a way to do it, it really shouldn't be that hard to figure out. – Rossen Stoyanchev Feb 04 '14 at 14:26
  • Thanks for You Answer! Can You also explain how to GET headers which comes with message to server? – udenfox Apr 14 '15 at 17:54