我有一个使用stomp的简单Web套接字应用程序。当用户访问页面时,它将自动建立到服务器的连接。通过spring安全性对用户进行身份验证。当用户关闭浏览器时,我希望用户自动注销。为此,我创建了一个监听器来监听SessionDisconnectEvent。问题是我没有与websocket session 关联的httpSession的句柄?是否想从websocket session 获取httpsession?

这是我的代码:

<websocket:message-broker application-destination-prefix="/test">

        <websocket:stomp-endpoint path="/sbapp">
            <websocket:handshake-interceptors>
                <bean class="com.sample.HttpSessionIdHandshakeInterceptor"></bean>
            </websocket:handshake-interceptors>
            <websocket:sockjs />
        </websocket:stomp-endpoint>
        <websocket:stomp-broker-relay prefix="/topic,/queue,/user" relay-host="localhost" relay-port="61613"/>
    </websocket:message-broker>

这是我的websocket session 监听器:
@Component
public class StompDisconnectListener implements ApplicationListener<SessionDisconnectEvent>{

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {

        System.out.println("Stomp disconnect: " + event.getSessionId());
    }
}

我需要一种方法,当我得到一个断开连接事件时,我得到相应的HttpSession,然后手动注销HttpSession。这可能吗?

最佳答案

现在,Spring Session支持WebSockets。按照this guide将其添加到您的项目中。然后,在您的SessionDisconnectEvent监听器中,您可以通过以下方式获取HttpSessionID:

import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

public class WebSocketDisconnectHandler<S>
    implements ApplicationListener<SessionDisconnectEvent> {

    public void onApplicationEvent(SessionDisconnectEvent event) {
    String session = SimpMessageHeaderAccessor.getSessionAttributes(event.getMessage().getHeaders()).get("HTTP.SESSION.ID").toString();
    }
}

(您可以访问的其他 header 值:)
headers {simpMessageType=CONNECT, stompCommand=CONNECT, nativeHeaders={X-XSRF-TOKEN=[cb73273e-bff3-4eb7-965d-4c696e22c25a], accept-version=[1.1,1.0], heart-beat=[10000,10000]}, simpSessionAttributes={HTTP.SESSION.ID=6dd63204-d5ec-4362-8f37-29af5605298d, org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@10b64145, org.springframework.security.web.csrf.CsrfToken=org.springframework.security.web.csrf.DefaultCsrfToken@10b64145}, simpHeartbeat=[J@3955ead4, simpSessionId=3x25c1e5}
确保在扩展ExpiringSession的WebSocket配置文件中将其注册为Bean:
import your.package.WebSocketDisconnectHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.ExpiringSession;

@Configuration
public class WebSocketHandlersConfig<S extends ExpiringSession> {

    @Bean
    public WebSocketDisconnectHandler<S> webSocketDisconnectHandler() {
        return new WebSocketDisconnectHandler<S>();
    }
}

关于spring-mvc - 在 Spring 获取Websocket session 的关联HTTPSession,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27119495/

10-09 21:35