2

this is my first experience with websockets and I am still adjusting to springboot. I was following this tutorial https://www.callicoder.com/spring-boot-websocket-chat-example/ and had it running fine.

However I made some adjustments to the code and added a new model ChatUser. When I attempt to send a message using stompClient the frontend populates a model and sends it to the backend, however on the java side the model is full of null values. Please explain why this is happening. If I attempt to receive a string or a ChatMessage (original model from tutorial) the model is populated fine.

Backend Message Handler

@MessageMapping("/chat.addUser")
@SendTo("/topic/public")
public ChatUser addUser(@Payload ChatUser user, SimpMessageHeaderAccessor headerAccessor) {
    //add username in web socket session
    ChatService service = new ChatService();
    if(user.getId() == null) {
        service.incrementId();
        user.setId(service.getNewId());
    }
    user.setStatus(Status.ACTIVE);
    service.addActiveUsers(user);
    headerAccessor.getSessionAttributes().put(Constants.USERID, user.getId());
    headerAccessor.getSessionAttributes().put(Constants.USERNAME, user.getUserName());
    return user;
}

UI

    stompClient.send("/app/chat.addUser",
    {},
    JSON.stringify({user: username})
)

I made the model in the UI simpler to see if I could populate just the username, however it still returned a null value. It also failed when removing @Payload.

ChatUser Model

package com.webchatapp.webchatapplication.model;

public class ChatUser {
private String user;
private Integer id;
private Status type;
private ChatMessage message;

public enum Status{
    ACTIVE,
    DISCONNECTED
}
public String getUserName() {
    return user;
}
public void setUserName(String user) {
    this.user = user;
}
public Integer getId() {
    return id;
}
public void setChatMessage(ChatMessage message) {
    this.message = message;
}
public ChatMessage getChatMessage() {
    return message;
}
public void setId(Integer id) {
    this.id = id;
}
public Status getStatus() {
    return type;
}
public void setStatus(Status type) {
    this.type = type;
}

}

Kevin Haro
  • 21
  • 1

0 Answers0