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/cpEP 著作权归作者所有。请勿转载和采集!