Container-Agnostic Websocket throws NPE with Embedded Jetty

丶灬走出姿态 提交于 2019-12-07 12:44:30

The JSR ServerContainer isn't initialized automatically in embedded-jetty.

Use the WebSocketServerContainerInitializer ...

WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setResourceBase(webroot);   
webapp.setDescriptor(webroot + "/WEB-INF/web.xml");

Server server = new Server();

ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);             

server.setConnectors(new ServerConnector[] { connector });
server.setHandler(webapp);

// Add this line
WebSocketServerContainerInitializer.configureContext(webapp);

server.start();
server.join();

Note: The WebSocketServerContainerInitializer is a javax.servlet.ServerContainerInitializer and you could set up your embedded-jetty to execute that ServerContainerInitializer automatically.

If you heavily rely on bytecode scanning of annotations, or have a javax.websocket.server.ServerApplicationConfig implementation, then you'll want to have the ServerContainerInitializer execute automatically.

Note: the javax.servlet.ServerContainerInitializer is only valid for a org.eclipse.jetty.webapp.WebAppContext.

If you use the org.eclipse.jetty.servlet.ServletContextHandler (the more common form in embedded-jetty) then you cannot use a javax.servlet.ServerContainerInitializer.

To set that up, do this:

private void enableAnnotationScanning(Server server)
{
    Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
    classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration",
            "org.eclipse.jetty.plus.webapp.EnvConfiguration",
            "org.eclipse.jetty.plus.webapp.PlusConfiguration");
    classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
            "org.eclipse.jetty.annotations.AnnotationConfiguration");
}

// ... later on ...

Server server = new Server();
enableAnnotationScanning(server);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!