5

我正在使用带有 Spring MVC 框架的 Websockets SockJS。我尝试了运行良好的 Stock Ticker 示例,但现在我想在我的控制器中获取 Session 但我无法找到出路。

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.
4

2 回答 2

7

如果您指的是 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
    ...
}
于 2014-09-17T16:10:48.890 回答
3

我也认为你需要一个拦截器,sessionAttributes没有它你会变得空虚。

您需要添加HttpSessionHandshakeInterceptordispatcher-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(...);
}
于 2015-05-20T15:08:53.117 回答