Spring Websocket教程告诉我,如果我想处理STOMP SEND命令,我将使用(http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html)
@Controller
public class GreetingController {
@MessageMapping("/greeting") {
public String handle(String greeting) {
return "[" + getTimestamp() + ": " + greeting;
}
}
我还需要知道哪个Websocket会话正在发送这个,以便像
那样进行检查if (sessionIsAllowedToDoThings(sessionData)) {...}
我如何获得此示例的Websocket Session数据?
答案 0 :(得分:1)
好吧,您可以通过将org.springframework.messaging.simp.stomp.StompHeaderAccessor
参数添加到handle(String)
方法handle(String, StompHeaderAccessor)
中来获取websocket的会话ID(和其他字段)。
如果您想访问真实的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属性中。通过传递到StompHeaderAccessor
方法的handle(String, StompHeaderAccessor)
可使用这些属性。