How-To: Create a WAR file using ANT

In one of my previous posts I mentioned about building a JAR using ANT.  This post – building a WAR (Web Application Archive) – is just an add-on to that.

Structure of a WAR file

|  |--
|  |-- web.xml   - deployment descriptor
|  |-- classes   - class files organized in packages
|  |-- lib       - other libraries
|-- <other files, directories etc.>

Deployment descriptor
This is a sample deployment descriptor from Java Servlet Specification version 2.4. Get the descriptor (.pdf)

Build file

<project name="my.enterprise.project" default="">
<property name="deploy.dir" value="/my/deploy/dir" />
<property name="" value="Application.war" />
  <target name="">
    <fileset dir="contents">
      <include name="**/*"/>
    <war destfile="${}" webxml="conf/web.xml">
      <classes dir="bin" />
    <echo>Copying ${}...</echo>
    <copy file="${}" todir="${deploy.dir}" />
    <delete file="${}" />

The above build file assumes that all the non-java resources and JSPs are within the “contents” directory. The build file will pick the class files from the “bin” directory within the base. Here the build file is not compiling existing source files. To compile Java files there is another ANT task –  javac.

<javac srcdir="src" destdir="bin" classpathref="application.classpath"/>

Add the javac task before the war task in the build file.

Defining the class path

<path id="application.classpath">
   <fileset dir="/path/to/my/lib">
      <include name="javax.servlet.jar"/>

Define the path before the target –

Read more