How to deploy application to Tomcat with Ant

Today I got stucked with my ant build for almost one hour but finally I solved the problem with deploying java web application from Eclipse to Tomcat. I haven't find any good article about deploying applications to Tomcat server so I create my build.xml file from pieces on the internet. So I took somewhere target for deploying applications and I have tried to use it on my development machine but it didn't work! I was getting  some strange error about non existing ant task so I had to dig on the internet for the solution and I am happy to show you.

At the first - I used this piece of code for my deployment build.xml.

<target name="deployWarToTomcat" depends="war">    <echo message="Deploying on Tomcat." />    <deploy url="http://localhost:8080/manager" username="${tomcat.admin.username}"     password="${tomcat.admin.password}" path="/myapp" war="${path.base}/${file.war}" /></target>

When I tried to run this target, I got an error regarding non existing ant target.

BUILD FAILEDbuild.xml:112: Problem: failed to create task or type deployCause: The name is undefined.Action: Check the spelling.Action: Check that any custom tasks/types have been declared.Action: Check that any <presetdef>/<macrodef> declarations have taken place.

After some time, tests and tries I've found, that the deploy target is not standard part of the original ant utility. It was made by Catalina Tomcat team as an additional task. The class is called org.apache.catalina.ant.DeployTask and is a part of the library catalina-ant.jar, which is distributed with tomcat package (you can find it in $TOMCAT_HOME/server/lib/ directory).

Okay, that was it but now how to make the Eclipse to use it? The sollution is pretty easy and elegant. Go to Preferences (Window > Preferences), click on Ant and highlight Runtime. On the first bookmark called Classpath we have to add the catalina-ant.jar library - so click on first entry called Ant Home Entries and on the right side choose Add External JARs.

Now you have two options - you can manually copy the catalina-ant.jar to your eclipse/ant directory (where are also the other ant libraries) or you can keep the library in your tomcat directory and from Eclipse just point to it. Since you can later move or rename the Tomcat directory and the build will stop working again until you will solve the changed path in Ant dependencies, I would prefer the first option.

Then still in runtime settings of Ant switch to second bookmark called Tasks, choose Add Task on the right side and enter your target name for deploy (in my case deploy) and the catalina-ant.jar library from the drop down list, which we have added in previous step.

And it is done! Just try to run the target again and you should see successful deploy action to your Tomcat server.

Comments