Did this blog help you solve a problem? Tip me with Bitcoins at: 17dQktcAmU4urXz7tGk2sbuiCqykm3WLs6

Thursday, November 12, 2009

Hello World Java Web Application in Eclipse (Part 3)

Want to integrate charts into your webapp? Check out XChart.

Building with ANT and Deploying to Tomcat


Download .war and full source code of this and other sample Java Web Applications here.

This is the third of a three part series of tutorials that shows how to create a Hello World Java Web Application in Eclipse. In Part 1, I demonstrate how to create your Java Web Application project in Eclipse and set up the directory structure of the project. In Part 2, I take you through getting the Java jar needed to code Java servlets, creating a Java Servlet and a JSP file, configuring the web.xml and build.xml files. In this part, I show how to build the project with ANT using the build.xml file and how to deploy the project to a Tomcat server running on your development computer. Along the way, I point out a few tips and tricks for using the Eclipse EE IDE.



Step 1: Understand the build.xml file. After Part 2, we have a Hello World Java Web Application project in Eclipse named HelloWebApp with the build.xml file shown below. The build file is used by ANT to take all the source code and configuration files in the Web App project, compile them, and package them in a .war file, which Tomcat needs to run your application.



build.xml

<?xml version="1.0"?>
<project name="hello" default="deploy_local" basedir=".">

<property file="build.properties"/>

<path id="classpath">
<fileset dir="${lib.dir}" includes="servlet-api.jar"/>
</path>

<target name="clean">
<echo>Cleaning the ${build.dir}</echo>
<delete dir="${build.dir}"/>
<delete dir="${dist.dir}"/>
</target>

<target name="init" depends="clean">
<echo>Creating the build directory</echo>
<mkdir dir="${build.dir}/WEB-INF/classes"/>
<mkdir dir="${build.dir}/WEB-INF/lib"/>
<mkdir dir="${dist.dir}"/>
</target>

<target name="compile" depends="init">
<echo>Compile the source files</echo>
<javac srcdir="${src.dir}" destdir="${build.dir}/WEB-INF/classes">
<classpath refid="classpath"/>
</javac>
</target>

<target name="copy" depends="compile">
<copy todir="${build.dir}/WEB-INF">
<fileset dir="${web.dir}/WEB-INF"/>
</copy>
<copy todir="${build.dir}">
<fileset dir="${web.dir}"/>
</copy>
<copy todir="${build.dir}/WEB-INF/lib">
<fileset dir="${lib.dir}">
<exclude name="servlet-api.jar"/>
</fileset>
</copy>
</target>

<target name="war" depends="copy">
<echo>Building the war file</echo>
<war destfile="${dist.dir}/${project.name}.war" webxml="${build.dir}/WEB-INF/web.xml">
<fileset dir="${build.dir}"/>
</war>
</target>

<target name="deploy_local" depends="war">
<echo>Deploying .war to local Tomcat</echo>
<copy todir="${tomcat.dir}">
<fileset dir="${dist.dir}">
<include name="${project.name}.war"/>
</fileset>
</copy>
</target>

</project>


build.properties

project.name=HelloWebApp
lib.dir=lib
src.dir=src
web.dir=web
build.dir=build
dist.dir=dist
tomcat.dir=/Library/Tomcat/webapps


The build file consists of several targets and a properties file and classpath definition. The ANT builder, which comes bundled with Eclipse parses this file and carries out the instructions defined within it. Here, I'll go through the file step-by-step and explain what the ANT builder does.

Line 2: The "deploy_local" target is the default target and will be implemented first. The "basedir", where all the paths will be relative to is defined as "." meaning the directory where the build.xml file is found.

Line 4: The properties file "build.properties" is imported by ANT and stores certain key value pairs used for the build. Mostly directory names and paths are defined in the properties file.

Line 6: The jars in the classpath are used by ANT when compiling the Java source code.

