Hot-Deploying to Tomcat

Problem

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

Solution

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

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.

Tip

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">
    <classpath>
      <path location="${env.CATALINA_HOME}/server/lib/catalina-ant.jar"/>
    </classpath>
  </taskdef>

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

  <install
      url="${url.manager}"
      username="${username.manager}"
      password="${password.manager}"
      path="/${webapp.context.name}"
      war="jar:file:/${fullWarDir}!/"/> ...

Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.