Damion Brown's Blog

D97A 07F3 DCB1 302D

Java REST API with JAX-RS, Jetty, and Jersey


  • Thu 22 March 2018
  • Tech

Utalizing JAX-RS, Jetty, and Jersey it's possible to create a lightweight RESTful server in no time.

This code produces a standalone JAR file.

Github repo of the full working sourcecode can be found here.


Application.java: (Source)

static Server startServer() throws IOException {

        // Construct a Jetty Server
        final Server server = new Server(new InetSocketAddress("127.0.0.1", 8080));

        // Jetty Context Handler
        ServletContextHandler handler = new ServletContextHandler();

        // Jetty ServletHolder contain a Jersey ServletContainer containing our JAX-RS Application.
        ServletHolder helloWorldServlet = new ServletHolder(new ServletContainer(new JaxRsApp()));

        // Adding the Servlet to the Context Handler
        handler.addServlet(helloWorldServlet, "/app1/*");

        // Adding the Context Handler to the Jetty Server
        server.setHandler(handler);

        // start the server
        try {
                server.start();
                server.join();
        } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        };

        return server;
}

JaxRsApp.java: (Source)

@ApplicationPath("/")
public class JaxRsApp extends Application {
        private final Set<Class<?>> classes;

        public JaxRsApp() {
                HashSet<Class<?>> c = new HashSet<Class<?>>();
                c.add(HelloWorld.class);
                classes = Collections.unmodifiableSet(c);
        }

        @Override
        public Set<Class<?>> getClasses() {
                return classes;
        }

}

HelloWorld.java: (Source)

@Path("/")
public class HelloWorld {
        @GET
        @Path("helloworld")
        @Produces(MediaType.TEXT_PLAIN)
        public String helloworld() {
                return "Hello World!";
        }
}