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
...
 <org.eclipse.jetty.version>9.0.6.v20130930</org.eclipse.jetty.version>
...
 
    org.eclipse.jetty
    jetty-webapp
    ${org.eclipse.jetty.version}
 
...
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;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;


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.setContextPath("/");
        context.addServlet(servletHolder, AppConfig.API_BASE);
        context.addEventListener(new ContextLoaderListener());

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

        server.setHandler(context);
        server.start();
        server.join();
    }
}



   You can find sources on GitHub

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

No comments:

Post a Comment