Adding a Web Application to a Jar-File

I had the job to implement the client side of a web service. To test this implementation I needed a server. I could have used a full-blown JEE server and deploy the server-side of the web service there. I decided against this approach (for several reasons).

Another solution for me would be to use the official test server for the web server. This was not feasible because the test server could be down for several reasons (leaving me with searching for bugs that are outside the scope of my duty) and the data was not reliable and changed regularly so that reliable tests were not reproducible.

I decided to deploy my web service as a simple web application to a simple web server (Jetty in my case). Also I wanted a simple way to deploy my test server/service so I decided to embed the Jetty server into a simple application which I can start with a simple script.

To embed Jetty inside your application there are only a few lines needed:

    Server jetty = new Server();
    List connectors =
        new LinkedList();
    
    Connector connector = new SelectChannelConnector();
    connector.setPort(8080);
    connectors.add(connector);
    jetty.setConnectors(connectors.toArray(
        new Connector[0]));
    
    List handlers = new LinkedList();
    
    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setInitParameter(
        "org.eclipse.jetty.servlet.Default.dirAllowed",
        "false");
    URL warURL = getClass().getProtectionDomain()
        .getCodeSource().getLocation();
    webAppContext.setWar(warURL.toExternalForm());
    webAppContext.setContextPath("/");
    handlers.add(webAppContext);
    
    DefaultHandler defaultHandler = new DefaultHandler();
    handlers.add(defaultHandler);
    
    HandlerList handler = new HandlerList();
    handler.setHandlers(handlers.toArray(new Handler[0]));

    jetty.setHandler(handler);
    
    jetty.start();
    jetty.join();

The server is created and a connector (plain HTTP) is added (lines 1 to 9).

After that a Handler is created for the web application and added to the server. The folder WEB-INF is placed in the root directory in the jar file. To access this folder inside the jar and extracted during development the line 17/18 are used to create the URL of the web application.

It is possible that you can also package this as a war file and start it this way but I decided the other way round. In my case I do not need to add all libraries to the WEB-INF/lib folder. This was a really big advantage in my case because I had to create multiple web application in the course of further development (which I will describe in another blog entry).

If there are any questions left please feel free to either leave a comment (please note that I check any comment before displaying) or ask at stackoverflow.com (I’m a regular visitor there).

Leave a Reply

Your email address will not be published. Required fields are marked *