3

Is it possible to attach a Jersey RESTful service to a Jetty runner programmatically? It is not clear to me how to create a Servlet object out of the web service class.

In other words, is it possible to create a Jersey web service without a web.xml file and attach it to a server that we would have instantiated ourselves?

Web Service

@Path("/hello")
public class HelloWebapp {
    @GET()
    public String hello() {
        return "Hi !";
    }
}

Jetty Runner

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();
        }
    }
}

Gradle dependencies

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'  
}
Pierre-Antoine
  • 7,939
  • 6
  • 28
  • 36

1 Answers1

5

Just as you would use in a web.xml

<servlet>
    <servlet-name>Jersey App</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    ...
</sevlet>

You can also use the ServletContainer for a standalone.

ResourceConfig config = new ResourceConfig();
config.packages("...");
ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(config));

You can see a full example here

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • 3
    Thanks! For future people reading this question. The servlet needs to be attached with: `context.addServlet(jerseyServlet, "/*");` – Pierre-Antoine Feb 22 '15 at 16:26