Thursday 3 April 2014

Leveraging Embedded Tomcat in Maven Application


In java when we develop a web application, we go for installation of tomcat on intended system. And then we deploy the application on tomcat for running it or for accessing it from the browser.

How about developing an application which can directly run on the intended system without installation of tomcat? Is it really achievable?

Yes, this can be easily achieved through Maven plug-in. Let us see how!

You might be puzzled as to how this is possible to run a web application without the installation of web container. Let us quickly have a look at the procedure which is pretty simple.

To accomplish this you just need to use a maven plug-in in pom.xml file of application. This plugin simply embed the tomcat inside the application and on build of application it generates an executable jar file, which can be easily executed by the java jar command and you can access the application on browser.

Please follow the below detailed step-by-step procedure:
1.   Add the following plugin in your pom.xml file:

<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.1</version>
    <executions>
        <execution>
        <id>tomcat-run</id>
     <goals>
            <goal>exec-war-only</goal>
        </goals>
       <phase>package</phase>
        <configuration>
            <path>/test</path>
            <attachartifactclassifier>exec-war</attachartifactclassifier>
            <attachartifactclassifiertype>jar</attachartifactclassifiertype>
        </configuration>
        </execution>
    </executions>
</plugin>

2.     Build your application: Build your application using the install or package goal. This will generate the 3 extra files in application target folder.
 
    a.  yourappname-version-exec-war.jar: An executable jar file with embedded tomcat. 
    b. war-exec.manifest:  Manifest file contains Main class name. 
    c. war-exec.properties: A properties file contains the tomcat information and some configuration options.
3.     Run your application: Once you are ready with the above three files, execute the below command to run the application.

 java –jar yourappname-version-exec-war.jar