【问题标题】:Mapping WebSocketEndpoints in a web.xml file在 web.xml 文件中映射 WebSocketEndpoints
【发布时间】:2013-12-06 07:49:48
【问题描述】:

我正在尝试开发一个使用 websocket 端点的 Java EE 7 Web 应用程序并将其部署在 Jetty 服务器上。

应用程序具有以下结构:

Game/
  src/
    main/
      java/
        game/
          WebSocketEndpoint.java
      webapp/
        index.html
        scripts/
          variousjavascriptstuff.js
        WEB-INF/
          beans.xml
          web.xml

在 beans.xml 文件中:

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="annotated">

WebSocketEndpoint 已正确注释并且可以与 Netbeans/Glassfish4 一起正常工作,但是,应用程序必须部署在 Jetty 服务器上。

所以,我的问题 - 如何将 websocket 端点映射到 web.xml 文件中的 URL /game?我找到了许多映射 servlet 的示例,但我认为这不适用于服务器端点。

或者,有没有办法为Jetty写一个web.xml文件,让它自动发现ll注解的类/方法(类似于上面的beans.xml)

【问题讨论】:

    标签: java jakarta-ee web-applications jetty java-ee-7


    【解决方案1】:

    假设您已使用 JSR-356 技术注释 game.WebSocketEndpoint ...

    例子:

    package game;
    
    import javax.websocket.server.ServerEndpoint
    
    @ServerEndpoint("/game")
    public class WebSocketEndpoint {
    
    }
    

    那么你必须做以下...

    1. 使用Jetty 9.1+
    2. Enable the 'websocket' module(将--module=websocket 添加到您的start.ini 或命令行)

    这将启用 websocket 服务器类 + 对 websocket 端点的注释扫描。

    注意:JSR-356 并不意味着通过部署描述符 (web.xml) 进行映射。

    但是,您可以使用以下技术之一以编程方式映射您的端点:

    1. 创建一个javax.servlet.ServletContextListener,通过javax.websocket.server.ServerContainer 手动添加端点(方法见下文)
    2. 创建一个javax.servlet.ServerContainerInitializer,通过javax.websocket.server.ServerContainer 手动添加端点(方法见下文)
    3. 创建一个javax.websocket.server.ServerAppliationConfig,返回您要添加的端点。

    注意:技术#2 和#3 都需要对注释进行类扫描(启动缓慢)。技巧 #1 是快速启动。

    如何手动添加端点

    // Get a reference to the ServerContainer
    javax.websocket.server.ServerContainer ServerContainer =
      (javax.websocket.server.ServerContainer)
      servletContext.getAttribute("javax.websocket.server.ServerContainer");
    // Add endpoint manually to server container
    serverContainer.addEndpoint(game.WebSocketEndpoint.class);
    

    【讨论】:

    • 其他容器呢?我喜欢手动配置,但我发现令人难以置信的是,互联网上没有人提到如何让你的 contianer (tomcat 8) 来检测严重点。没有通用的方法吗?我不喜欢容器特定的解决方案。
    • 上面的代码片段也适用于 Tomcat 8.5(也可能适用于其他 Tomcat)。在javax.websocket.server.ServerContainer 的javadoc 中,提到这是访问ServerContainer 以获取“启用websocket 的Web 容器”的标准过程(参见例如:github.com/eclipse-ee4j/websocket-api/blob/master/api/server/…
    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2013-09-24
    • 2015-03-01
    • 1970-01-01
    相关资源
    最近更新 更多