Configuring & Using Apache Tomcat 6
A Tutorial on Installing and Using
Jakarta Tomcat for Servlet and JSP Development
Following is a guide to installing and configuring Apache Tomcat 6 for use
as a standalone Web server (for development) that supports servlets
2.5 and JSP 2.1. (Note: Apache Tomcat is sometimes referred to
as "Jakarta Tomcat" since the Apache
Java effort
is known as "The Jakarta Project"). This Tomcat tutorial
covers version 6.0.10, but the steps are almost the same
for any Tomcat 6.0.x version.
For coverage of Tomcat 5.5, see the separate
Tomcat 5.5 tutorial. For coverage
of very old Tomcat versions (Tomcat 5.0.x and
Tomcat 4.0.x), please see
the Apache Tomcat 5.0 and 4.0 tutorial.
Using Tomcat as a deployment server or integrating Tomcat as a
plugin within the regular Apache server or a commercial Web
server is more complicated than what is described in this tutorial.
Although such integration is valuable for a deployment
scenario (see http://tomcat.apache.org/tomcat-6.0-doc/),
my goal here is to show how to use Tomcat as a development
server on your desktop. Regardless of what deployment
server you use, you'll want a standalone server on your desktop
to use for development.
The examples here assume you are using Windows, but they can be
easily adapted for MacOS, Linux, Solaris, and other versions of Unix.
Except when I refer to specific Windows paths (e.g., C:\blah\blah),
I use URL-style forward slashes for path separators (e.g.,
install_dir/webapps/ROOT). Adapt as necessary.
To report errors or omissions in this writeup or to inquire about customized
on-site training courses on servlets, JSP, Struts, JSF, Ajax, Java 5,
Java 6, and other J2EE technologies, please contact Marty Hall
at hall@coreservlets.com.
Most people will just want to download the
preconfigured Tomcat version,
set JAVA_HOME and CLASSPATH,
and they are done. But following is a summary of the steps for people who want to change the configuration or do it themselves. This section gives a summary of the
required steps; I give extremely detailed instructions in the following sections.
- Install the JDK.
Make sure JDK 1.5 or 1.6 is installed and your
PATH is
set so that both "java -version" and
"javac -help" give a result.
- Configure Tomcat.
- Download the software. Go to
http://tomcat.apache.org/download-60.cgi and
download and unpack the zip file for the current release build of Tomcat 6.0.
- Set the
JAVA_HOME variable.
Set it to refer to the base JDK directory, not the bin subdirectory.
- Change the port to 80.
Edit install_dir/conf/server.xml and change
the
port attribute of the Connector element
from 8080 to 80.
- Turn on servlet reloading.
Edit install_dir/conf/context.xml and
change
<Context> to
<Context reloadable="true" privileged="true">.
- Enable the invoker servlet.
Go to install_dir/conf/web.xml and
uncomment the
servlet and servlet-mapping
elements that map the invoker servlet
to /servlet/*.
- Turn on directory listings.
Go to install_dir/conf/web.xml, find the
init-param entry for listings,
and change the value from false to
true.
- Set the
CATALINA_HOME variable.
Optionally, set CATALINA_HOME to refer to the top-level
Tomcat installation directory. Not necessary unless you copy the
startup scripts instead of making shortcuts to them.
- Use a preconfigured Tomcat version.
Optionally, use a version of Jakarta Tomcat that has all of the above changes
already made, and has the test HTML, JSP, and servlet
files already bundled. Just unzip the file, set your
JAVA_HOME and CLASSPATH variables,
and you are ready to go.
- Test the server.
- Verify that you can start the server.
Double-click install_dir/bin/startup.bat and
try accessing http://localhost/.
- Check that you can access your own HTML &
JSP pages. Drop some simple HTML and JSP pages into
install_dir/webapps/ROOT and access them with
http://localhost/filename.
- Try Compiling and Deploying Servlets.
- Set up your development environment.
- Create a development directory.
Put it anywhere except within the Tomcat installation hierarchy.
- Make shortcuts to the Tomcat startup &
shutdown Scripts. Put shortcuts to install_dir/bin/startup.bat
and install_dir/bin/shutdown.bat in
your development directory and/or on your desktop.
- Set your class path.
Use the
CLASSPATH environment variable or set the
path in the project settings of your IDE.
Include the current directory ("."), the
servlet/JSP JAR files (install_dir/lib/servlet-api.jar,
and install_dir/lib/jsp-api.jar, and
install_dir/lib/el-api.jar),
and your main development directory from Step 1.
- Bookmark the servlet & JSP javadocs.
Add
the servlet 2.4 API and
the JSP 2.0 API
to your bookmarks/favorites list.
- Compile and test some simple servlets.
- Test a packageless servlet.
Compile a simple servlet, put the .class file
in install_dir/webapps/ROOT/WEB-INF/classes,
and access it with http://localhost/servlet/ServletName.
- Test a servlet that uses packages.
Compile the servlet, put the .class file
in install_dir/webapps/ROOT/WEB-INF/classes/packageName,
and access it with http://localhost/servlet/packageName.ServletName.
- Test a servlet that uses packages and utility classes.
Compile a servlet, put both the servlet .class file and the
utility file .class file in
install_dir/webapps/ROOT/WEB-INF/classes/packageName,
and access the servlet with http://localhost/servlet/packageName.ServletName.
This third step verifies
that the
CLASSPATH includes the top level of your
development directory.
- Establish a simplified deployment method.
- Copy to a shortcut.
Make a shortcut to install_dir/webapps/ROOT.
Copy packageless .class files directly there.
With packages, copy the entire directory there.
This is the simplest option for beginners, and
the preconfigured
Tomcat version already has a development directory with
these shortcuts.
- Use the
-d option of
javac. Use -d to
tell Java where the deployment directory is.
- Let your IDE take care of deployment.
Tell your IDE (Eclipse, NetBeans, JBuilder, etc.) where the deployment directory
is and let it copy the necessary files.
- Use
ant or a similar tool.
Use the Apache make-like tool
to automate copying of files.
- Get more info. Access the complete set of
Tomcat docs, get free JSP and servlet tutorials,
read the official servlet and JSP specifications,
get JSP-savvy editors and IDEs, look for J2EE jobs, etc.
Your first step is to download and install Java.
Tomcat 6.0 requires JDK 1.5 Standard Edition (Java 5) or
JDK 1.6 Standard Edition (Java 6).
See the following sites for download and installation information.
Once you've installed Java, confirm that
everything including your PATH is configured properly by opening a DOS
window and typing "java -version" and "javac -help".
You should see a real result both times, not an error message about
an unknown command. Or, if
you use an IDE, compile and run a simple program to confirm that
the IDE knows where you installed Java.
For example, if you have JDK 1.5_08, you could set your PATH
by putting the following line in your C:\autoexec.bat file.
set PATH="C:\Program Files\Java\jdk1.5.0_08\bin";%PATH%
On Windows XP, you could also go to the Start menu, select Control Panel,
choose System, click on the Advanced tab, press the Environment Variables
button at the bottom, and enter the PATH
variable and value directly. On Windows 2000 and NT, you do Start,
Settings, Control Panel, System,
then Environment. However, you can use C:\autoexec.bat
on those versions of Windows also (unless a system administrator has set your PC
to ignore it).
Configuring Tomcat involves four main steps and five optional steps:
- Downloading the Tomcat software.
- Setting the
JAVA_HOME variable.
- Changing the port from 8080 to 80.
- Telling Tomcat to reload servlets when they are modified.
- Enabling the invoker servlet.
- Turning on directory listings.
- Setting the
CATALINA_HOME variable.
(Optional; rarely used)
- Using a preconfigured version of Tomcat
with these changes already made. (Optional; widely used)
- Using the Windows .exe installer instead of the .zip file.
(Not Recommended)
Details of each step are given below. If Tomcat is already running, restart it
after performing these steps.
Go to
http://tomcat.apache.org/download-60.cgi and download
and unpack the zip file for the current release build of Tomcat 6.
You specify the top-level directory (e.g., C:\) and the zip file
has embedded subdirectories (e.g., apache-tomcat-6.0.10).
Thus, C:\apache-tomcat-6.0.10 is a common resultant installation directory.
Note: from this point forward, I'll refer to that location as install_dir.
For Windows, there is also a .exe installer; I prefer the .zip file,
but see the .exe
installer section for notes on the differences between the two.
Alternatively, you can use my
preconfigured Jakarta Tomcat version.
This version already has the port changed to 80, servlet reloading enabled,
and the invoker servlet turned on.
It also comes with a sample development directory, autoexec.bat file,
startup/shutdown shortcuts, and shortcuts for deploying applications.
Next, you must set the JAVA_HOME environment variable to
tell Tomcat where to find Java. Failing to properly set this variable
prevents Tomcat from compiling JSP pages. This variable should list
the base JDK installation directory, not the bin subdirectory.
For example, on almost any version of Windows, if you use JDK 1.5_08, you
might put the following line in your C:\autoexec.bat file.
set JAVA_HOME=C:\Program Files\Java\jdk1.5.0_08
On Windows XP, you could also go to the Start menu, select Control Panel,
choose System, click on the Advanced tab, press the Environment Variables
button at the bottom, and enter the JAVA_HOME variable
and value directly. On Windows 2000 and NT, you do Start, Settings,
Control Panel, System, then Environment. However, you can use C:\autoexec.bat
on those versions of Windows also (unless a system administrator h
as set your PC to ignore it).
Assuming you have no other server already running on port 80,
you'll find it convenient to configure Tomcat to run on the
default HTTP port (80) instead of the out-of-the-box port of 8080.
Making this change lets you use URLs of the form
http://localhost/blah instead of http://localhost:8080/blah.
Note that you need admin privileges to make this
change on Unix/Linux. Also note that some versions of Windows XP
automatically start IIS on port 80. So, if you use XP and
want to use port 80 for Tomcat, you may need to disable IIS
(see the Administrative Tools section of the Control Panel).
To change the port, edit install_dir/conf/server.xml
and change the port attribute of the
Connector element from 8080 to 80, yielding a result similar to that below.
<Connector port="80" ...
maxThreads="150" ...
You can also:
The next step is to tell Tomcat to check the modification dates of
the class files of requested servlets, and reload ones
that have changed since they were loaded into the server's memory.
This slightly degrades performance in deployment situations,
so is turned off by default. However, if you fail to turn it on for
your development server, you'll have to restart the server
every time you recompile a servlet that has already been loaded into
the server's memory. Since this tutorial discusses the
use of Tomcat for development, this change is strongly recommended.
To turn on servlet reloading, edit Edit
install_dir/conf/context.xml and change
<Context>
to
<Context reloadable="true" privileged="true">
Note that the privileged entry is really to support the invoker
servlet (see the following section), so you can omit that entry if you do not
use the invoker.
You can also:
The invoker servlet lets you run servlets without first making
changes to your Web application's deployment descriptor (i.e.,
the WEB-INF/web.xml file). Instead, you just drop your servlet
into WEB-INF/classes and use the URL
http://host/servlet/ServletName
(or http://host/webAppName/servlet/ServletName once
you start using your own Web applications.
The invoker servlet is extremely convenient when you are learning
and even when you are testing things doing your
initial development. You almost certainly want to enable it when learning,
but you should disable it again before deploying
any real applications.
To enable the invoker servlet, uncomment the following
servlet and servlet-mapping elements
in install_dir/conf/web.xml. Do not confuse this
Apache Tomcat-specific web.xml file with the standard
one that goes in the WEB-INF directory of each Web application.
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
...
</servlet>
...
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
In Tomcat 6 (but not Tomcat 5.5), you also need the privileged="true"
entry in the Context element of context.xml. See the previous
section for an example.
You can also:
In previous Tomcat versions, if you entered a URL ending in a slash
(/) and there was no welcome-file in the directory (or servlet-mapping that matched the URL), Tomcat displayed a directory listing. In Tomcat 6, the default
was changed from true to false for these directory listings. Many developers find
it convenient to turn directory listings back on.
To make this change, edit install_dir/conf/web.xml
and change the init-param value of listings for the default servlet,
as below. Do not confuse this
Apache Tomcat-specific web.xml file with the standard
one that goes in the WEB-INF directory of each Web application.
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
You can also:
If you are going to make copies of the Tomcat startup or shutdown scripts
(e.g., startup.bat and shutdown.bat),
it is also helpful to set the CATALINA_HOME environment
variable to refer to the top-level directory of the
Apache Tomcat installation (e.g., C:\apache-tomcat-6.0.10).
This variable identifies the Tomcat installation directory
to the server. However, if you are careful to avoid copying the server
scripts and you use only shortcuts (called "symbolic
links" on Unix/Linux) instead, you are not required to set this variable.
I recommend using shortcuts and not bothering
with CATALINA_HOME.
Please see the
preconfigured Tomcat page to get a version of Jakarta Tomcat 6.0
with all configuration settings already made.
Just unzip the file, set your JAVA_HOME and
CLASSPATH variables, and you are read to go.
If you are using Microsoft Windows, you can download a .exe installer
instead of the .zip file discussed in this tutorial.
In my opinion, it is not worth the bother to do so, but some people like it.
If you use it, note these differences:
- It will prompt you for the desired port. It will ask you
what port it should run on, and make the changes
in server.xml for you. You will still need to manually
edit context.xml and web.xml, however.
- It will set
JAVA_HOME for you.
The installer hunts for your Java installation and tries
to set JAVA_HOME appropriately. This is a convenience,
albeit a minor one.
- It will setup Start Menu entries. In particular, instead of
using startup.bat and shutdown.bat,
you can go to the Start Menu, select Apache Tomcat 6.0,
select Monitor Tomcat, and select Start or Stop, as shown
below. I prefer startup.bat and shutdown.bat
so that I can put shortcuts in my development directory
(easier to invoke) and/or the desktop (where I can associate keyboard shortcuts).

Testing the server involves three steps:
- Verifying that the server can even start.
- Checking that you can access your own HTML and JSP pages.
- Seeing if you can compile and run simple servlets.
Before trying your own servlets or JSP pages, you should make sure that the server is
installed and configured properly. For Tomcat, click on install_dir/bin/startup.bat
(or execute install_dir/bin/startup.sh on Unix/Linux).
Next, enter the URL http://localhost/ in your browser and make sure
you get the Tomcat welcome page, not an error message saying that the
page could not be displayed or that the server could not be found.
If you chose not to change the port number to 80 as
described above, you will need to use a URL like
http://localhost:8080/ that includes the port number.
If this does not work, there are a couple of things to check:
- Did the Tomcat window pop up and stay open?
If not, the error messages are lost and it is hard to know
what you did wrong. So, open a DOS window, go to install_dir/bin and
type "
catalina run" to start Tomcat without popping up
a new window. Now, the error messages should help you figure out the
problem (e.g., JAVA_HOME not set properly or IIS already
reserving port 80).
- Does the server appear to be running but you cannot access the
home page? Maybe your browser is using a proxy and you have
not set it to bypass proxies for local addresses? To fix this:
- On Internet Explorer,
go to Tools, Internet Options, Connections, and LAN Settings. If
the "Use a proxy server" checkbox is selected, make sure the "Bypass
proxy server for local addresses" box is also selected.
- On Netscape 6/7, go to the Edit menu, then select Preferences, Advanced, and Proxies.
Then enter "localhost" in the textfield labeled "No Proxy for:".
- On Mozilla Firefox go to Tools, Internet Options, and Connections.
Make sure "localhost" is in the textfield labeled "No Proxy for:".
Note that this entry is the default with Firefox, so you probably do not
need to change it.
To halt the server, double click on install_dir/bin/shutdown.bat.
I recommend that you make shortcuts to (not copies of) the startup and
shutdown scripts and place those shortcuts on the desktop or in your main development
directory. If you put them on the desktop, you can assign keyboard shortcuts,
which is convenient.
After you have verified that the server is running, you should make sure that you can
install and access simple HTML and JSP pages. This test, if successful, shows two
important things. First, successfully accessing an HTML page shows that you understand
which directories should hold HTML and JSP files, and what URLs correspond
to them. Second, successfully
accessing a new JSP page shows that the Java compiler
(not just the Java virtual machine) is configured properly.
Eventually, you will almost certainly want to create and use
your own Web applications, but for initial
testing many people prefer to use the default Web application.
With Tomcat and the default Web application, you put HTML and JSP pages in
install_dir/webapps/ROOT or install_dir/webapps/ROOT/somePath and
access them with http://localhost/filename or
http://localhost/somePath/filename.
For your first tests, I suggest you simply take Hello.html
and Hello.jsp and drop them into the appropriate locations.
Right click on the link to download these two files to your system. If you download the files
using Internet Explorer, be careful that it does not try to change the file extension,
yielding Hello.htm instead of Hello.html.
Note also that the
preconfigured Tomcat version
already contains all the test files, and has shortcuts from the development directory
to the deployment locations.
If you put the files in the top-level directory of the
default Web application (i.e., in install_dir/webapps/ROOT),
access them with the URLs
http://localhost/Hello.html and http://localhost/Hello.jsp,
respectively. If you put them in a subdirectory of install_dir/webapps/ROOT,
use the URLs http://localhost/directoryName/Hello.html and
http://localhost/directoryName/Hello.jsp, respectively.
If you successfully started the server as
described above, but
neither the HTML file nor the JSP file works (e.g., you get File Not
Found--404--errors), you likely are using the wrong directory for the files. If the
HTML file works but the JSP file fails, you probably have incorrectly specified the
base JDK directory (i.e., with the JAVA_HOME variable).
After you set up your development environment, be sure to come back and
verify that you can compile and run servlets.
The server startup script startup.bat automatically sets the
server's CLASSPATH to include the
standard servlet and JSP classes and the
WEB-INF/classes directory (containing
compiled servlets and other .class files) of each Web application.
But you need similar settings, or you will
be unable to compile servlets in the first place.
Configuring your system for servlet development involves
the following four steps:
- Creating a development directory
- Making shortcuts to the Tomcat startup and shutdown scripts
- Setting your
CLASSPATH
- Bookmarking the servlet & JSP javadocs
Details on each step are given below.
The first thing you should do is create a directory in which to place the servlets and
JSP pages that you develop. This directory can be in your home directory (e.g.,
C:\Documents and Settings\Your Name\My Documents\Servlets+JSP
on Windows 2000) or in a convenient general location
(e.g., C:\Servlets+JSP). It should not, however,
be in the Tomcat deployment directory (e.g., anywhere
within install_dir/webapps).
Eventually, you will organize this development directory into
different Web applications. For initial testing of your
environment, however, you can just put servlets either directly in the development
directory (for packageless servlets) or in a subdirectory that matches the servlet package
name. Some developers simply put all their code in the server's deployment
directory (within install_dir/webapps).
I strongly discourage this practice and instead recommend
one of the approaches described in the
deployment section.
Although developing in the deployment directory seems simpler at
the beginning since it requires no copying of files,
it significantly complicates matters
in the long run. Mixing locations makes it hard to separate an operational version
from a version you are testing, makes it difficult to test on multiple servers, and
makes organization much more complicated. Besides, your desktop is almost certainly
not the final deployment server, so you'll eventually have to develop a good system
for deploying anyhow.
Note that the preconfigured Tomcat version
already contains all the test files, has shortcuts from the development directory
to the deployment locations, and has shortcuts to start and stop the server.
Since I find myself frequently restarting the server, I find it convenient to place
shortcuts to the server startup and shutdown scripts inside my main development
directory or on my desktop. You will likely find it convenient to do the same.
For example, one way to make these shortcuts is to go to
install_dir/bin, right-click on startup.bat,
and select Copy. Then go to your development directory, right-click in the
window, and select Paste Shortcut (not just Paste). Repeat the process for
install_dir/bin/shutdown.bat. If you put the shortcuts on your desktop,
you can also assign keyboard shortcuts to invoke them. On Unix, you would use
ln -s to make a symbolic link
to startup.sh, catalina.sh
(needed even though you don't directly invoke this file), and
shutdown.sh.
Since servlets and JSP are not part of the Java 2
platform, standard edition, you have
to identify the servlet classes to the compiler.
The server already knows about the
servlet classes, but the compiler (i.e., javac)
you use for development probably
doesn't. So, if you don't set your CLASSPATH (either via
an environment variable, an operating system setting, or an IDE setting),
attempts to compile servlets, tag libraries, filters, Web app listeners,
or other classes that use the servlet and JSP APIs will fail with error messages about
unknown classes. Here are the standard Tomcat locations:
- install_dir/common/lib/servlet-api.jar
- install_dir/common/lib/jsp-api.jar
You need to include both files in your CLASSPATH.
Now, in addition to the servlet JAR file, you also need to put your development
directory in the CLASSPATH. Although this is
not necessary for simple packageless
servlets, once you gain experience you will almost certainly use packages. Compiling
a file that is in a package and that uses another class in a
user-defined package requires the
CLASSPATH to include the directory that is at the
top of the package hierarchy. In
this case, that's the development directory I just discussed.
Forgetting this setting is perhaps the most common
mistake made by beginning servlet programmers!
Finally, you should include "." (the current directory)
in the CLASSPATH. Otherwise,
you will only be able to compile packageless classes that are in the top-level
development directory.
Here are two representative methods of setting the
CLASSPATH. They assume
that your development directory is C:\Servlets+JSP.
Replace install_dir with the actual Tomcat installation
path (e.g., C:\apache-tomcat-6.0.10). Also, be sure to use the appropriate
case for the filenames, and enclose your pathnames in double
quotes if they contain spaces.
Any Windows Version from Windows 98/Me Onward.
Use the autoexec.bat file.
- Sample code: (Note that
this all goes on one line with no spaces--it is broken here only for
readability.)
set CLASSPATH=.;
C:\Servlets+JSP;
install_dir\common\lib\servlet-api.jar;
install_dir\common\lib\jsp-api.jar
- Sample file to download and modify:
autoexec.bat
Note that these examples represent only one approach for
setting the CLASSPATH. Many
Java integrated development environments have global or project-specific settings
that accomplish the same result. But these settings are totally IDE-specific and
won't be discussed here. Another alternative is to make a .bat file or
ant build script whereby
-classpath ... is automatically appended onto calls to javac.
Windows NT/2000/XP. You could use the autoexec.bat file as above, or you can
use system settings. On WinXP, go to the Start menu and select Control Panel, then
System, then the Advanced tab, then the Environment Variables button.
On Win2K/WinNT, go to the Start menu and select Settings,
then Control Panel, then System, then Environment. Either way, enter the
CLASSPATH value from the previous bullet.
Just as no serious programmer should develop general-purpose Java applications
without access to the
JDK API documentation (in Javadoc format), no serious programmer
should develop servlets or JSP pages
without access to the API for classes in the javax.servlet packages.
Here are the standard locations:
- Servlet API:
- JSP API:
-
JSP 2.0.
-
JSP 2.1. Note that the official Tomcat pages point here, but
as of 5/2007, this link was dead.
OK, so your environment is all set. At least you
think it is. It would be nice to confirm
that hypothesis. Verifying this involves the
following three steps:
- Testing a packageless servlet
- Testing a servlet that uses packages
- Testing a servlet that uses packages and utility classes
Details on each step are given below.
The first servlet to try is a basic one:
no packages or utility (helper) classes.
Rather than writing your own test servlet, you can just download
HelloServlet.java into your
development directory, compile it, and copy the .class file
to install_dir/webapps/ROOT/WEB-INF/classes.
Right-click on the link to download the file to your system.
Note: in all versions of Apache Tomcat, the location for servlets in the default
Web application is install_dir/webapps/ROOT/WEB-INF/classes.
However, in some versions of Tomcat (including Tomcat 6.0.10),
the system doesn't create the classes directory for you automatically.
No problem: just create it yourself. (Remember that case matters:
WEB-INF is upper case, classes is lower case.) Note
that my preconfigured Apache Tomcat version
already contains the classes directory and already has the sample
servlets.
What about install_dir/shared/classes?
"Hey, wait! Shouldn't I use install_dir/shared/classes
instead of install_dir/webapps/ROOT/WEB-INF/classes?"
Nope. There are two reasons why it is preferable to use
install_dir/webapps/ROOT/WEB-INF/classes:
1. It is standard. The ROOT directory follows the normal
structure of a Web application (see Section 2.11
of the book):
HTML/JSP files go in the main directory, the web.xml
file goes in WEB-INF, unjarred Java classes go in WEB-INF/classes,
and JAR files go in WEB-INF/lib. So, if you use WEB-INF/classes,
you are using a structure that works on all servers that support servlets
2.2 and later. On the other hand, install_dir/shared/classes is a Tomcat-specific location
that is supported on few, if any, other servers.
2. It is specific to a Web application. Once you become
comfortable with the basics, you will almost certainly divide
your projects up into separate Web applications.
By putting your code in WEB-INF/classes, you are ready
for this, since your code is already part of a Web application
(the default one for Tomcat). So, the code can easily move to another
Web application, and it will not interfere with any future
applications. On the other hand, install_dir/shared/classes results in code that
is shared by all Web applications on your server. This is
almost never what you want for servlets.
If you get compilation errors, go back and check your
CLASSPATH settings (see the earlier section
on this topic)--you most likely erred in listing the location of the
JAR files that contains the servlet and JSP classes.
Once you compile HelloServlet.java, put HelloServlet.class
in install_dir/webapps/ROOT/WEB-INF/classes. After compiling the code,
access the servlet with the URL
http://localhost/servlet/HelloServlet
(or http://localhost:8080/servlet/HelloServlet if you
chose not to change the port number as
described earlier). You should get
a simple HTML page that says "Hello".
If this URL fails but the test of the server itself
succeeded, you probably put the class file in the wrong directory
or forgot to enable the invoker servlet.
The second servlet to try is one that uses packages but not utility classes. Again,
rather than writing your own test, you can download and install
HelloServlet2.java.
Since this servlet is in the coreservlets package, it should go
in the coreservlets directory
both during development and when deployed to the server.
Once you compile HelloServlet2.java, put HelloServlet2.class in
install_dir/webapps/ROOT/WEB-INF/classes/coreservlets.
For now, you can simply copy (not move!) the coreservlets subdirectory
from the development directory to install_dir/webapps/ROOT/WEB-INF/classes.
An upcoming section
will provide some other options for the deployment process.
Once you have placed the servlet in the proper directory, access it with the URL
http://localhost/servlet/coreservlets.HelloServlet2. You should get
a simple HTML page that says "Hello (2)". If the first test succeeded
but this test failed,
you probably either typed the URL wrong (e.g., used
a slash instead of a dot after the package name) or
put HelloServlet2.class in the
wrong location (e.g., directly in install_dir/webapps/ROOT/WEB-INF/classes
directory instead of in the coreservlets subdirectory).
The final servlet you should test to verify the configuration of
your server and development
environment is one that uses both packages and utility classes.
HelloServlet3.java
is a servlet in the coreservlets package that uses
the
ServletUtilities class to simplify the generation of the
DOCTYPE (specifies the HTML version--useful
when using HTML validators) and HEAD
(specifies the title) portions of the
HTML page. Those two parts of the page are useful (technically required, in fact),
but are tedious to generate with servlet println statements.
Since both the servlet and the utility class are in
the coreservlets package,
they should go in the coreservlets directory.
If you get compilation errors such as "Unresolved symbol: ServletUtilities",
check the following two things.
- That you put the classes in the coreservlets subdirectory,
not directly in your development directory.
Packaged Java code should always be placed
in a subdirectory matching the package name.
- That your CLASSPATH is set properly.
If this is the cause of your problem, you most likely forgot to include
the top-level development directory (i.e., the directory above the package-specific
subdirectory). I've said it before, but
I'll say it again: your
CLASSPATH must include the top-level directory
of your package hierarchy before you can compile a packaged class that makes use
of another class from a user-defined package. This requirement is not particular to servlets;
it is the way packages work on the Java platform in general. Nevertheless,
many servlet developers are unaware of this fact, and it is one of the (perhaps the) most
common errors beginning developers encounter.
Please don't send me email about unresolved symbol errors until you have confirmed
that HelloServlet3.java and ServletUtilities.java are in a subdirectory called coreservlets,
and that the directory above this is in the CLASSPATH.
Once you compile HelloServlet3.java (which will automatically
cause ServletUtilities.java to be compiled), copy (don't move!)
the entire coreservlets subdirectory from your development location to
install_dir/webapps/ROOT/WEB-INF/classes. Then,
access the servlet with the URL
http://localhost/servlet/coreservlets.HelloServlet3 (again, note that it
is a dot, not a slash, between the package name and the servlet name). You
should get a simple HTML page that says "Hello (3)".
OK, so you have a development directory. You can compile servlets with or without
packages. You know which directory the servlet classes belong in. You know the URL
that should be used to access them. (Actually,
http://hostname/servlet/ServletName is just the default URL; you can also
use the web.xml file to customize that URL; for details,
see the Web app section.) But how do you move the
class files from the development directory to the deployment directory?
Copying each one by hand every time is tedious and error prone. Once you
start using Web applications, copying individual files becomes even
more cumbersome.
There are several options to simplify the process. Here are a few of the most popular
ones. If you are just beginning with servlets and JSP, you probably want to start
with the first option and use it until you become comfortable with the development
process. Note that I do not list the option of putting your code directly in the server's
deployment directory. Although this is one of the most common choices among
beginners, it scales so poorly to advanced tasks that I recommend you steer clear of it
from the start.
- Copy to a shortcut or symbolic link.
- Use the
-d option of javac.
- Let your IDE take care of deployment.
- Use
ant or a similar tool.
Details on these four options are given below.
Go to install_dir/webapps/ROOT/WEB-INF, right-click on the classes
directory, and select Copy. Then go to your development directory, right-click, and
select Paste Shortcut (not just Paste). Note that if you use my
preconfigured Jakarta Tomcat version,
this shortcut is already in your C:\Servlets+JSP directory.
Now, whenever you compile a packageless
servlet, just drag the class files onto the shortcut.
When you develop in packages, use
the right mouse to drag the entire package directory
(e.g., the coreservlets directory) onto
the shortcut, release the mouse, and select Copy. On Unix/Linux, you can use symbolic
links (created with ln -s) in a manner similar to that for Windows shortcuts.
An advantage of this approach is that it is simple. So, it is good for beginners who
want to concentrate on learning servlets and JSP, not deployment tools. Another
advantage is that a variation applies once you start using
your own Web applications.
For instance, with Tomcat, you can easily make your own Web application by
putting a copy of the install_dir/webapps/ROOT directory into your
development directory and renaming it (for example,
to testApp). Now, to deploy your Web application,
just make a shortcut to install_dir/webapps
and copy the entire Web application directory (e.g., testApp)
each time by using the right mouse to drag the directory that contains your
Web application onto this shortcut and selecting Copy (say Yes when asked
if you want to replace existing files). The URL
stays almost the same as it was without Web applications:
just insert the name of the directory after
the hostname (e.g., replace http://localhost/blah/blah with
http:/localhost/testApp/blah/blah).
Note that the
preconfigured Tomcat version
already contains all the test files, has shortcuts from the development directory
to the deployment locations, and has shortcuts to start and stop the server.
One disadvantage of this approach is that it requires repeated copying if you use
multiple servers. For example, I previously had
Apache Tomcat, Macromedia JRun, and Caucho Resin
on my desktop system and regularly test my code with all three servers.
A second disadvantage is
that this approach copies both the Java source code files and the class files to the
server, whereas only the class files are needed. This does not matter on your
desktop development server, but when you get to the "real" deployment server, you won't want to
include the source code files.
By default, the Java compiler (javac) places
class files in the same directory as the
source code files from which they came. However,
javac has an option (-d) that lets
you designate a different location for the class files. You need only specify the
top-level directory for class files--javac will
automatically put packaged classes in
subdirectories that match the package names. So, for example,
I could compile the HelloServlet2 servlet as follows (line break
added only for clarity; omit it in real life).
javac -d install_dir/webapps/ROOT/WEB-INF/classes
HelloServlet2.java
You could even make a Windows batch file or Unix shell script or alias that makes
a command like servletc expand to
javac -d install_dir/.../classes.
See
http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javac.html for more details on
-d and other javac options.
An advantage of this approach is that it requires no manual copying of class files.
Furthermore, the exact same command can be used for classes in different packages
since javac automatically puts the class files in
subdirectories matching the package names.
The main disadvantage of this approach is that it applies only to Java class files; it won't
work for deploying HTML and JSP pages, much less entire Web applications.
Most
servlet- and JSP-savvy development environments (e.g.,
Eclipse, JBuilder, NetBeans, Java Studio Creator) have options that let you tell the
IDE where to deploy class files for your project. Then, when you tell the IDE to
build the project, the class files are automatically deployed to the proper location
(package-specific subdirectories and all).
An advantage of this approach, at least in most IDEs, is that it can deploy HTML
and JSP pages and even entire Web applications, not just Java class files. A disadvantage
is that it is an IDE-specific technique and thus is not portable across systems.
Developed by the Apache foundation's Jakarta project, ant is a tool
similar to the Unix make utility.
However, ant is written in the Java programming
language (and thus is portable)
and is touted to be both simpler to use and more powerful
than make. Many servlet
and JSP developers use ant for compiling and deploying.
The use of ant is especially
popular among Tomcat users and with those developing Web applications.
For general information on using ant, see
http://jakarta.apache.org/ant/manual/.
See
Tomcat Documentation
for specific guidance on using ant with Tomcat.
The main advantage of this approach is flexibility:
ant is powerful enough to handle
everything from compiling the Java source code files, to copying class files, to producing
WAR files. The disadvantage of ant is the overhead of learning to use
it; there is more of a learning curve with ant
than with the other techniques in this section.
If you prefer not to individually make each of the changes described in this tutorial,
you can
download a version of Jakarta Tomcat that has all of these changes already made.
All you have to do is unzip the file and set your
JAVA_HOME and CLASSPATH variables, and you are ready to run.
In particular, this Tomcat version:
- Has the port changed from 8080 to 80 (so you do not have to
type the port number in the URL).
- Has servlet reloading turned on (so you do not have to restart
the server if you change a servlet .class file).
- Has the invoker servlet enabled (so you can invoke servlets
with http://localhost/servlet/ServletName, without
making changes to web.xml or restarting the server).
- Includes the sample HTML page, JSP page, servlets, and
utility classes needed to test your setup.
- Includes a sample development directory with shortcuts to
ROOT, ROOT/WEB-INF/classes, startup.bat,
and shutdown.bat.
- Includes an autoexec.bat file that sets the
PATH,
CLASSPATH, and JAVA_HOME variables.
Be sure you edit this file to refer to the proper JDK path,
and be sure to save your original autoexec.bat file, if you have one.
For learning and practicing specific servlet and JSP techniques, it is simplest
to use Tomcat's default Web application (ROOT) and to use the "invoker servlet"
that lets you run servlets by putting /servlet/ServletName at the end of
the URL. When you start developing your real project, however, you almost always use
custom Web applications (and never use the invoker servlet). This section
gives a quick summary on the use of Web applications in Tomcat. For more
details, see the Web application sections of the
JSP and servlet training materials page.
| Learning |
Deployment |
- Use default Web application (ROOT on Tomcat)
- Use default URLs (http:///servlet/ServletName)
- Advantages
- Simpler. Just drop the servlet in the right location and test immediately.
This is far easier than editing web.xml every time you create
a new servlet.
- Can test without restarting server or editing web.xml (although Tomcat
6.0 usually notices when web.xml has been modified, and reloads the Web
app automatically when it has)
|
- Use a custom Web application (on Tomcat, a
directory in install_dir/webapps with
structure similar to ROOT)
- Register custom URLs in WEB-INF/web.xml
- Advantages
- URLs look better. No class names in the URLs.
- Advanced features (init params, security, filters, etc.) depend on
your using registered URLs. The invoker servlet is just a convenience
for initial testing; never use it for real applications!
|
Using custom Web apps involves the following steps:
- Making a directory whose structure mirrors the structure of
the default Web application.
- Updating your
CLASSPATH
- Using the directory name in the URL
- Using web.xml to assign custom URLs
- HTML, JSP, images, style sheets, and other regular Web
content goes in the top-level directory (or any subdirectory other
than WEB-INF or META-INF).
- The web.xml file goes in the WEB-INF subdirectory
- Servlets and other classes go either in
WEB-INF/classes (unpackaged servlets) or a subdirectory of
WEB-INF/classes that matches the package name.
- On Tomcat, entire directory is deployed in install_dir/webapps.
One of the simplest approaches is to create the Web app in your
development directory (e.g., C:\Servlets+JSP), then copy the
entire directory to install_dir/webapps whenever you
want to test it. Simplify the process by keeping
a shortcut to install_dir/webapps
in C:\Servlets+JSP.
Note that you can also deploy using WAR files instead of regular directories.
A WAR file is just a JAR file (which is just a ZIP file) with a .war extension.
You can create WAR files using jar, WinZip, or the Windows XP
"Create Compressed Folder" R-Mouse option. If you use WAR files, a directory
such as myWebApp should become myWebApp.war, and the top-level
directory within the WAR file should be WEB-INF (i.e., do not repeat
myWebApp within the WAR file).
If your Web application directory is myWebApp, your
CLASSPATH should include
mainDevelDir/myWebApp/WEB-INF/classes. A convenient trick
is to include .. and ../.. in your
CLASSPATH so that you never need to
update your CLASSPATH as long as you stick with singly and doubly nested
packages. The CLASSPATH setting in the
preconfigured Tomcat version uses
this trick.
All URLs should be of the form http://hostname/myWebApp/... . For example,
if Hello.html is in the top-level directory of the Web app and you
are running on your desktop system, once the Web app is
deployed (copied to tomcat_dir/webapps), the file would be accessed with
http://localhost/myWebApp/Hello.html. In general, you use the same URLs
as for the default Web app (ROOT) except that you insert /myWebApp right
after the hostname.
First, you use servlet and servlet-mapping elements to
give the servlet an address relative to the Web application, as below:
(note that the servlet-name is arbitrary, but you have to use the same
name in both the servlet and servlet-mapping entries)
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>coreservlets.HelloServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
If you deployed HelloServlet2 in the
myWebApp application using the invoker servlet, it would go in .../myWebApp/WEB-INF/classes/coreservlets
and be invoked with the URL http://localhost/myWebApp/servlet/coreservlets.HelloServlet2.
If you used a registered URL of servlet2 as above, the class file would still go in
.../myWebApp/WEB-INF/classes/coreservlets, but it would be invoked with the URL
http://localhost/myWebApp/servlet2
|