如何使用 spring websocket 实现访问 @MessageMapping 方法中的请求对象

How to access request object in @MessageMapping method with spring websocket implementation

我正在将现有的 spring MVC 网络应用程序与 spring websockets 集成。我按照

中的说明成功集成

https://spring.io/guides/gs/messaging-stomp-websocket/

现有的网络应用程序有一个过滤器,它设置了一些属性。我需要访问控制器中过滤器设置的属性,即在 @MessageMapping 方法中。

有人能告诉我们如何在@MessageMapping 方法中访问请求对象吗?

当 STOMP 客户端连接到应用程序时,它首先必须请求协议升级以切换到 websocket。使用该 websocket 连接后,消息 sent/received 不会通过您的常规 Servlet 过滤器 - 只有第一个 HTTP 请求("Handshake")会。

根据您的用例,有多种方法可以实现此目的。

如果它与身份验证相关,则 there are existing features for this 在 Spring 框架中,但也在 Spring 安全性中。

如果它与 HTTP 会话相关,您可以轻松地要求将所有 HTTP 会话属性复制到 websocket 会话中 - 或者甚至根据您自己的需要自定义握手 (see reference doc). Once done, you can inject the Websocket scope in a @MessageMapping controller method and get those attributes (see reference doc)。