10.3 Hot-Deploying to Tomcat

10.3.1 Problem

You want to install a new version of a web application without stopping and restarting Tomcat.

10.3.2 Solution

Tomcat provides an Ant task called InstallTask that uploads and deploys a WAR file to Tomcat using Tomcat's Manager application.

10.3.3 Discussion

Deploying a new web application to a running server is critical for test-first development because it takes too long to restart most servers. Example 10-1 shows how to use Tomcat's InstallTask, aptly named install, to hot deploy. A new target, deploy, invokes the install task.

Like all Ant taskdefs, you are responsible for giving the task a name. The name is not specified by the task. For example, you could name a task BrianCoyner.

Before deploying the web application, a new WAR file must be generated, the server must be started, and the old web application must be removed (if it exists). Recipes later in this chapter delve into more details on the dependency targets.

Example 10-1. Hot-deploying to Tomcat
<target name="deploy" depends="war,start.tomcat,undeploy">
  <taskdef name="install" classname="org.apache.catalina.ant.InstallTask">
      <path location="${env.CATALINA_HOME}/server/lib/catalina-ant.jar"/>

  <pathconvert dirsep="/" property="fullWarDir">
      <pathelement location="${dir.build}/${webapp.context.name}.war"/>


First, create a task definition so Ant knows about the install task. The task is found at $CATALINA_HOME/server/lib/catalina-ant.jar, where $CATALINA_HOME is the base directory for Tomcat. Next, the full path of the WAR file being deployed is stored in the property fullWarDir. This is done using Ant's pathconvert task. Finally, the install task is executed. The install task defines five attributes:

  1. The url attribute specifies the location of the Manager application. By default, Tomcat installs the application on the context path /manager. For example, the URL might be http://localhost:8080/manager.

  2. The username attribute specifies the name of the user who wishes to use the Manager application.

  3. The password attribute specifies a password for authenticating the username with the Manager application.

  4. The path attribute specifies the context path to install the web application.

  5. The war attribute specifies an absolute path to the WAR file being deployed and takes on a URL that complies with the class java.net.JarURLConnection.

The install task fails if there is an existing web application installed on the current context path. Failure causes the build processes to halt. Before deploying the new WAR file, you must remove the old instance. Recipe 10.4 shows how to do this.

10.3.4 See Also

Recipe 10.4 discusses removing an existing application from Tomcat using the Manager application.