Can't get session in Spring Controller when using Webs
I am using Websockets SockJS with Spring MVC Framework. I tried the Stock Ticker example, which works fine, but now I want to get Session in my controller, but I cannot 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.
source to share
If you are referencing a WebSocket session, Spring 4.1 allows you to get the session attributes in the header of the client's incoming messages, which can be accessed through SimpMessageHeaderAccessor
.
@MessageMapping("/topic/agent-sendstatus")
public void testmethod(SimpMessageHeaderAccessor headerAccessor) {
String sessionId = headerAccessor.getSessionId(); // Session ID
Map<String, Object> attrs = headerAccessor.getSessionAttributes(); // Session Attributes
...
}
source to share
I also think you need an interceptor, you get empty sessionAttributes
without it.
You need to add HttpSessionHandshakeInterceptor
to dispatcher-servlet.xml
:
<websocket:message-broker
application-destination-prefix="/app"
user-destination-prefix="/user">
<websocket:stomp-endpoint path="/websocket">
<websocket:handshake-interceptors>
<bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"/>
</websocket:handshake-interceptors>
<websocket:sockjs session-cookie-needed="true" />
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic, /message" />
</websocket:message-broker>
And then you should be able to get the session in the controller:
@MessageMapping("/authorization.action")
public Message authorizationAction(
SimpMessageHeaderAccessor headerAccessor, Message message) {
Map<String, Object> sessionAttributes = headerAccessor.getSessionAttributes();
System.out.println(sessionAttributes);
// Do something with session
return new Message(...);
}
source to share