spring websocket 5327 ServerEndpoint 携带参数在路径中
在 Spring WebSocket 5.3.27 中,可以使用 @ServerEndpoint 注解来创建一个 WebSocket 服务器端点。如果需要在路径中携带参数,可以在 @ServerEndpoint 注解中使用 {paramName} 的形式来指定参数名,并在实现类中使用 @PathParam 注解来获取参数值。
例如,以下代码演示了如何在路径中携带一个名为 "userId" 的参数:
@ServerEndpoint("/chat/{userId}")
public class ChatEndpoint {
private String userId;
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.userId = userId;
// ...
}
// ...
}
在上面的代码中,@ServerEndpoint 注解指定了路径为 "/chat/{userId}",其中 {userId} 表示要在路径中携带一个名为 "userId" 的参数。在实现类中,使用 @PathParam("userId") 注解来获取参数值,并存储在类的成员变量中,以便在后续的方法中使用。
注意,@PathParam 注解只能用于方法参数上,不能用于类成员变量上。如果需要在类中存储路径参数的值,可以在方法中将其存储在成员变量中
原文地址: https://www.cveoy.top/t/topic/cpFo 著作权归作者所有。请勿转载和采集!