好吧,您可以通过在您的handle(String) 方法中添加org.springframework.messaging.simp.stomp.StompHeaderAccessor 参数来获取websocket 的会话ID(和其他字段):handle(String, StompHeaderAccessor)。
如果你想访问你真正的JSESSIONID 属性,你必须像这样创建org.springframework.web.socket.server.HandshakeInterceptor 的实现(它是用Kotlin 编写的):
class HttpHandshakeInterceptor : HandshakeInterceptor {
companion object {
const val ATTRIBUTE_SESSION_ID = "sessionId"
}
override fun beforeHandshake(request: ServerHttpRequest, response: ServerHttpResponse, wsHandler: WebSocketHandler, attributes: MutableMap<String, Any>): Boolean {
attributes[ATTRIBUTE_SESSION_ID] = (request as ServletServerHttpRequest).servletRequest.session.id
return true
}
override fun afterHandshake(request: ServerHttpRequest, response: ServerHttpResponse, wsHandler: WebSocketHandler, exception: Exception?) {}
}
并在您的org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer 中注册,如下所示:
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
registry.addEndpoint("/endpoint").addInterceptors(httpHandshakeInterceptor)
}
这里的主要思想是您拦截初始握手并将真实会话 ID 存储在 websocket 属性中。这些属性可通过您传递给handle(String, StompHeaderAccessor) 方法的StompHeaderAccessor 获得。