在web.xml文件中映射WebSocketEndpoints

Kyl*_*yle 5 java web-applications jetty java-ee java-ee-7

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

该应用程序具有以下结构:

Game/
  src/
    main/
      java/
        game/
          WebSocketEndpoint.java
      webapp/
        index.html
        scripts/
          variousjavascriptstuff.js
        WEB-INF/
          beans.xml
          web.xml
Run Code Online (Sandbox Code Playgroud)

在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">
Run Code Online (Sandbox Code Playgroud)

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

所以,我的问题 - 如何将websocket端点映射到web.xml文件中的URL /游戏?我已经找到了一些映射servlet的例子,但我认为这不适用于服务器端点.

或者,有没有办法为Jetty编写web.xml文件,以便它自动发现ll带注释的类/方法(类似于上面的beans.xml)

Joa*_*elt 8

假设您game.WebSocketEndpoint使用JSR-356技术进行了注释......

例:

package game;

import javax.websocket.server.ServerEndpoint

@ServerEndpoint("/game")
public class WebSocketEndpoint {

}
Run Code Online (Sandbox Code Playgroud)

然后你必须做以下......

  1. 使用Jetty 9.1+
  2. 启用'websocket'模块(添加--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);
Run Code Online (Sandbox Code Playgroud)