Wednesday, October 3, 2012

Runtime deploy Java Webapp

Requirement:
Do not spend time for deploying Java web application.

Solution:
Use Jetty
Jetty is an HTTP server, HTTP client, and javax.servlet container.

So let's say we have the spring RESTful web application developing in Eclipse. Te structure of application is:

Inline image 2

The web application folder to deploy is /webapp, also is needed to add conf.properties and log4j.properties to the application classpath.
If you have noticed in src folder there is a package http.server here lies our savior. The class Launcher.java is the http server. In that class we have some code lines, let's look inside this class:

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

            Connector connector = new SelectChannelConnector();
            connector.setPort(8080);
            server.addConnector(connector);

            WebAppContext root = new WebAppContext("webapp""/");
            //Add .properties files to classpath
            WebAppClassLoader classLoader = new WebAppClassLoader(root);
            classLoader.addClassPath("conf/localhost");
            root.setClassLoader(classLoader);
            server.setHandlers(new Handler[] { root });
            server.start();
      }
}

For resolve all dependencies you need to download the following jars: 


That's all :) 
Also if your classes aren't compiled in webapp/WEB-INF/classes path then you can add them for example in that way:
classLoader.addClassPath("bin");

After running that class, go to your browser and open the address: http://localhost:8080/<servlet_path>
In my case the address is http://localhost:8080/service/xml/info and in the browser I get the:

Inline image 3

Happy developing!