在使用 @ServerEndpoint 注解的 WebSocket 服务器端点中,无法直接携带参数。但是,可以通过以下方法解决这个问题:

  1. 将参数作为查询字符串传递。例如:ws://localhost:8080/websocket?param1=value1&param2=value2

  2. 在 WebSocket 连接建立后使用 WebSocketSessiongetQueryString() 方法获取查询字符串,然后解析参数。

  3. 将参数存储在 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'));
WebSocket @ServerEndpoint 注解传递参数方法

原文地址: https://www.cveoy.top/t/topic/nvbp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录