Line 51: Let's skip down to this line because ANT starts with this target because it is defined as the default target. This target depends on the "war" target, which depends on the "copy" target, which depends on the "compile" target, which depends on the "init" target, which depends on the "clean" target. So actually, this means the "clean" target will be implemented first, then the "init" and so on...

Line 10: The "echo" element just prints out to the console what you tell it to. In this case, "Cleaning the ${build.dir}", where "${build.dir}" is replaced with the value "build" from the build.properties file, and "Cleaning the build" is printed out. The "delete" elements delete the "build" and "dist" folders in the project if they exist.

Line 16: The "init" target creates 3 folders in the project: "build/WEB-INF/classes", "build/WEB-INF/lib", and "dist".

Line 23: The "compile" target compiles all the java files found in the src folder and puts them in the "build/WEB-INF/classes" folder. It uses the jars defined on the classpath on line 6.

Line 30: The "copy" target moves files from the "web" and "lib" folders to the "build" folder.

Line 39: We don't copy over the servlet-api.jar because the Tomcat server already contains this jar. After all, that we're the jar came from in the first place.

Line 44: The "war" target takes everything in the "build folder", makes a WAR file and puts it in the "dist" folder.

Line 53: Inside the "deploy_local" target, the war is copied from the "dist" folder to the "/Library/Tomcat/webapps" folder, which is where the Tomcat installation resides.

Step 2: Run ANT to build the project. Right-click on build.xml and choose Run As --> Ant Build.



Here's what your new HelloWebApp Java project should now look like in the Eclipse Package Explorer View after the ANT build:



Step 3: Startup Tomcat. Now that the Tomcat installation has the WAR file in it's webapps folder, you need to start Tomcat up so it runs the web app. To do this, fire up the terminal and type: "sh /Library/Tomcat/bin/startup.sh". If you're using a non-UNIX-based computer (Windows), you have to start the startup.bat file instead, remove the sh at the front of the command, and adjust your path appropriately.

Step 4: Check out your web application in action. Point your browser to http://127.0.0.1:8080/HelloWebApp/ . You should see the Hello Web App web application in it's full glory!





Piece of Cake!!

Download .war and full source code of this and other sample Java Web Applications here.
Hello World Java Web Application in Eclipse (Part 1)
Hello World Java Web Application in Eclipse (Part 2)

See Also:
Java Ant - Build Jar with Auto-Incrementing Build Number
Java Ant - Build .War file with Auto-Incrementing Build Number

22 comments:

Wendy said...

Thank you so much for this! Not much information out there about this confusing process on Mac. Thanks again!

Tim Molter said...

Wendy, thanks for the message. Glad it helped!

Anonymous said...

Thank you, it is really helpful.
I have a problem, I google it but still don't know how to fix it.

when I "Run ANT to build the project."
it gives the following error:
----
BUILD FAILED
C:\Users\***\workspace\HelloWebApp\build.xml:25: Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "C:\Program Files\Java\jre1.6.0_06"
----
Would you help me to fix it?

thanks again
---
O.Y.

Tim Molter said...

O.Y., Try right clicking on Run As... --> Ant Build... In the dialog box that pops up go to the JRE tab and make sure you have one selected. That's my only guess. Hope it helps.

O.Y. said...

Thank you for your answer. It is solved.But another issue have aroused.

Is tomcat take a lot of time to start up?

see this pic.
http://rapidshare.com/files/451175756/tomcat_start.jpg

the place where i will write:
"sh /Library/Tomcat/bin/startup.sh"
won't appear

note that: I have a vista machine.

so what is the problem?

thanks in advance;

Tim Molter said...

O.Y., yeah tomcat can take over one second to start - that's normal. The problem you have is that on a Windows machine you have to run the *.bat scripts not the *.sh scripts.

O.Y. said...

I am not sure that I have understood you. I waited over than 15 minutes and still nothing happened.

Another issue but related with a program that I am developing. When I run it as a web app. it gives this error:

[ERROR] shell failed in doStartupServer method
Port 127.0.0.1:8888 is already is use; you probably still have another session active

so how could i fix it also.

O.Y. said...

Let me revise with you the steps that I made,

