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

Application.war
|-- META-INF
|  |-- manifest.mf
|-- WEB-INF
|  |-- 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="build.my.war">
<property name="deploy.dir" value="/my/deploy/dir" />
<property name="file.name" value="Application.war" />
  <target name="build.my.war">
    <fileset dir="contents">
      <include name="**/*"/>
    </fileset>
    <war destfile="${file.name}" webxml="conf/web.xml">
      <classes dir="bin" />
    </war>
    <echo>Copying ${file.name}...</echo>
    <copy file="${file.name}" todir="${deploy.dir}" />
    <delete file="${file.name}" />
  </target>
</project>

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"/>
   </fileset>
</path>

Define the path before the target – build.my.war.

Read more
http://ant.apache.org/manual/CoreTasks/war.html
http://ant.apache.org/manual/CoreTasks/javac.html
http://ant.apache.org/manual/dirtasks.html

Advertisements