WebSocket @ServerEndpoint 注解传递参数方法
在使用 @ServerEndpoint 注解的 WebSocket 服务器端点中,无法直接携带参数。但是,可以通过以下方法解决这个问题:
-
将参数作为查询字符串传递。例如:
ws://localhost:8080/websocket?param1=value1¶m2=value2 -
在 WebSocket 连接建立后使用
WebSocketSession的getQueryString()方法获取查询字符串,然后解析参数。 -
将参数存储在
HttpSession中,然后在 WebSocket 连接建立时从HttpSession中获取参数。
例如,以下代码演示了如何从 HttpSession 中获取参数:
@ServerEndpoint("/websocket")
public class MyWebSocket {
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
String param1 = (String) httpSession.getAttribute('param1');
String param2 = (String) httpSession.getAttribute('param2');
// do something with the parameters
}
// other WebSocket methods
}
在使用 WebSocket 时,需要在建立连接之前将参数存储在 HttpSession 中:
HttpSession httpSession = request.getSession();
httpSession.setAttribute('param1', 'value1');
httpSession.setAttribute('param2', 'value2');
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(MyWebSocket.class, URI.create('ws://localhost:8080/websocket'));
原文地址: https://www.cveoy.top/t/topic/nvbp 著作权归作者所有。请勿转载和采集!