Home Programming Tomcat 6 Developer's Guide

Tomcat 6 Developer's Guide

books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introduction to Tomcat
About this book
While Tomcat is one of the most popular servlet containers, its inner workings still remain a mystery to many developers. If you only have a superficial familiarity of how this container actually functions, much of its power remains untapped and underutilized. This book will provide you with all that you need to undertand how to effectively use Apache Tomcat. This book begins by providing detailed instructions on building a Tomcat distribution. The next few chapters introduce you to the conceptual underpinnings of web servers, the Java EE and servlet specifications, and the Tomcat container. Subsequent chapters address the key Tomcat components, taking care to provide you with the information needed to understand the internal workings of each component. Detailed examples let you walk through a Tomcat installation, stepping into key Tomcat components, as well as into your own custom servlets. During the course of the book you will encounter various structural components such as the Server and Service; containers such as the Engine, Host, Context, and Wrapper; and helpers such as the Loader, Manager, and Valve. You will also see how Tomcat implements the JNDI API to provide both a directory service for storage agnostic access to its resources, as well as a naming service that implements the Java EE Environment Naming Context. Along the way you will learn how various elements of the servlet 2.5 specification, as well as the HTTP RFCs are implemented by a servlet container. By the end of your journey, you will be able to count yourself as part of the elite minority of Java EE web developers who truly understand what goes on under the covers of a servlet container.
Publication date:
December 2009
Publisher
Packt
Pages
416
ISBN
9781847197283

 

Chapter 1. Introduction to Tomcat

It is hard to overemphasize the importance of Apache Tomcat in the realm of Java Enterprise Edition web development. Tomcat began its life as source code that was donated by Sun Microsystems to the Apache Software Foundation (ASF). Since then, it has played a central role in the development and validation of the Java Servlet and JavaServer Pages specifications and has been the official reference implementation for these specifications.s

Its early popularity stemmed from the fact that it was easily integrated with two of the world's most popular web server software, Apache httpd and Microsoft's Internet Information Services (IIS) server.

