【问题标题】:Unable to get Session in Spring Controller when using Websockets使用 Websockets 时无法在 Spring Controller 中获取 Session
【发布时间】:2014-09-15 06:27:45
【问题描述】:

我正在使用带有 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.

【问题讨论】:

    标签: session sockjs spring-websocket


    【解决方案1】:

    如果您指的是 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
        ...
    }
    

    【讨论】:

    • 这对我有帮助,虽然我使用的是 Spring 4.0.6,所以我在没有更新 Spring 的情况下尝试了你的解决方案,它可以工作。
    【解决方案2】:

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

    您需要在dispatcher-servlet.xml中添加HttpSessionHandshakeInterceptor

    <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(...);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      相关资源
      最近更新 更多