Deploying a WAR to Tomcat using Maven

Most articles you will find about automatically deploying a WAR to Tomcat using Maven will mention the Tomcat Maven plugin. I was trying to use this plugin, but I didn't get it to work. The manager app kept returning a 403 even though I followed the instructions and added the credentials to my Maven settings.xml file. Also, the plugin kept trying to publish my app to a path under root, while I wanted it published to the root of the server (ROOT.war). The plugin kept using the artifact-id as an application path. 

ANYWAY, I decided to return to good old Ant, because Ant always understands what I want and I always understand what Ant wants. Fortunately, since we can run Ant tasks from Maven, I didn't have to switch my entire build process to Ant.

Here is how I (re)deploy my WAR to Tomcat using Ant tasks from Maven.

  1. Put the plugin definition below between the <plugins>  tags in your application's pom.xml  file.
    <plugin>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.3</version>
        <executions>
            <execution>
                <phase>install</phase>
                <configuration>
                    <tasks name="Deploy to Tomcat">
                        <!-- stop tomcat -->
                        <exec dir="${tomcat.dir}" executable="${tomcat.dir}/bin/shutdown.bat" failonerror="false">
                            <arg line="" />
                        </exec>
                        <!-- give Tomcat some time to shut down -->
                        <sleep seconds="1"/>
                        <!-- delete the web application folder -->
                        <delete dir="C:\tomcat7\webapps\ROOT" />
                        <!-- copy the new war file to Tomcat and overwrite an existing file -->
                        <copy file="C:\PROJECTS\MyProject\target\ROOT.war" todir="C:\tomcat7\webapps" overwrite="true"
                            failonerror="true" />
                        <!-- start tomcat -->
                        <exec dir="${tomcat.dir}" executable="${tomcat.dir}/bin/startup.bat" failonerror="true">
                            <arg line="" />
                        </exec>
                    </tasks>
                </configuration>
                <goals>
                    <goal>run</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    
  2. Obviously, you should adjust the directory paths in the code above to reflect your own situation.
  3. Finally, create the tomcat.dir  property in your maven file like this:
    <properties>
        <tomcat.dir>C:\tomcat7</tomcat.dir>
    </properties>
    

I hope this works for you. Happy programming!

John at Monday, July 15, 2013 4:30 AM It's very useful. A++

Your email address will not be shown on the site
1 + 9 =