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'
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With