10.7 Stopping Tomcat with Ant

10.7.1 Problem

You want to stop Tomcat using Ant.

10.7.2 Solution

Create a target that invokes the custom Ant task com.oreilly.javaxp.tomcat.tasks.StopTomcatTask.

10.7.3 Discussion

Typically, a server is stopped from a command prompt using a predefined script distributed with the server. Since we have a new task to start Tomcat, it only seems fitting to provide a way to stop Tomcat, too. The ability to stop Tomcat is very useful from within an Ant buildfile, especially if we need to ensure that Tomcat is stopped before allowing any other Ant targets to execute. Example 10-8 shows the StopTomcatTask class. This new task extends AbstractTomcatTask, which we saw in Recipe 10.6, and causes Tomcat to shutdown. The task patiently waits until Tomcat is stopped before relinquishing control to other tasks.

An alternative approach is executing Tomcat's shutdown script with Ant's exec task. This approach works fine if you do not care if and when Tomcat actually stops. The same holds true for starting Tomcat.

Example 10-8. StopTomcatTask class
package com.oreilly.javaxp.tomcat.tasks;

public class StopTomcatTask extends AbstractTomcatTask {
    public String getScriptToExecute(  ) {
        return "shutdown";

    public boolean isStarting(  ) {
        return false;

Example 10-9 shows how to use this task in an Ant buildfile.

Example 10-9. Stopping Tomcat with Ant
<target name="stop.tomcat">
  <taskdef name="stoptomcat" 
      <path location="${dir.build}"/>