Unable to get Session in Spring Controller when using Websockets

abcd picture abcd · Sep 15, 2014 · Viewed 7.4k times · Source

I am using Websockets SockJS with Spring MVC Framework. I tried the Stock Ticker example that's working fine but now I want to get Session in my Controller but I am unable to find a way out.

Client Code:
$scope.socket = new SockJS("ws/ws"); 
$scope.stompClient = Stomp.over($scope.socket); 
$scope.stompClient.connect("guest", "guest",connectCallback, errorCallback);

//in connectCallback
$scope.stompClient.subscribe('/topic/agent-sendstatus', showScreenPop);

    Java Code:
    @MessageMapping("/topic/agent-sendstatus")
        public void testmethod()
        {
            //How do i get Session here to further implement solution?

            template.convertAndSend("/topic/agent-sendstatus","bcd");
        }

Please suggest.

Answer

Sergi Almar picture Sergi Almar · Sep 17, 2014

In case you are referring to the WebSocket session, Spring 4.1 lets you get the session attributes in a header of the incoming client messages which can be accessed via the SimpMessageHeaderAccessor.

@MessageMapping("/topic/agent-sendstatus")
public void testmethod(SimpMessageHeaderAccessor headerAccessor) {
    String sessionId = headerAccessor.getSessionId(); // Session ID
    Map<String, Object> attrs = headerAccessor.getSessionAttributes(); // Session Attributes
    ...
}