Solace
Solace

Reputation: 2189

Java Spring STOMP MessageMapping not being called

I am trying to have my websocket client (browser) send a message to my server. The server should catch the message with a @MessageMapping annotation like so:

@Controller
public class GameController {

    @MessageMapping("/game/{id}")
    public void onMessage(@DestinationVariable String id,Message message) {
        System.out.println("reached");
        System.out.println(id);
        System.out.println(message);
    }

}

The above snippet works fine as the "Message" object is from org.springframework.messaging.Message.

However, when I try to convert the incoming message to my own POJO like so:

@MessageMapping("/game/{id}")
    public void onMessage(@DestinationVariable String id,ChatMessage message) {
        System.out.println("reached");
        System.out.println(id);
        System.out.println(message);
}

The function is no longer being called. After reading this tutorial it looks like we are allowed to define our POJOs to encapsulate JSON strings and @MessageMapping should automatically convert the JSON to our custom Java objects, but it is not working for me (message mapping function is not being called).

I was wondering if anyone can point me in the general direction of where the problem might be. Something to note is that the tutorial used Spring Boot, but I am using Spring MVC. I suspect that SpringBoot may have some auto-configuration property that I do not have, but I have tried configuring my own Jackson ObjectMapper and registering it inside WebSocketConfig (did not work).

Any help would be appreciated

Upvotes: 5

Views: 3563

Answers (1)

Solace
Solace

Reputation: 2189

So instead of using my own object as a parameter, I was supposed to use it as a generic type like so:

@MessageMapping("/game/{id}")
public void onMessage(@DestinationVariable String id,Message<ChatMessage> message) {
        //Now we can get our ChatMessage object like so
        ChatMessage m = message.getPayload();
}

Where ChatMessage is your custom object that maps to your JSON input

Upvotes: 3

Related Questions