以编程方式将 Jersey REST 服务附加到 Jetty

Pie*_*ine 3 java rest jetty jersey gradle

是否可以以编程方式将 Jersey RESTful 服务附加到 Jetty 运行程序?我不清楚如何从 Web 服务类中创建 Servlet 对象。

换句话说,是否可以在没有web.xml文件的情况下创建 Jersey Web 服务并将其附加到我们自己实例化的服务器?

网络服务

@Path("/hello")
public class HelloWebapp {
    @GET()
    public String hello() {
        return "Hi !";
    }
}
Run Code Online (Sandbox Code Playgroud)

码头跑者

public class JettyEmbeddedRunner {
    public void startServer() {
        try {
            Server server = new Server();

            ServletContextHandler context = new ServletContextHandler();
            context.setContextPath("/test");

            new ServletContextHandler(server, "/app", true, false) {{
                addServlet(new ServletHolder(HelloWorldServlet.class), "/world");
            }};

            server.addConnector(new ServerConnector(server) {{
                 setIdleTimeout(1000);
                 setAcceptQueueSize(10);
                 setPort(8080);
                 setHost("localhost");
            }});
            server.start();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Gradle 依赖项

dependencies {
    compile 'org.eclipse.jetty:jetty-server:9.0.0.RC2'
    compile 'org.eclipse.jetty:jetty-servlet:9.0.0.RC2'
    compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.14'  
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*tha 5

正如您在 web.xml 中使用的那样

<servlet>
    <servlet-name>Jersey App</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    ...
</sevlet>
Run Code Online (Sandbox Code Playgroud)

您也可以ServletContainer独立使用。

ResourceConfig config = new ResourceConfig();
config.packages("...");
ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(config));
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看完整的示例

  • 谢谢!对于未来阅读这个问题的人。servlet 需要附加: `context.addServlet(jerseyServlet, "/*");` (3认同)