I had a tomcat 7 running on my machine
then I run the build.xml
then I copy this url in the browser of the eclipse:http://127.0.0.1:8080/HelloWebApp/
and it gives:
---
HTTP Status 404 - /HelloWebApp/

--------------------------------------------------------------------------------

type Status report

message /HelloWebApp/

description The requested resource (/HelloWebApp/) is not available.


--------------------------------------------------------------------------------

Apache Tomcat/7.0.8
------------

would you help me??

Tim Molter said...

O.Y., sorry, but not being there right next to you I can't troubleshoot your problem too well. I would suggest googling the specific errors/problems you are having and going from there...

O.Y. said...

thank you for your help.
I know that I am bothering you, but don't you know what is the actual reason of this error:

The requested resource (/HelloWebApp/) is not available.

Tim Molter said...

O.Y., That error is your browser saying it found nothing at that URL. It could be caused by many reasons. Is Tomcat running? Did it unpack the .war file and create a HelloWebApp folder? Are you correctly using port 8080 in the URL? Are you seeing any errors in the .../log folder that can give you a hint? Good luck.

O.Y. said...

thank you, your answers helped me a lot.
thanks again.

Urema said...

Hi,

This didnt work for me....it keeps telling me that srcdir doesn't exist....but when I point directly to my src folder, it says that "/lib" is not found....confusion

Any suggestions?
U.

Tim Molter said...

@Urema Please post for me the exact error you get from the ANT Build. Thanks.

Urema said...

Thanks greatly for your quick reply!
Sorry - I fixed this error, I just directly pointed to some of the directories.....

However I cannot run this example on my local tomcat server...I keep getting a HTTP 404 error.
Is it because I am running my local server from eclipse? If I run it by 'sh startup.sh" how does this local server relate to that that I see in my server view in Eclipse?

When I do run 'sh startup.sh" I get

"Cannot find ./catalina.sh
This file is needed to run this program"

Even though ./catalina.sh is there and it has the same permissions as startup.sh....any suggestions?

Thanks greatly in advance,
U.

Tim Molter said...

@Urema Is tomcat running? To check, look for the running process "java" in Activity Monitor. If not, that's your first problem. I wrote: use the terminal and type "sh /Library/Tomcat/bin/startup.sh". Did you use the terminal? Yes, you can run shell scripts from within Eclipse, but I would suggest getting it working with the Terminal first to remove one layer of complexity.

Urema said...

Tim,
As I mentioned above I did try it in the terminal and it tells me that './catlina.sh' does not exist...however it does exist and it has the same permissions as the startup.sh......what does this mean?

I have two 'java' processes running....what does this mean?

Thanks greatly in advance,
U.

Tim Molter said...

@Urema Ah, now I see the problem... That's weird though. I have no idea why it would not find catalina.sh. The fact that two "java" processes are running is worrisome though. Go ahead and kill them and start over. It may be that you have Tomcat installed in two locations accidentally? Sorry I can't tell you what your exact problem is. :(

Urema said...

Sorry, I will update my last message...

I now have Tomcats main page running when I request http://localhost:8080/ - however I cannot access my http://localhost:8080/HelloWorldApp/

When I run the ANT build, I do not get a server-api.jar file in my /lib folder, is this a problem for running on localhost?

Thanks,
U.

Urema said...

I can access my Server Manager once I get into my http://localhost:8080/ and I can see my application HelloWorldApp there, it says its available etc though when i click on it to access this application i still get the HTTP 404 error - so I can see my application and it looks fine in terms of server health etc however I cant access it.....

Thanks greatly,
U.

Tim Molter said...

@Urema You don't need servlet-api.jar in your projects lib file because tomcat already has that jar in its lib file. Go ahead and make sure it's there if you want. At this point, you need to start looking in the log files tomcat produces in its log folder to find out what your problem is exactly. Look for exceptions and start fixing anything that comes up. You made it this far, you almost there!

Anonymous said...

Wonderful. Covered everything form basics and thank you so much for the step by step explanation.