Monday, October 21, 2013

REST with JAX-RS: Part 3 - Embedded Jetty

See previous posts:
There is one feature which I'd like to add. It's embedded Jetty server. I.e. we should be able to run our application from main() method.

Update pom.xml, add jetty server as dependency
Create special Launcher class which runs embedded Jetty Server. Jetty configuration registers port, host, base REST URL ("/api/*") and the most important - proper Spring config.
package com.halyph;

import com.halyph.config.AppConfig;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;

public class Launcher {

    public static final int PORT = 8080;

    public static void main(final String[] args) throws Exception {
        Server server = new Server(PORT);

        // Register and map the dispatcher servlet
        final ServletHolder servletHolder = new ServletHolder(new CXFServlet());
        final ServletContextHandler context = new ServletContextHandler();
        context.addServlet(servletHolder, AppConfig.API_BASE);
        context.addEventListener(new ContextLoaderListener());

        context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
        context.setInitParameter("contextConfigLocation", AppConfig.class.getName());


   You can find sources on GitHub

  1. Going REST: embedding Jetty with Spring and JAX-RS (Apache CXF)
  2. Embedding Jetty or Tomcat in your Java Application