我正在使用带有Spring MVC Framework的Websockets SockJS。我尝试了股票代码示例工作正常,但现在我想在我的控制器中获取会话,但我无法找到出路。
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.
答案 0 :(得分:6)
如果您指的是WebSocket会话,Spring 4.1允许您在传入客户端消息的标头中获取会话属性,可以通过SimpMessageHeaderAccessor
访问。
@MessageMapping("/topic/agent-sendstatus")
public void testmethod(SimpMessageHeaderAccessor headerAccessor) {
String sessionId = headerAccessor.getSessionId(); // Session ID
Map<String, Object> attrs = headerAccessor.getSessionAttributes(); // Session Attributes
...
}
答案 1 :(得分:3)
我还认为你需要一个拦截器,没有它你会得到空sessionAttributes
。
您需要在HttpSessionHandshakeInterceptor
:
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>
然后你就可以在控制器中获得会话了:
@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(...);
}