Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching Jersey REST service programmatically to Jetty

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'  
}
like image 713
Pierre-Antoine Avatar asked Dec 05 '25 14:12

Pierre-Antoine


1 Answers

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

like image 139
Paul Samsotha Avatar answered Dec 07 '25 04:12

Paul Samsotha