【问题标题】:Mapping websockets endpoints at runtime在运行时映射 websockets 端点
【发布时间】:2015-10-16 21:27:04
【问题描述】:

我知道从 servlet api 3.0 开始我们可以在运行时映射一个 servlet,可以如下实现:

@Override
public void contextInitialized( ServletContextEvent sce ) {
    ServletContext sc = sce.getServletContext();

    String servletMapping = "/yourURL";
    ServletRegistration sr = sc.addServlet( servletMapping, "org.yourdomain.yourclass" );
    sr.setInitParameter( "key", "value" );
    sr.addMapping( servletMapping );
}

是否有类似的方式使用 websockets(使用 javax.websockets.api)?

【问题讨论】:

    标签: java jakarta-ee websocket


    【解决方案1】:

    ServletContainerInitializer 的 Websocket 等效项是 ServerApplicationConfig。它只是不需要服务文件,Websocket API 将主动扫描 WAR 和 WAR 中的 JAR 以查找任何实现 ServerApplicationConfig 接口的类并使用它们。您可以在getEndpointConfigs() 中使用ServerEndpointConfig.Builder 以编程方式构建Websocket 端点并返回它。

    这是一个启动示例,假设 YourEndpoint.class 表示您希望以编程方式添加的 Websocket 端点,并且您希望忽略任何扫描的类。

    public class YourServerApplicationConfig implements ServerApplicationConfig {
    
        @Override
        public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> scannedClasses) {
            Set<ServerEndpointConfig> configs = new HashSet<>();
            configs.add(ServerEndpointConfig.Builder.create(YourEndpoint.class, "/yourPath").build());
            return configs;
        }
    
        @Override
        public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scannedClasses) {
            return Collections.emptySet();
        }
    
    }
    

    【讨论】:

    • 是的,我知道,但我真正追求的是一种在运行时更改端点的方法,对于 servlet,我保留对 servlet 上下文的引用,并且可以在运行时随时添加 servlet。 ServerAppllicationConfig 方法只在启动时被调用,对吗?
    • 在上下文初始化后不允许添加/删除 servlet。它会抛出 ISE。所以,没有什么不同。
    • 哎呀...我指望在初始化后能够更改映射。你是对的,它不起作用。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 2017-02-07
    相关资源
    最近更新 更多