However, since then, it has evolved into a production-grade product used by multiple large corporations (see a partial list at http://wiki.apache.org/tomcat/PoweredBy).

Tomcat is also found embedded, in part or whole, in various open source application server offerings. Even when using competing commercial application server offerings such as IBM's WebSphere and BEA's WebLogic, developers often use Tomcat to validate the vendor-independence of their applications.

It is also priced just right. It is open source and distributed under the Apache license, meaning it is free for use and modification (see www.apache.org/licenses for details). This also has the side effect of having the source code readily available for examination.

This availability of source code, strict adherence to specifications, and proven track record, combine to make Tomcat a unique learning opportunity for us. This book will assist you in taking the covers off this unique project, so that you get to see exactly how a production-grade servlet container is implemented.

What's the story behind Tomcat?

As I write this, the most current version of Tomcat is 6.0.20, where 6 is the major version, 0 is the minor version, and 20 is the bug fix release number. This version implements, and is completely compliant with, version 2.5 of the Java Servlet specification, and version 2.1 of the JavaServer Pages (JSP) specification.

That's a pretty hefty mouthful, so let's start at the beginning.

Every superhero has an origins story, and Tomcat is no exception. The Tomcat web site lists the available versions at http://tomcat.apache.org/whichversion.html, which shows the first stable release listed as Tomcat 3.x. So what happened to versions 1 and 2?

Tomcat was conceived in November 1998 by James Duncan Davidson at Sun Microsystems, who wrote it to form the core of the JavaServer Web Development Kit (JSWDK) for the Servlet 2.1 specification.

The name 'Tomcat' came to him when he was trying to decide a package name for the code he was working on. He ended up using com.sun.tomcat.

At the time, Apache JServ, a free servlet container, was in the process of being updated to support the Servlet 2.1 specification.

However, this effort was abandoned due to the donation of Tomcat by Sun Microsystems to the Apache Software Foundation, at JavaOne in 1999. It soon came to life as Tomcat version 3.0, the successor to JSWDK 2.1.

This was a major milestone for the open source community as it meant that a commercial package owned and developed by Sun Microsystems, and which implemented the latest Servlet 2.2 and JSP 1.1 specifications, was now being offered to the general public for free.

All of this made the decision to abandon Apache JServ rather uncontroversial.

The focus soon shifted from updating JServ to support the new specification, to getting Tomcat to implement features that were missing. The most important one being the ability to cooperate with the Apache web server. This was critical to the popularity of Tomcat, as it meant that developers could leverage the static file handling capabilities of the Apache web server together with the dynamic capabilities of Tomcat to achieve a well rounded solution. Subsequent Tomcat releases have actually strengthened this connection component.

In addition, Tomcat can now directly serve static content and so is often deployed in standalone mode without a separate web server.

It is interesting to note that Tomcat began life not as its own top level project. Instead, it started humbly as a subproject within the Jakarta project (an umbrella project that covers many subprojects such as Apache Commons, Cactus, and JMeter). It was only in 2005 that it was upgraded to the status of a top level project at Apache.

 

What's the story behind Tomcat?


As I write this, the most current version of Tomcat is 6.0.20, where 6 is the major version, 0 is the minor version, and 20 is the bug fix release number. This version implements, and is completely compliant with, version 2.5 of the Java Servlet specification, and version 2.1 of the JavaServer Pages (JSP) specification.

That's a pretty hefty mouthful, so let's start at the beginning.

Every superhero has an origins story, and Tomcat is no exception. The Tomcat web site lists the available versions at http://tomcat.apache.org/whichversion.html, which shows the first stable release listed as Tomcat 3.x. So what happened to versions 1 and 2?

Tomcat was conceived in November 1998 by James Duncan Davidson at Sun Microsystems, who wrote it to form the core of the JavaServer Web Development Kit (JSWDK) for the Servlet 2.1 specification.

The name 'Tomcat' came to him when he was trying to decide a package name for the code he was working on. He ended up using com.sun.tomcat.

At the time, Apache JServ, a free servlet container, was in the process of being updated to support the Servlet 2.1 specification.

However, this effort was abandoned due to the donation of Tomcat by Sun Microsystems to the Apache Software Foundation, at JavaOne in 1999. It soon came to life as Tomcat version 3.0, the successor to JSWDK 2.1.

This was a major milestone for the open source community as it meant that a commercial package owned and developed by Sun Microsystems, and which implemented the latest Servlet 2.2 and JSP 1.1 specifications, was now being offered to the general public for free.

All of this made the decision to abandon Apache JServ rather uncontroversial.

The focus soon shifted from updating JServ to support the new specification, to getting Tomcat to implement features that were missing. The most important one being the ability to cooperate with the Apache web server. This was critical to the popularity of Tomcat, as it meant that developers could leverage the static file handling capabilities of the Apache web server together with the dynamic capabilities of Tomcat to achieve a well rounded solution. Subsequent Tomcat releases have actually strengthened this connection component.

In addition, Tomcat can now directly serve static content and so is often deployed in standalone mode without a separate web server.

It is interesting to note that Tomcat began life not as its own top level project. Instead, it started humbly as a subproject within the Jakarta project (an umbrella project that covers many subprojects such as Apache Commons, Cactus, and JMeter). It was only in 2005 that it was upgraded to the status of a top level project at Apache.

 

What exactly is Tomcat?


For most users, the typical web interaction can be represented as follows: Joe User enters a Uniform Resource Locator(URL) in the browser's location box to request the resource that is identified by that URL. A URL is composed of a host name, an optional port (which defaults to 80), and the resource being requested.

When a web server receives that request, it first determines whether the resource being requested is static or dynamic in nature.

A static resource is one that is identical no matter how many times, or in what order, that resource is requested. Some examples of these would be a company's logo on a web page, a CSS style sheet, or a typical HTML page.

The web server handles the request for a static resource by simply fetching the identified resource from the appropriate path in which its static content resides (for example, htdocs for Apache), and returning those bytes in the response to the user.

For static resources, a depiction of this request flow is as shown below.

A dynamic resource, on the other hand, indicates a resource that varies its content based on various factors that may include the specific user making the request, the time of day when the request is made, or the presence of additional information in the request that affects how the request is interpreted. Some examples of these would include the current inventory for a specific product in an online store, or the availability of a seat on an airplane.

Most web servers are tuned to deliver blazing fast request handling for static resources. However, they require additional help when dealing with dynamic resources. This help is typically provided by an additional software component that is registered with the web server, called a servlet container on the Java EE platform.

In the IIS world, access to this servlet container is offered by implementing an Internet Server Application Programming Interface (ISAPI) extension, which is a Dynamic Link Library (DLL) that allows you to extend the functionality of IIS. In the Apache world, you access the container using code written in C or C++.

When a request comes in that is directed at a dynamic resource, the web server simply hands off that request to its associated servlet container.

The container then springs into action, invokes the appropriate servlet that represents the requested dynamic resource. This servlet is responsible for generating the response. The generated response is returned by the servlet container to the web server which, in turn, returns it to the requesting user. This interaction is depicted in the following diagram.

A servlet in its most basic form is a Java class that acts as a dynamic web resource. In other words, it can be the target of a client browser's request.

Being a Java class, it can tailor its response according to the payload of the incoming request, the conversation that this request is a part of, as well as other environmental criteria (such as the time of the day or the inventory status from a database).

Note

It is important to note that there is nothing special about this delegation mechanism that restricts it only to dynamic resources. You could configure a web server to also delegate requests for a certain subset of static resources (for example, those within a given URL path) to the servlet container.

JSPs

The problem with using Java code to generate HTML content is that you end up with a lot of string generation and concatenation to generate the actual HTML content, interspersed with actual program logic written in Java. This is an unholy combination as it tends to make the program logic impervious to the person tasked with maintaining your code. In addition, changes to static content now require you to compile the servlet class.

Applying the 80-20 rule very loosely to dynamic content, you might find that 80% of the content of a page is in reality static content. The JavaServer Pages specification was evolved as the solution to this situation. A JSP (JavaServer Page) is a template made up primarily of static content with very specific (and hopefully, few) invocations of Java code to retrieve the dynamic aspects of the page.

The problem of requiring a compilation step was resolved by making a JSP an artificial construct. The container is responsible for transparently parsing a JSP and converting it into a bona fide servlet, compiling it, and then invoking it in the same manner as the other servlets in the application.

As long as the ratio of static to dynamic content is high, that is, as long as there are more static elements than dynamic elements on a page, even non programmers, such as graphic artists, can find their way around a JSP file with some comfort.

This is about as much as we will cover on JavaServer Pages technology in this book.

Servlet container

With all that behind us, we are now ready to answer the question posed by this section's title-what exactly is Tomcat?

Tomcat is classified as a servlet container, that is, an environment within which servlets can live and prosper. As a container, it provides a lot of administrative support to servlets, allowing programmers to focus on the core application logic that is to be implemented, without having to bother about low level specifics such as session management and class loading.

The servlet and JSP specifications describe the service contract that the container promises to provide to the servlets and JSP files that we write. Together, the specifications describe all the services that a container should provide, and specify how the servlet may make use of those services. As with all other Application Programming Interfaces (APIs), the specifications describe the 'what' and leave the 'how' to the implementer of the specific container.

Tomcat serves as the 'reference implementation' of these specifications, and as a result, serves as a guinea pig or canary in the mine shaft for them. In other words, it provides a sample implementation to prove that the specification can indeed be implemented, and serves as a guide for other implementers.

The following diagram provides an early bird's eye view of the responsibilities of a servlet container.

The primary responsibility of a container is to process an incoming request and to generate a corresponding response that is then returned to the client.

A Connector component provides the external interface that allows clients to connect to the container. This component not only accepts incoming connections, but is also responsible for delegating the processing of the request to an available request processor thread. The 'Processors' block in the image denotes multiple threads in a pool that may be used to process the incoming request.

The request processing framework is implemented using a multiple level hierarchy of sub containers (the servlet Engine, virtual hosts, web application contexts, and servlet Wrappers) and nested components (Valves, Listeners, Loaders, Resources, and Security Realms). Note that the '+' sign in the above image indicates that there can be more than one instance of that component. For instance, more than one Host, Context, and servlet Wrapper component may be contained within its parent container.

The result of processing a request is represented by a response, which is then returned through the same Connector.

In addition to the core request processing components, the container also provides support for other aspects of operation, such as logging, security, and JMX monitoring.

In this book, our primary focus will be on the request processing responsibilities of a servlet container. These components form the unshaded boxes in the previous image. Additional topics will be considered only when they are crucial to understanding a request processing component's actions.

Note

It is important to note that a servlet container is a completely different beast from an application server.

In the simplest sense, an application server contains a servlet container, along with other containers, such as an EJB container, an applet container, and an application client container. In addition, an application server provides implementations for a number of Service APIs that are required for heavy duty applications. We will take a closer look at the Java EE platform in Chapter 2.

Examples of application servers include the JBoss Application Server, GlassFish, IBM's WebSphere, and BEA's WebLogic.

Whether or not you should use a full fledged application server, with its support for Enterprise JavaBeans and other Java EE heavy artillery, depends on your application needs.

 

Why this book?


Tomcat is one of the few technology areas that is particularly blessed with a plethora of very well written books, and the Tomcat mailing lists are rather friendly places for new developers. So really, why another book on Tomcat?

The answer is simple. Most of these books and material focus primarily on the set up, administration, and management, of a Tomcat server.

This is no accident. Most web developers rarely have to concern themselves with anything more challenging than setting up a context fragment or changing the default port for Tomcat from 8080 to 80.

As long as a developer understands the basic terminology of web applications (such as the context, the context root) and the structure of a WAR file, most modern Integrated Development Environments (IDEs), such as Eclipse and IntelliJ IDEA, do all the heavy lifting for you.

It seems only appropriate then, for authors to target their books at the typical administrator or deployer.

For its part, Tomcat exposes a myriad of configuration files that enable even an obsessive administrator to fine tune the installation and the Java Virtual Machine as much as desired.

The net result is that your average book contains the customary chapter on installing Tomcat, chapters on configuring it, on deploying servlets into it, on integration with either the Apache httpd web server or Microsoft's IIS, and on securing the installation.

The downside with this approach is that it provides a one-sided view of the software engineering marvel that is Tomcat. You tend to see it as a black box with lots of control switches that you can throw, but you never ever really get a chance to peer into the open vents on the sides of that box.

In this book, I hope to correct that imbalance. I'm going to pry open the service door on the side of that black box, and take you in on an interesting journey through some of the sights that most people rarely get to see. A connector shimmering in the moonlight, the rays of the early morning sun catching an application class loader in its native state, a lumbering valve caught in motion capture frames as it springs into action with surprising agility. There are a lot of fantastical beings that populate this world, if you only dare to venture into it.

In the course of the next few chapters, we will look at Tomcat from the perspective of someone attempting to understand what makes it tick. Our goal will be to understand Tomcat as few others do. We'll not only see the control switches on the outside, but we'll also learn about how these switches affect the machinery within.

 

Gathering our tools


In this section, I'm going to get together all the pieces that you will need for the remainder of this book. If you would like to follow along with the rest of this book, then this section is crucial.

The software that we will download and install includes the following:

  • The Java SE Development Kit (JDK) version 6.0

  • A download verifier

  • Apache Ant 1.7.1

  • Subversion 1.6.3

  • Eclipse 3.5 Galileo

The workstation that I use throughout this book runs a Microsoft Windows operating system (XP Professional or Vista).

Note

The version numbers that are specified were current at the time of writing this text. However, with the speed of product cycles in the open source arena, it is likely that newer versions will be available by the time you read this.

Java Development Kit (JDK) 6.0

JDK 6 can be found at http://java.sun.com/javase/downloads/index.jsp.

As with every download page on the Sun web site, there are enough choices to make your head spin. For our needs, we need the plain vanilla JDK 6.0 that at the time of writing is JDK 6 Update 14.

Once you've picked the Platform: (Windows) and Language: (Multi-language), you will end up with a file named jdk-6u14-windows-i586.exe on your workstation.

Execute this file to install it. Once you have accepted the terms and conditions, and have picked an install directory, the installation process will begin.

Once the JDK has been installed, the installer will prompt you to install the JRE. You may do so if you wish.

Note

The JDK for 64-bit platforms

There are 64-bit versions of the JDK that are available for Windows, Linux, and Solaris. The file for 64-bit Windows is named jdk-6u14-windows-x64.exe.

Verifying downloaded files

Most open source software is hosted on multiple mirror sites, and you are expected to pick your nearest mirror from which to download it. A key question here is how do you ensure that the file that you just downloaded is an exact copy of the version that the open source team intended for download, and there isn't a malicious hacker chuckling with glee to see you install a Trojan on your workstation?

There are a couple of answers to this question—using PGP keys or using a message digest.

The former is more secure as it uses public key cryptography, but as a result is also more complex.

The latter, while simpler to use, is not quite as secure, as the most common digest algorithm (MD5) has some well documented flaws, allowing different files to generate the same digest. In addition, the MD5 digest value itself may have been modified by the hacker so that it matches the compromised file.

Using the principle that any security is better than none, you would compute the MD5 message digest for the downloaded file, and compare that computed value against the published digest for the file.

You can download a digest generator from either www.formilab.ch/md5/ or www.nullriver.com/index/products/winmd5sum.

For example, the MD5 digest for the ZIP file distribution of Tomcat 6.0.18 is:

f7d0c15df19fedf52476767f7ce0b6f8

*apache-tomcat-6.0.18.zip

Apache Ant

Apache Ant or Another Neat Tool is a build automation utility that owes its existence to James Duncan Davidson and Tomcat. It originated as a tool used to build Tomcat itself. But its widespread popularity ensured that it was promoted into its own project, independent of Tomcat, in January 2000.

As Ant is written in Java, it inherits its Write Once Run Anywhere aspect, making it platform independent. Its build directives (by default, in a file named build.xml) are written using XML - another cross platform advantage.

Ant build directives take the form of targets that describe the actions or tasks that must be performed, whether creating, deleting, or copying files and directories, setting classpaths, compiling Java classes, or even packaging your applications.

The ability to define dependencies on targets adds to its flexibility. You can indicate that a compile target depends on other targets that clear out the output directories, fetch the latest changes from your source code repository, and set the classpath.

Finally, throw in the ability to define your own targets, and the sky's the limit!

Download the latest version from http://ant.apache.org/bindownload.cgi and extract the Ant distribution. The version that was current when I wrote this, was Ant 1.7.1.

You need to add Ant to your PATH. On Windows, this is accomplished by opening the System Properties box - by right clicking your My Computer icon and clicking Properties. Pick System from the Control Panel's classic view or press the keyboard shortcut Windows + Pause/Break.

On the Advanced system settings tab, click on Environment Variables tab and edit the Path variable. Add [ANT_HOME]\bin to the end of the path variable, replacing [ANT_HOME] with the absolute path to the location where you extracted the downloaded file.

Note that path variables in Windows are delimited by a semicolon.

Subversion

Next, we need a way to retrieve the latest version of the Tomcat source code, which is currently housed in a Subversion repository.

Subversion was conceived in 2000, when CollabNet, Inc. decided that it was time to write a brand new version control system, and brought on Karl Fogel to head this effort. The stated goal of the original team was to write a better version of CVS, while retaining the familiar elements of CVS, to make it easier for developers to switch without much effort.

Subversion has since dethroned CVS as the system of choice. In particular, it has been adopted as the standard version control mechanism by the Apache Software Foundation.

Subversion, like CVS, uses a copy-modify-merge model. In the copy phase, each developer makes a private copy of the project's source code on to their individual workstations. This copy acts as a sandbox within which each developer may work.

In the modify phase, each developer makes changes in his or her own working copy. The changes made by one developer are not visible to the others. If you need visibility into another developer's changes, you would need to update your working copy from the repository.

In the merge phase, a developer commits his changes back into the source code. If a file was modified by another developer since you checked out your copy, you would then need to merge your changes back into the repository resolving any conflicts as necessary.

Get the latest version of the Subversion Command-Line Client for Windows from http://www.collab.net/downloads/subversion/, which is currently 1.6.3. Execute the downloaded file, CollabNetSubversion-client-1.6.3-3.win32.exe.

The installation is fairly straightforward and only requires that you specify a path name for your installation.

To verify that the software was successfully installed, run the svn --version command from the command prompt. This command should output the version of Subversion that is installed on your workstation.

Obtaining the Tomcat source code

You have two options when trying to download the Tomcat source. You could either use the Subversion version control software, which was described in the last section, or you could simply download the compressed source distribution of Tomcat as a ZIP file. The former option is preferred if you expect to be developing in Tomcat, whereas the latter is simply a snapshot of the code at a given version.

Using Subversion

To obtain the latest source code for Tomcat from the Subversion repository at the ASF, change your working directory to where you want to download your working copy (for example, c:\tomcat), and execute the following at the command line (all on one line):

 svn checkout http://svn.apache.org/repos/asf/tomcat/tc6.0.x/trunk/

When this completes, you will notice that your current directory now contains a trunk subfolder with the source directories for Tomcat.

Note

The above command downloads the most up-to-date version of the source trunk and may result in code that may differ from the descriptions in this text.

If you would like to ensure that you are working with the exact codebase covered in this book, then you should use the following command instead:

svn checkout http://svn.apache.org/repos/asf/tomcat/tc6.0.x/tags/TOMCAT_6_0_20/

This is the 'copy' phase of your interaction with the Subversion version control system. The result of this operation is to make a local copy of Tomcat's latest development code line from the Subversion repository. This lets you play in your own little sandbox, making changes and experimenting for as long as you need.

Tomcat source distribution

If you'd rather not install Subversion, a less invasive option would be to simply download the Tomcat source from the Source Code Distributions section at http://tomcat.apache.org/download-60.cgi.The source for a previous version can be downloaded from http://archive.apache.org/dist/tomcat/tomcat-6/. The only downside with this approach is that the source distribution does not contain a project file for use with the Eclipse IDE. To get these files, point your browser at http://svn.apache.org/repos/asf/tomcat/tc6.0.x/trunk (or to http://svn.apache.org/repos/asf/tomcat/tc6.0.x/tags/TOMCAT_6_0_20 for the version used in this book) and download the .classpath and .project files. Ensure that the downloaded files are named exactly the same as their originals.

Getting ready to build Tomcat

Now, we're ready to get started with building the source that we just downloaded. This is a two step process that utilizes the power of Ant and the build.xml file that exists in the trunk directory. First change directory to the directory to which your source code has been downloaded (or unzipped.).

Downloading dependencies

Now, run the download target:

ant download

The download target downloads a number of binaries that are needed for this build. These artifacts are downloaded to the folder that is identified by the base.path property in the Ant build.properties.default file. By default, this will be /usr/share/java. However, you can change this to a different absolute path such as c:/tomcat/downloads/trunk.

The files that are downloaded include:

  • The native Tomcat connectors (currently at version 1.1.15).

  • The Commons daemon library (version 1.0.1), which is used with jsvc—a Java Service Wrapper that is used to run Tomcat as a non-root user listening on the privileged port 80 on non Windows operating systems.

  • The Eclipse JDT JAR, which is used by Tomcat to compile JSPs.

  • The Nullsoft Scriptable Install System (NSIS)—an open source system to create Windows installers.

  • The Commons Collections library.

  • The Commons Database Connection Pool (version 1.2.2) and Commons Pool (version 1.4). The build-tomcat-dbcp Ant target renames the packages for these Commons projects, for example, by replacing org.apache.commons with org.apache.tomcat.dbcp. The stated goal here is to ensure that the DBCP and Pool classes, used by Tomcat internally, do not conflict with any versions of DBCP or Pool classes that are packaged with individual web applications.

Note

Download errors

I have noticed that the download target sometimes fails when trying to unzip the NSIS with the following error: java.io.IOException: Negative seek offset

In such cases, a manual workaround is to simply download the target ZIP file (in this case http://downloads.sourceforge.net/nsis/nsis-2.37.zip) and unzip it to the folder into which the build script is downloading files. Then, ensure that the test file is present, which in this case is c:/tomcat/downloads/trunk/nsis-2.37/makensis.exe.

Building Tomcat

We're finally ready to build Tomcat using Ant, so run the deploy target.

ant deploy

This target compiles the Java code and builds the binary distribution of Tomcat. Note that you can omit the target name because deploy is defined as the default target in the build.xml file. So the following would be equivalent:

ant

The deploy target builds the Tomcat binaries and copies files out to output\build.

Note

The "clean" target

If you need to start with a clean build, then the clean target is your friend. It clears out all the output folders for a fresh distribution to be laid into it.

Starting up your shiny new Tomcat

From the output\build\bin directory within your Tomcat trunk folder, execute the startup.bat batch file.

startup

This starts up your Tomcat server in a separate command window. Reassuring log messages should be output to your console as shown.

Now, using your favorite browser, type in the URL http://localhost:8080, and marvel at what you have wrought.

Finally, to shut down your server, execute the shutdown.bat batch file.

shutdown

This command closes down the Tomcat server gracefully, and you're done.

Eclipse

We're now on to the home stretch. The ultimate prize for us is to be able to use an IDE to run the Tomcat server. What would be more appropriate for investigating Tomcat, than the free and full featured open source IDE—Eclipse!

Note

While you can simply use your favorite IDE, the Tomcat source distributions include project metadata files only for the Eclipse IDE.

In particular, let's pick Eclipse Galileo, which is the most recent in an annual series of releases that package multiple major projects. Previous releases have been code named Callisto, Europa, and Ganymede.

Galileo was released in June 2009, and includes the core Eclipse project along with almost three dozen other major projects, including the Web Tools Platform project, the Rich Ajax Platform project, and the SOA Tools Platform project.

Eclipse downloads are available at http://www.eclipse.org/downloads/. Make sure that you pick the Eclipse IDE for Java EE Developers version. For Windows, this results in the file eclipse-jee-galileo-win32.zip being copied down to your workstation.

Note

Eclipse for 64-bit Windows

The above link works fine for downloading Eclipse for the most common platforms, including 64-bit Linux. However, you have to work a bit harder to get the 64-bit version for Windows. The downloads for the Eclipse project are available at http://download.eclipse.org/eclipse/downloads/. For safety, click the link associated with the Latest Release version, which is currently at 3.5. These downloads are named eclipse-SDK-[versionNumber]-[platform].zip. For Vista 64, this download is eclipse-SDK-3.5-win32-x86_64.zip.

Unzip the Eclipse distribution to a folder of your choice, and execute eclipse.exe to verify that your IDE starts up.

At startup, you are prompted for a workspace location. A workspace folder is used to house your projects as well as to store metadata about your plugins and your IDE preferences.

In this dialog, you can either point to an existing workspace folder if you have one, or to a new folder location. It is recommended that you pick a folder that lies outside of your Eclipse installation directory so that when you upgrade your Eclipse version, you can simply delete the old installation folder without losing your workspace.

Once Eclipse starts up, dismiss the Welcome screen to proceed to the Workbench, and then select the Window | Preferences menu option to display the Preferences dialog.

In the left pane of this dialog, drill down to Java | Installed JREs, and verify that your previously installed version of JDK 6 shows up. If it doesn't, then click on the Add button to add a reference to your JDK.

We will also set up two classpath variables as shown next— ANT_HOME to point at the base directory for your Ant installation and TOMCAT_LIBS_BASE to point to the directory that holds the files downloaded by the download ant target that you executed while building Tomcat.

Note

If you are building a non-trunk version of Tomcat, then ensure that your TOMCAT_LIBS_BASE classpath variable points to the path to where the ant download target downloads its dependencies.

Next, import the project file that is present in the working copy of the Tomcat trunk. Choose File | Import to open the Import dialog. From this dialog, choose General | Existing Projects into Workspace to import the Eclipse project present in the Tomcat trunk into your new workspace.

Click on Finish to import the project.

A project build begins automatically, and you will get the following screen.

To start up your Tomcat server from within Eclipse, create a Run configuration by choosing the Run | Run Configurations… menu option, and select org.apache.catalina.startup.Bootstrap as the Main class.

Click on Run, and watch the Console pane for output indicating that Tomcat was successfully started.

Now browse on over to http://localhost:8080 to view the Tomcat welcome page.

Congratulations! You're done.

For now, play with this code by placing breakpoints and stepping through interesting code sections. We'll explore these sections in far greater detail in the chapters to come.

In the next couple of chapters, we'll regroup and visit concepts that are necessary for the exploring that we'll be doing in later chapters.

 

Summary


We covered a lot of ground in this chapter. We began by looking at the principles behind a servlet container. We looked at the origins of Tomcat, and we built ourselves our very own server by cobbling together a number of software helpers.

We looked at the JDK, the Ant build tool, the Subversion version control tool, and the Eclipse IDE. We retrieved the latest source from the Tomcat Subversion repository, and we compiled the Java sources to result in a binary distribution of the container.

In the next chapter, we'll explore some of the ideas embodied in the servlet specification.

Latest Reviews (1 reviews total)
Tomcat 6 Developer's Guide
Unlock this book and the full library FREE for 7 days
Start now