BUY THIS BOOK
Add to Cart

Print Book $39.99


Add to Cart

Print+PDF $51.99

Add to Cart

PDF $31.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £24.99

What is this?

Looking to Reprint or License this content?


Tomcat: The Definitive Guide
Tomcat: The Definitive Guide, Second Edition By Jason Brittain, Ian F. Darwin
October 2007
Pages: 494

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Getting Started with Tomcat
Because Tomcat is written in Java, some people assume that you have to be a Java guru to use it. That is not so! Although you need to know Java to modify the internals of Tomcat or to write your own servlet programs, you do not need to know any Java to use Tomcat or to write or maintain many JavaServer Pages (JSPs). You can have JSPs that use "JavaBeans" or "JSP Custom Tags"; in both cases, you are simply using Java components that a developer has set up for you.
In this chapter, we explain how to install Tomcat, get it running, and test it to make sure that it's functioning properly.
As of this writing, there are several production-ready versions of Tomcat available, but we strongly suggest you use the latest stable version of the 6.0 branch or whichever is the latest stable version of Tomcat by the time you read this. See the Apache Tomcat home page (http://tomcat.apache.org) to find the latest stable version. For Tomcat versions 5.5 and 6.0, this book provides an abundance of answers and explanations about the general concepts of how Tomcat works, in addition to showing rich detail about how to use these popular versions of Tomcat.
There are several paths to getting Tomcat up and running. The quickest one is to download and run the compiled binary. Tomcat is written in Java, which means you need to have a modern and complete Java runtime installed before you can build or test it. Read to make sure you have Java installed properly. Do not skip this step; it is more important than it sounds!
One of the benefits of open source projects is that programmers find and fix bugs and make improvements to the software. If you're not a programmer, there is little or nothing to be gained from recompiling Tomcat from its source code, as you are not interested in this level of interaction. Also, if you're not an experienced Tomcat developer, attempting to build and use your own Tomcat binaries may actually cause problems because it is relatively easy to build Tomcat in ways that quietly disable important features. To get started quickly, you should download an official release binary package for your system.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing Tomcat
There are several paths to getting Tomcat up and running. The quickest one is to download and run the compiled binary. Tomcat is written in Java, which means you need to have a modern and complete Java runtime installed before you can build or test it. Read to make sure you have Java installed properly. Do not skip this step; it is more important than it sounds!
One of the benefits of open source projects is that programmers find and fix bugs and make improvements to the software. If you're not a programmer, there is little or nothing to be gained from recompiling Tomcat from its source code, as you are not interested in this level of interaction. Also, if you're not an experienced Tomcat developer, attempting to build and use your own Tomcat binaries may actually cause problems because it is relatively easy to build Tomcat in ways that quietly disable important features. To get started quickly, you should download an official release binary package for your system.
If you want some hints on compiling from source, see .
There are two levels of packaging. The Apache Software Foundation publishes binaries in the form of releases and nightly builds. Other organizations rebundle these into RPM packages and other kinds of installers for Linux, "packages" for BSD, and so forth. The best way to install Tomcat depends on your system. We explain the process on several systems: Linux, Solaris, Windows, Mac OS X, and FreeBSD.
Tomcat 6 requires any Java runtime version 1.5 or higher (which Sun's marketing group calls "Java 5"). We suggest that you run Tomcat 6 on Java 1.6 or higher, however, due to the additional features, fixes, and performance improvements that Java 1.6 (or higher) JVMs offer.
Tomcat is available in at least two different binary release forms for Linux users to choose from:
Multiplatform binary releases
You can download, install, and run any of the binary releases of Tomcat from Apache's web site regardless of the Linux distribution you run. This format comes in the form of gzipped tar archives (tar.gz files) and zip archive files. This allows you to install Tomcat into any directory you choose, and you can install it as any user ID in the system. However, this kind of installation is not tracked by any package manager and will be more difficult to upgrade or uninstall later. Also, it does not come with an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Starting, Stopping, and Restarting Tomcat
Once you have the installation completed, you will probably be eager to start Tomcat and see if it works. This section details how to start up and shut down Tomcat, including specific information on each supported operating system. It also details common errors that you may encounter, enabling you to quickly identify and resolve any problems you run into.
The correct way to start and stop Tomcat depends on how you installed it. For example, if you installed Tomcat from a Linux RPM package, you should use the init script that came with that package to start and stop Tomcat. Or, if you installed Tomcat on Windows via the graphical installer from tomcat.apache.org, you should start and stop Tomcat as you would any Windows service. Details about each of these package-specific cases are given in the next several sections. If you installed Tomcat by downloading the binary release archive (.zip or .tar.gz) from the Tomcat downloads page—what we'll call the generic installation case—you should use the command-line scripts that reside in the CATALINA_HOME/bin directory.
There are several scripts in the bin directory that you will use for starting and stopping Tomcat. All the scripts you will need to invoke directly are provided both as shell script files for Unix (.sh) and batch files for Windows (.bat). lists these scripts and describes each. When referring to these, we have omitted the filename extension because catalina.bat has the same meaning for Microsoft Windows users that catalina.sh has for Unix users. Therefore, the name in the table appears simply as catalina. You can infer the appropriate file extension for your system.
Table : Tomcat invocation scripts
Script
Purpose
catalina
The main Tomcat script. This runs the java command to invoke the Tomcat startup and shutdown classes.
cpappend
This is used internally, and then only on Windows systems, to append items to Tomcat classpath environment variables.
digest
This makes a crypto digest of Tomcat passwords. Use it to generate encrypted passwords.
service
This script installs and uninstalls Tomcat as a Windows service.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Automatic Startup
Once you have Tomcat installed and running, you can set it to start automatically when your system reboots. This will ensure that every time your system comes up, Tomcat will be running and handling requests. Unix users will make changes to their init scripts, and Windows users will need to set Tomcat up as a service. Both approaches are outlined in this section.
If you've installed Tomcat via an RPM package, getting it to run on a reboot is just a matter of telling your system to run the tomcat or tomcat55 service (depending on which RPM package you installed) when it enters a multiuser run level.
If you know how to use chkconfig, as the root user you can simply chkconfig tomcat on for the run level(s) of your choice.
Use the chkconfig command to make the tomcat service start in the run level(s) of your choice. Here's an example of how to make it start in run levels 2, 3, 4, and 5:
# chkconfig --level 2345 tomcat on
If chkconfig does not see the tomcat service, try tomcat55 instead (the JPackage.org RPM package's init script has this name). Otherwise, you probably did not install Tomcat as an RPM package. Below, we show how to add a simple init script to make it work anyway.
Now, query your configuration to make sure that startup is actually set:
# chkconfig --list tomcat
tomcat    0:off   1:off   2:on   3:on    4:on    5:on    6:off
Now, reboot and see if Tomcat starts up when the system comes back up.
If you didn't use the RPM package to install Tomcat, you can still set up Tomcat to start on reboots. Tomcat does not come with a Linux init script, but it is simple to create one that would just start Tomcat at boot time and stop it on shutdown.- is a very simple Tomcat init script for Linux.
Example . A Tomcat init script for Linux
#!/bin/sh
# Tomcat init script for Linux.
#
# chkconfig: 2345 96 14
# description: The Apache Tomcat servlet/JSP container.

JAVA_HOME=/usr/java/jdk1.6.0_02
CATALINA_HOME=/opt/apache-tomcat-6.0.14
export JAVA_HOME CATALINA_HOME

exec $CATALINA_HOME/bin/catalina.sh $*
Save this script in a file named tomcat and change the file ownership and group to
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Testing Your Tomcat Installation
Once you have Tomcat installed and started, you should confirm that it has successfully started up. Open the URL http://localhost:8080 (it's port 8180 if you're running FreeBSD and installed the FreeBSD port) in a browser to verify that you see output like that shown in .
Figure : Success!
If you have changed the port number in server.xml, you will need to use that same port here.
Now that Tomcat is up and running, you can begin to customize its behavior, which is discussed in .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Where Did Tomcat Come From?
The first Java servlet container was Sun Microsystems's Java Web Server (JWS). Sun's Java Web Server was a product that Sun offered for sale. It was more affordable than most commercial server offerings, but it did not enjoy widespread commercial success—largely due to Java still being new, and servlets being only recently introduced. One of Java Web Server's main outgrowths, however, was the Java Servlet Specification as a de facto standard that Sun documented and made available separately. One big success of JWS was that it put Java servlets in the limelight.
In 1996, a plethora of free Java servlet containers became popular. Apache's JServ and CERN/W3C's Jigsaw were two of the earliest open source Java servlet containers. They were quickly followed by several more, including Jetty (http://jetty.mortbay.org), the Locomotive Application Server (see the web archives at http://web.archive.org/web/*/http://www.locomotive.org), Enhydra (http://www.enhydra.org), and many others. At the same time, commercial servlet containers were starting to become available as the industry embraced the Java Servlet standard; some of these were WebLogic's Tengah, ATG's Dynamo, and LiveSoftware's JRun.
In 1997, Sun released its first version of the Java Servlet Development Kit (JSDK). The JSDK was a very small servlet container that supported JSP and had a built-in HTTP 1.0 web server. In an effort to provide a reference implementation for developing servlets, Sun made it available as a free download to anyone wanting to experiment with the new Java server-side standard. It also had success as a testing and development platform in preparation for deployment to a commercial server.
In the first half of 1998, Sun announced its new JSP specification, which built upon the Java Servlet API and allowed more rapid development of dynamic web application content. After the 2.1 release of the JSDK (now called the JSWDK to add "Web" to the name), James Duncan Davidson at Sun rewrote the core of the older JSDK server. At the heart of this new Java servlet engine reference implementation was a brand new servlet container named Tomcat, and its version number started at 3.0 because it was a follow-on to version 2.1 that it replaced.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Configuring Tomcat
Once Tomcat is up and running, you will want to keep an eye on it, to help it along occasionally. Troubleshooting application servers can be intimidating. In this chapter, we show you the various places to look for information about your server, how to find out why things aren't working, and give you some examples of common mistakes in setting up and configuring Tomcat. Want to run Tomcat on the default HTTP port 80? We show you some ways of doing that. You will also find some pointers on what JVM startup switch settings you can use. You'll learn how you can manage the web user accounts that Tomcat knows about and how to configure security realms to customize which users can access your Tomcat's web content. We also show you how to configure your Tomcat to open a pool of connections to your database for your webapp to use. Next, we show how to configure Tomcat to use Common Gateway Interface (CGI) programs. Finally, we discuss the Tomcat administration web application, a tool for helping you with the task of keeping Tomcat running.
You can use Tomcat as a standalone combination web server and servlet container, or you can use it as an add-on servlet container for a separate web server. Both are common, and each is appropriate in certain situations.
The Tomcat authors have spent quite a bit of time and effort to make Tomcat run efficiently as a standalone web server; as a result, it is easy to set up and run a web site without worrying about the issues involved with connecting Tomcat to a third-party web server. Tomcat's built-in web server is a highly efficient HTTP 1.1 server that is quite fast at serving static content once configured correctly for the computer on which it runs. They've also added features to Tomcat that one would expect from full-featured web servers, such as CGI scripting, a home directory mapper, and more.
The Tomcat authors also realized that many companies and other organizations already run the Apache httpd web server and may not want to switch from that server to Tomcat's built-in web server. The Apache Web Server is the most popular web server on the Internet according to many web surveys and is arguably the most flexible, fully featured, and supported web server ever written. Even if users running Apache
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Word About Using the Apache Web Server
You can use Tomcat as a standalone combination web server and servlet container, or you can use it as an add-on servlet container for a separate web server. Both are common, and each is appropriate in certain situations.
The Tomcat authors have spent quite a bit of time and effort to make Tomcat run efficiently as a standalone web server; as a result, it is easy to set up and run a web site without worrying about the issues involved with connecting Tomcat to a third-party web server. Tomcat's built-in web server is a highly efficient HTTP 1.1 server that is quite fast at serving static content once configured correctly for the computer on which it runs. They've also added features to Tomcat that one would expect from full-featured web servers, such as CGI scripting, a home directory mapper, and more.
The Tomcat authors also realized that many companies and other organizations already run the Apache httpd web server and may not want to switch from that server to Tomcat's built-in web server. The Apache Web Server is the most popular web server on the Internet according to many web surveys and is arguably the most flexible, fully featured, and supported web server ever written. Even if users running Apache httpd wanted to switch web servers, it may be difficult for them to do so because their web sites are often already too integrated with Apache's features.
Keep in mind, however, that Apache httpd may not be more efficient at serving your content than Tomcat standalone is. Tomcat's web server is highly optimized, and today's Java runtimes are very good at natively compiling Tomcat so that the resulting binary it is running is also highly optimized for your operating system and architecture. Configuring Tomcat so that all of its requests must first travel through Apache httpd may actually slow down Tomcat's response times, and it is usually the performance of the dynamic content that web server administrators need to improve.
With these issues in mind, if you're still considering using Apache httpd and Tomcat together, you will want to refer to for an in-depth look at how to hook together these two programs.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Relocating the Web Applications Directory
Depending on how you install and use Tomcat, you may not want to store your web application's files in the Tomcat distribution's directory tree. For example, if you plan to upgrade your installation of Tomcat periodically, you probably shouldn't modify Tomcat's files—for instance, CATALINA_HOME/conf/server.xml, which you will likely need or want to modify in order to configure Tomcat for your site—because when you install a newer version of Tomcat's files into the Tomcat installation directory tree, you may overwrite the server.xml and any other configuration files that you modified for your site. This is the case whether you use an operating-system-specific package of Tomcat (an RPM package, etc.) or an operating-system-neutral archive of Tomcat (.zip or .tar.gz). Upgrading the Tomcat package means that the native package manager may replace your configuration files with stock versions from any new version of the same package that you upgrade to. Usually, package managers save the file they're replacing if it is a known configuration file, but even then it's a pain to know what you need to do to get your site back in running order. Regardless of how you installed Tomcat, though, it may be a good idea to keep your web site's files cleanly separate from the Tomcat distribution files.
Another scenario in which you may not want to store your web application files in the Tomcat distribution's directory tree is if you install one copy of the Tomcat distribution, but you wish to run more than one instance of Tomcat on your server computer. There are plenty of reasons why you may want to run more than one Tomcat instance, such as having each one serve different content on different TCP ports and you want each webapp in its own JVM so they can be operated independently. In this case, you don't want files from one instance clashing with files from another instance.
To have one Tomcat distribution installed and run two or more Tomcat JVM instances that are configured differently, you must keep each JVM instance's files separate. During normal usage of Tomcat, the server reads configuration from the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Changing the Port Number from 8080
Tomcat, in a default installation, is configured to listen on port 8080 rather than the conventional web server port number 80. This is sensible because the default port 80 is often in use already and because opening a network server socket listener on the default port 80 requires special privileges on Linux, Solaris, BSD, and other non-Windows operating systems. However, the majority of the time it still makes sense to run Tomcat on port 80 instead of the default 8080.
To change the port number, edit the main Connector element in the server.xml file. Find the XML tag that looks something like this:
<!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />
Just change the port attribute from 8080 to 80, and restart Tomcat. Unless that port number is already in use or you lack administrative permission to start a server on port 80, Tomcat should now be operational on port 80.
Running a server on port 80 normally requires that it run with high administrative permissions, such as the root account on Linux, Solaris, BSD, and other non-Windows operating systems.
You (or your site security policies) may not want to trust Tomcat running as root, but we have not heard even a single reported incident where a machine's security was compromised because Tomcat was running as root. If you're worried about this, there are other ways of making Tomcat answer on port 80 without running Tomcat's JVM process as root. The following sections explain a few ways of doing just that.
It is true that the JVM process must run as the root user in order to open a server socket on port 80 on non-Windows operating systems. But, the JVM would not need to run as root if something outside the JVM process could relay all port 80 TCP connections to Tomcat on some port higher than 1024 (such as port 8080, for example). Tomcat can open its web server on port 8080, and something else with the proper permissions can relay port 80 TCP connections to Tomcat's port 8080. This is often referred to as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Java VM Configuration
How Tomcat will run depends in part on how you configure the Java virtual machine in which it runs. For example, if you do not configure the JVM to be able to use up to a specified amount of heap memory, it will use only up to the default amount of memory, which may not be enough for the web application you're trying to run. If Tomcat does not have sufficient memory to run your webapp on startup, it will just serve error pages to all web clients. If Tomcat has enough memory to start your webapp but not enough to process as many concurrent requests as you configured your connector to allow into Tomcat, some or all of the requests will get an error response or a dropped connection.
There is a plethora of JVM startup switch settings that you may set. See for the settings we chose as some of the most useful JVM startup switch settings you can use when running Tomcat.
Table : Java VM configuration options
Use
JVM option
Meaning
Memory setting
-Xms384M
Sets the heap memory size at JVM startup time.
Memory setting
-Xmx384M
Sets the maximum heap memory size the JVM can expand to.
Debugging security
-Djava.security.debug=all
Turns on all debug output for security.
Debugging
-enableassertions
Enables assertion checking.
Debugging
-verbose:class
Enables verbose class loading debug output.
Debugging
-verbose:gc
Enables verbose garbage collection debug output.
Graphical
-Djava.awt.headless=true
Allows the JVM to run without any graphical display software installed.
Localization
-Duser.language=en
Sets the language bundle that Tomcat uses.
Localization
-Dfile.encoding=UTF-8
Sets the default file encoding that Tomcat uses.
Networking
-Djava.net.preferIPv4Stack=true
Configures the JVM to use IPv4 instead of IPv6; thus, any misconfiguration of IPv6 does not prevent Tomcat from working properly over Ipv4. On some operating systems such as FreeBSD, this switch appears to be required for Tomcat to work.
The heap settings are undoubtedly the most important settings to understand and set appropriately. With an overly restrictive memory setting, Tomcat will either run too slow or fail with an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Changing the JSP Compiler
By default, Tomcat version 5.5 and higher compiles JSP pages using a bundled Eclipse JDT compiler. See the Eclipse JDT core page at http://www.eclipse.org/jdt/core for more information about this Java compiler. The JDT compiler is written in pure Java and performs the same job for Tomcat as the JDK's javac command. It is a relatively new Java compiler, and as such may not be as mature or as robust as javac, or other older compilers.
Since Tomcat bundles the JDT compiler, Tomcat can compile and serve JSP page content when running on top of either a JRE or the full JDK. Even though the JDK has a javac compiler, since Tomcat contains its own Java compiler, Tomcat does not need the JDK's Java compiler, as long as Tomcat's bundled Java compiler can compile everything that javac can. Because the JDT compiler is newer, it is still maturing, and you may find that some Java 1.5 or 1.6 source code language features are not fully implemented yet. Because it is the Java compiler that the Eclipse IDE uses, quite a bit of effort is going into making it both complete and robust, and there are a large number of people using it and testing it. Still, you may run into a situation where you want to switch Tomcat between the JDT compiler and your JDK's javac compiler.
The way Tomcat 5.5 is written, you have two main Java compiler choices:
  • Use the built-in JDT Java compiler, which is the default.
  • Make some changes to enable Tomcat to use Apache Ant to compile the JSP pages.
Tomcat versions 5.0.x and older do not bundle the JDT Java compiler and by default use Ant's compiler to compile JSPs, so the below procedure will only work with Tomcat versions 5.5.x and higher.
If you choose to enable the use of Ant to compile JSP pages, you may configure Ant to use any of the Java compilers that Ant supports. By default, Ant uses the JDK's javac compiler.
To switch Tomcat from using its default JDT compiler to using Ant, you must:
  1. Move Tomcat's CATALINA_HOME/common/lib/jasper-compiler-jdt.jar file so that it is not used in the common class loader.
  2. Install Apache Ant's ant.jar file into the common/lib/
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Managing Realms, Roles, and Users
The security of a web application's resources can be controlled either by the container or by the web application itself. The Java EE specification (previously known as J2EE) calls the former container-managed security and the latter application-managed security. Tomcat provides several different approaches for handling security through built-in mechanisms, which represent container-managed security. On the other hand, if you have a series of servlets and JSPs that have their own login mechanism, it would be considered application-managed security. In both types of security, users and passwords are managed in groupings called realms. This section details setting up Tomcat realms and using the built-in security features of Tomcat to handle user authentication.
The combination of a realm configuration in Tomcat's conf/server.xml file and a <security-constraint> in a webapp's WEB-INF/web.xml file define how user and role information will be stored and how users will be authenticated for the webapp. There are many ways of configuring each; feel free to mix and match.
In this and future sections, you will see the term context used interchangeably with web application. A context is the technical term used within Tomcat for a web application and has a corresponding set of XML elements and attributes that define it in Tomcat's server.xml file or in its own context XML fragment file.
To use Tomcat's container-managed security, you have to set up a realm. A realm is simply a collection of users, passwords, and roles. Web applications can declare which resources are accessible by which groups of users in their web.xml deployment descriptor. Then, a Tomcat administrator can configure Tomcat to retrieve user, password, and role information using one or more of the realm implementations.
Tomcat contains a pluggable framework for realms and comes with several useful realm implementations: UserDatabaseRealm, JDBCRealm, JNDIRealm, and JAASRealm. Java developers can create additional realm implementations to interface with their own user and password stores as well. To specify which realm should be used, insert a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Controlling Sessions
An HTTP session is a series of interactions between a single HTTP client (e.g., a web browser instance) and a web server such as Tomcat. The servlet specification defines an HttpSession object that temporarily stores information about a user, including a unique session identifier and references to Java objects that the web application stores as attributes of the session. Typical uses of sessions include shopping carts and sites that require users to sign in. Usually, sessions are set to time out after a configurable period of user inactivity, where user inactivity is defined as a pause in requests belonging to the HTTP session. Once a session has timed out, it is said to be an invalid session, and if the user makes a new HTTP request to the site a new, valid session has to be created, usually through a re-login.
Tomcat has pluggable session Managers that handle the logic about how sessions are handled and session Stores to save and load sessions. Not every Manager uses a Store to persist sessions; it is an implementation option to use the Store interface in order to provide pluggable session store capabilities. Robust session Managers will implement some kind of persistent storage for their sessions, regardless of whether they use the Store interface. Specifying a Manager implementation works in a similar fashion to specifying a Realm:
<Manager className="some.manager.implementation.className"
         customAttribute1="some custom value"
         customAttribute2="some other custom value"/>
Almost all of the control over sessions is vested in the Manager and Store objects, but some options are set in web.xml, that is, at the context level. These options are described in detail in .
This Manager is an HTTP session manager. Do not confuse it with the Manager web application described in .
Session persistence is the saving (persisting) to disk of HTTP sessions when the server is shut down and the corresponding reloading when the server is restarted. Without session persistence, a server restart will result in all active user sessions being lost. To users this means they will be asked to log in again (if you're using container-managed security), and they may lose the web page they were on, along with any shopping cart information or other web page state information that was stored in the session. Persisting that information helps to ensure that it won't be lost.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessing JNDI and JDBC Resources
Many web applications will need access to a relational database. To make web applications portable, the Java EE specification requires a database-independent description in the web applications's WEB-INF/web.xml file and allows the container developer to provide a means for providing the database-dependant details; Tomcat developers naturally chose to put this in the server.xml file. Then, the JNDI is used to locate database sources and other resources. Each of these resources, when accessed through JNDI, is referred to as a context.
Watch out! A JNDI context is completely different than a Tomcat context (which is a synonym for "web application"). In fact, JNDI contexts and Tomcat webapp contexts are completely unrelated.
You probably know whether your web application requires a JDBC datasource. If you're not sure, look in the web.xml file for the application, and search for something like this:
<resource-ref>
  <description>
    The database DataSource for the Acme web application.
  </description>
  <res-ref-name>jdbc/JabaDotDB</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>
As an alternative, if you have the Java source code available, you can look for something like this:
Context ctx = new InitialContext(  );
DataSource ds = (DataSource)
  ctx.lookup("java:comp/env/jdbc/JabaDotDB");

Connection conn = ds.getConnection(  );
... Java code that accesses the database ...
conn.close(  );
If you're not familiar with JNDI usage from Java, a DataSource is an object that can hand out JDBC Connection objects on demand, usually from a pool of preallocated connections.
Tomcat uses the Apache DBCP connection pool by default.
In both of the above code snippets, the resource string jdbc/JabaDotDB tells you what you need to configure a reference for in your webapp's Context container element. Find the Context element for your webapp, and insert a Resource element similar to the one shown in .
Example . DataSource: the Resource element inside your webapp's context
<!-- Configure a JDBC DataSource for the user database. -->
<Resource name="jdbc/JabaDotDB"
          type="javax.sql.DataSource"
          auth="Container"
          user="ian"
          password="top_secret_stuff"
          driverClassName="org.postgresql.Driver"
          url="jdbc:postgresql:jabadot"
          maxActive="8"
          maxIdle="4"/>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Servlet Auto-Reloading
Tomcat by default will automatically reload a servlet when it notices that the servlet's class file has been modified. This is certainly a great convenience when debugging servlets; however, bear in mind that in order to implement this functionality, Tomcat must periodically check the modification time on every servlet. This entails a lot of filesystem activity that is unnecessary when the servlets have been debugged and are not changing.
To turn this feature off, you need only set the reloadable attribute in the web application's Context element (in either your server.xml or your context XML fragment file, wherever you've stored your Context element), and restart Tomcat. Once you've done this, you can still reload the servlet classes in a given Context by using the Manager application (detailed in the section "" in Chapter 3).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Customized User Directories
Some sites like to allow individual users to publish a directory of web pages on the server. For example, a university department might want to give each student a public area, or an ISP might make some web space available on one of its servers to customers that don't have a virtually hosted web server. In such cases, it is typical to use the tilde character (˜) plus a user's name as the virtual path of the user's web site:
http://www.cs.myuniversity.edu/˜ian
http://members.mybigisp.com/˜ian
The notion of using ˜ to mean a user's home directory originated at the University of California Berkeley during the development of Berkeley Unix, when the C shell command interpreter was being developed in the late 1970s. This usage has been expanded in the web world to refer to a particular directory inside a user's home directory or more generally a particular user's web directory, typically a directory named public_html.
Tomcat gives you two ways to map this on a per-host basis, using a couple of special Listener elements. The Listener's className attribute should be org.apache.catalina.startup.UserConfig, and the userClass attribute specifies one of several mapping classes. If your system runs Unix and has a standard /etc/passwd file that is readable by the account running Tomcat, and that file specifies users' home directories, use the PasswdUserDatabase mapping class:
<Listener className="org.apache.catalina.startup.UserConfig"
  directoryName="public_html"
  userClass="org.apache.catalina.startup.PasswdUserDatabase"/>
Web files would need to be in directories such as /home/users/ian/public_html or /users/jbrittain/public_html. Of course, you can change public_html to be whatever subdirectory your users put their personal web pages into, but it must be the same subdirectory name for all users within that Tomcat host.
In fact, the directories don't have to be inside a user's home directory at all. If you don't have a password file but want to map from a username to a subdirectory of a common parent directory, such as /home, use the HomesUserDatabase class:
<Listener className="org.apache.catalina.startup.UserConfig"
   directoryName="public_html"
   homeBase="/home"
   userClass="org.apache.catalina.startup.HomesUserDatabase"/>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tomcat Example Applications
When installed out of the box, Tomcat includes a variety of sample applications. These are actually quite useful to people learning how to write JavaServer pages and servlets (look inside the CATALINA_HOME/weabpps and the CATALINA_HOME/conf/Catalina/localhost directories to see what webapps are already present in a fresh installation of Tomcat).
Because these examples are so helpful, you may wish to keep them deployed so you can learn from them; on the other hand, you may not want somebody else's examples showing up on your production web server. In that case, you should remove the example webapps from the CATALINA_HOME/webapps/ directory. One way of doing that is to just move them to a different directory, like this:
# cd $CATALINA_HOME
# mkdir moved-webapps
# mv webapps/*
moved-webapps/
Then, restart Tomcat to put these changes into effect.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Common Gateway Interface (CGI)
As mentioned in the previous section, Tomcat is primarily meant to be a Servlet/JSP container, but it also has the capabilities that one would expect any traditional web server to have. One of these is support for the Common Gateway Interface (CGI). Traditional web servers provide a means for running an external program in response to a browser request, typically used to process a web-based form. This mechanism is named the Common Gateway Interface, or CGI for short. CGI is called common because it can invoke programs in almost any programming or scripting language: Perl, Python, awk, Unix shell scripting, and even Java are all supported options. In reality, you probably wouldn't run Java applications as a CGI due to the startup overhead; elimination of this overhead was what led to the original design of the servlet specification. Servlets are almost always more efficient than CGIs because you're not starting up a new operating-system-level process every time somebody clicks on a link or a button. You can consult a good book on web site management for details on writing CGI scripts.
Tomcat includes an optional CGI servlet that allows you to run legacy CGI scripts; the assumption is that most new backend processing will be done by user-defined servlets and JSPs. A simple CGI is shown in .
Example . CGI demonstration
#! /usr/bin/python

# Trivial CGI demo

print "content-type: text/html"
print ""

print "<html><head>Welcome</head>"
print "<body><h1>Welcome to the output of a CGI under Tomcat</h1>"
print "<p>The subject says all.</p>"
print "</body></html>"
As already mentioned, scripts can be written in almost any language. For the example, we chose Python, and the first line is a bit of Unix that tells the system which interpreter to use for the script; on Windows the filename would have to match some pattern like *.py to produce the same effect. The first few statements print the content type (useful to the browser, of course) and a blank line to separate the HTTP headers from the body. The remaining lines print the HTML content. This is typical of CGI scripts. Of course, most CGI scripts also handle some kind of forms processing, but that is left as an exercise—presumably your CGI scripts are already working in whatever language you regularly use for this purpose.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Tomcat Admin Webapp
Most of the work in this chapter has been figuring out what needs changing in a configuration file, knowing which XML to edit and then editing that file, and restarting either Tomcat or the affected web application. We end the chapter with a look at an alternative way of making changes to Tomcat's configuration—for some versions of Tomcat.
Tomcat versions before 6.0.0 (including 5.5.x and lower versions) included an administration webapp that allowed inspecting and modifying the configuration of Tomcat from a web application running within the same Tomcat instance. But, when the Tomcat developers refactored Tomcat for the 6.0 branch, they did not maintain the Admin webapp, so this webapp does not build or run on Tomcat 6.0.x, nor does the webapp come with Tomcat 6.0.x. If you want to run the Admin webapp, as of this writing, you must run Tomcat version 5.5.x or lower. The Tomcat developers are, however, planning to refactor and include the Admin webapp in the next branch of Tomcat after 6.0. It is possible that by the time you read this there will be a new branch of Tomcat that includes the Admin webapp.
Most commercial Java EE servers provide fully functional administrative interfaces; many of them are accessible as web applications. The Tomcat Admin webapp is a featureful Tomcat administration tool rivaling these commercial offerings. First included in Tomcat 4.1, it provides control over contexts, data sources, users, and groups. You can also control resources such as initialization parameters, as well as users, groups, and roles in a variety of user databases. The list of capabilities will be expanded upon in future releases, but the present implementation has proven itself useful.
To install the Admin webapp, you must download and unpack the Admin webapp's binary release archive over the top of Tomcat's CATALINA_HOME directory of Tomcat.
You must also configure a user who is assigned the admin role. There is no "default user," for security reasons. In CATALINA_HOME/conf/tomcat-users.xml, add a role with the name "admin", and make sure your user account's role memberships include "
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Deploying Servlet and JSP Web Applications in Tomcat
Now that you've got Tomcat installed, you will invariably need to deploy web applications. This chapter shows you web applications composed of servlets, JSPs, and other files, and several approaches for deploying them. It ends with a discussion of the Manager web application, which can handle some deployment operations for you.
Before Java servlets, web applications were mostly written in C/C++ or Perl. Usually they were made up mainly of static HTML pages and a few CGI scripts to generate the dynamic content portions of the web application. Those CGI scripts could be written in a platform-independent way, although they didn't need to be (and for that reason the scripts often weren't). Also, because CGI was an accepted industry standard across all web server brands and implementations, CGI scripts could be written to be web server implementation-independent. In practice, some are and some aren't. The biggest problem with CGI was that the design made it inherently slow and unscalable.
Another approach to generating dynamic content is web server modules. For instance, the Apache httpd web server allows dynamically loadable modules to run on startup. These modules can answer on preconfigured HTTP request patterns, sending dynamic content to the HTTP client/browser. This high-performance method of generating dynamic web application content has enjoyed some success over the years, but it has its issues as well. Web server modules can be written in a platform independent way. But, there is no web server implementation-independent standard for web server modules—they're specific to the server you write them for and probably won't work on any other web server implementation.
Java brought platform independence to the server, and Sun wanted to leverage that capability as part of the solution toward a fast and platform-independent web application standard. The other part of this solution was Java servlets. The idea behind servlets was to use Java's simple and powerful multithreading to answer requests without starting new processes. You can now write a JSP or servlet-based web application and move it from one servlet container to another, from one computer architecture to another, and run it without any change (in fact, without even recompiling any of its code in almost all cases).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
In order to deploy any webapps into Tomcat, you must deploy them under a Host. A host represents a fully qualified domain name or IP address, such as groovywigs.com, for example. The stock Tomcat server.xml configuration file has a default host named localhost. The fact that this Host is the default Host as well as the only Host means that all HTTP requests entering Tomcat will be mapped to this Host, regardless of what host name is specified in the HTTP requests. For example, if the Host header in an incoming HTTP request says groovywigs.com as the host that the request is destined for, it won't be a match for the only Host name that Tomcat knows about (localhost), so Tomcat will instead map it to the default Host: the same one named localhost.
For example, if you create a webapp for a web site named groovywigs.com, the webapp itself will probably be the root webapp of that site. There are at least a few ways of deploying the webapp, but let's say that you want to deploy it as an unpacked webapp directory (all of the webapp's content resides within one outermost directory) named ROOT. You could deploy that as webapps/ROOT. In this case, the host's name is groovywigs.com.
To deploy the webapp into the groovywigs.com host, you must already have configured Tomcat for the groovywigs.com host. This is pretty easy to do. Edit your server.xml file and find the spot where the first <Host> XML element is defined. Then, add a new <Host> element above it, like this:
<Host name="groovywigs.com" appBase="webapps"
 unpackWARs="true" autoDeploy="true"
 xmlValidation="false" xmlNamespaceAware="false">

  <!-- Context elements for the groovywigs.com host go here. -->

</Host>

<!-- Define the default virtual host
     Note: XML Schema validation will not work with Xerces 2.2.
 -->
<Host name="localhost" appBase="webapps"
      unpackWARs="true" autoDeploy="true"
      xmlValidation="false" xmlNamespaceAware="false">
And, if your Tomcat primarily serves requests for the groovywigs.com host, you should also change your <Engine>'s default host, also in server.xml:
    <!-- Define the top level container in our container hierarchy -->
    <Engine name="Catalina" defaultHost="
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Layout of a Web Application
Tomcat provides an implementation of both the servlet and JSP specifications. These specifications are in turn part of Sun's Java Enterprise Edition. Java EE is designed to let application developers move their applications from one compliant application server (a program that implements the Java EE specification) to another, without significant rewriting or revising. To accomplish this, applications are packaged in very specific, portable ways; for example, as web application archives or enterprise application archives.
The Java Servlet Specification defines the Web Application aRchive (WAR) file format and its file structure for this very purpose. For your webapp to be application-server-implementation-independent, your files must follow certain conventions, such as the directory layout for storing web pages, configuration files, and so on. This general layout is shown in .
Figure : Servlet/JSP web application file layout
As a concrete example, Acme Widgets' site might look like .
Example . Example web application file layout
/
/index.jsp
/products.jsp
/widgets/index.html
/widgets/pricing.jsp
/images/logo.png
/WEB-INF/web.xml
/WEB-INF/classes/com/acme/PriceServlet.class
/WEB-INF/classes/DataHelper.class
/WEB-INF/lib/acme-util.jar
As you can see, the web pages (whether static HTML, dynamic JSP, or another dynamic templating language's content) can go in the root of a web application directory or in almost any subdirectory that you like, except the WEB-INF or META-INF directory trees. Images often go in a /images subdirectory, though this is a convention, not a requirement. The WEB-INF directory has several specific pieces of content. First, the classes directory is where you place any Java class files that are not in a JAR file, whether they are servlets or other class files used by a servlet, JSP, or other part of your webapp's code. Second, the lib directory is where you put any JAR files containing packages of classes. And finally, the web.xml file is known as a deployment descriptor, which contains configuration for the web application, a description of the webapp, and any additional customization.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying an Unpacked Webapp Directory
One way of deploying a web application into Tomcat is to deploy it as a directory of webapp content that is not packed into a WAR file. If you deploy your webapp as an unpacked directory, you won't need to pack it into a WAR file at all—you may go straight to deploying it once you have your webapp's content organized, as shown earlier in .
There are two ways to configure Tomcat to recognize and start your web application, when you first deploy it as an unpacked webapp d