我知道我们可以在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)?
I know we can map a servlet at runtime since servlet api 3.0, that can be achieved as below:
@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 ); }Is there a similar way of doing this with websockets (using javax.websockets.api)?
最满意答案
ServletContainerInitializer的Websocket相当于ServerApplicationConfig 。 它只需要一个服务文件,Websocket API将主动扫描WAR中的WAR和JAR,以实现ServerApplicationConfig接口的任何类并使用它们。 您可以在getEndpointConfigs()使用ServerEndpointConfig.Builder以编程方式构建Websocket端点并将其返回。
以下是一个YourEndpoint.class例子,假设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(); } }The Websocket equivalent of ServletContainerInitializer is the ServerApplicationConfig. It only doesn't require a services file, the Websocket API will proactively scan the WAR and JARs in WAR for any classes implementing ServerApplicationConfig interface and use them. You can in getEndpointConfigs() use ServerEndpointConfig.Builder to programmatically build a Websocket endpoint and return it.
Here's a kickoff example, given that YourEndpoint.class represents the Websocket endpoint you'd like to programmatically add, and you'd like to ignore any scanned classes.
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(); } }更多推荐
发布评论