Table Of ContentSECOND EDITION
Tomcat
The Definitive Guide
Jason Brittain with Ian F. Darwin
Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo
Tomcat: The Definitive Guide, Second Edition
by Jason Brittain with Ian F. Darwin
Copyright © 2008 O’Reilly Media, Inc. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (safari.oreilly.com). For more information, contact our
corporate/institutional sales department: (800) 998-9938 orcorporate@oreilly.com.
Editor: Simon St.Laurent Indexer: Tolman Creek Design
Production Editor: Loranah Dimant Cover Designer: Karen Montgomery
Copyeditor: Nancy Reinhardt Interior Designer: David Futato
Proofreader: Loranah Dimant Illustrator: Jessamyn Read
Printing History:
June 2003: First Edition.
October 2007: Second Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’ReillyMedia,Inc.Tomcat:TheDefinitiveGuide,theimageofasnowleopard,andrelatedtradedress
are trademarks of O’Reilly Media, Inc.
Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun
Microsystems,Inc.,intheUnitedStatesandothercountries.O’ReillyMedia,Inc.isindependentofSun
Microsystems.
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedas
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors
assume no responsibility for errors or omissions, or for damages resulting from the use of the
information contained herein.
This book uses RepKover™, a durable and flexible lay-flat binding.
ISBN-10: 0-596-10106-6
ISBN-13: 978-0596-10106-0
[M]
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
1. Getting Started with Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Installing Tomcat 1
Starting, Stopping, and Restarting Tomcat 17
Automatic Startup 29
Testing Your Tomcat Installation 34
Where Did Tomcat Come From? 35
2. Configuring Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
A Word About Using the Apache Web Server 38
Relocating the Web Applications Directory 39
Changing the Port Number from 8080 42
Java VM Configuration 51
Changing the JSP Compiler 54
Managing Realms, Roles, and Users 55
Controlling Sessions 70
Accessing JNDI and JDBC Resources 75
Servlet Auto-Reloading 78
Customized User Directories 78
Tomcat Example Applications 80
Common Gateway Interface (CGI) 80
The Tomcat Admin Webapp 82
v
3. Deploying Servlet and JSP Web Applications in Tomcat . . . . . . . . . . . . . . . . . 86
Layout of a Web Application 93
Deploying an Unpacked Webapp Directory 95
Deploying a WAR File 100
Hot Deployment 106
Working with WAR Files 107
The Manager Webapp 108
Automation with Apache Ant 111
Symbolic Links 124
4. Tomcat Performance Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Measuring Web Server Performance 127
External Tuning 153
Internal Tuning 156
Capacity Planning 164
Additional Resources 167
5. Integration with the Apache Web Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
The Pros and Cons of Integration 170
Installing Apache httpd 174
Apache Integration with Tomcat 177
Tomcat Serving HTTP over the APR Connector 194
6. Tomcat Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Securing the System 202
Multiple Server Security Models 204
Using the SecurityManager 205
Granting File Permissions 208
Setting Up a Tomcat chroot Jail 213
Filtering Bad User Input 224
Securing Tomcat with SSL 241
7. Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
server.xml 260
web.xml 316
tomcat-users.xml 333
catalina.policy 333
catalina.properties 334
context.xml 335
vi | Table of Contents
8. Debugging and Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Reading Logfiles 336
Hunting for Errors 337
URLs and the HTTP Conversation 337
Debugging with RequestDumperValve 342
When Tomcat Won’t Shut Down 343
9. Building Tomcat from Source. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
Installing Apache Ant 348
Obtaining the Source 349
Downloading Support Libraries 351
Building Tomcat 352
10. Tomcat Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
Clustering Terms 355
The Communication Sequence of an HTTP Request 356
Distributed Java Servlet Containers 366
Tomcat 6 Clustering Implementation 370
JDBC Request Distribution and Failover 388
Additional Resources 389
11. Final Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Supplemental Resources 391
Community 395
A. Installing Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
B. jbchroot.c. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
C. BadInputValve.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
D. BadInputFilter.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
E. RPM Package Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
Table of Contents | vii
Preface
1
TomcathaseasedthelivesofthousandsofJava™developers,supplyingthemwitha
free environment for testing and deploying web applications. Tomcat has proved its
mettle in all kinds of environments, providing the foundation you’ll need to apply
your Java expertise to the Web.
What’s This Book About?
TomcatisaJavaservletcontainerandwebserverfromtheApacheSoftwareFounda-
tion(http://tomcat.apache.org).Awebserveris,ofcourse,aprogramthatdishesout
webpagesinresponsetorequestsfrom,forexample,ausersittingatawebbrowser.
But web servers aren’t limited to serving up static HTML pages; they can also run
programs in response to user requests and return the dynamic results to the user’s
browser.ThisisanaspectoftheWebthatApache’sTomcatisverygoodatbecause
TomcatprovidesbothJavaservletandJavaServerPages(JSPs)technologies(inaddi-
tiontoservingtraditionalstaticpagesandexternalCGIprogramswritteninanypro-
gramming language). The result is that Tomcat is a good choice for use as a web
server for many applications, including using it as a high performance production
web server. And it’s a very good choice if you want a free, open source (http://
opensource.org)servletandJSPengine.Itcanbeusedstandaloneandinconjunction
with other web servers such as Apachehttpd.
This book is about how to use Tomcat itself. If you’re looking for detailed informa-
tion and tutorials about how to write web applications, be sure to read Java Servlet
Programming by Jason Hunter with William Crawford (O’Reilly).
ix
Why an Entire Book on Tomcat?
Can’t you just download and run Tomcat from the Apache Software Foundation’s
website?Well,ofcourseyoucan,andyou’llneedto,butthereisalotmoretoTom-
catthanjustgettingitrunning.You’llgetmoreoutofTomcatifyouunderstandhow
and why it was written. So in Chapter1, Getting Started with Tomcat, we explain
that. You will then be better able to make informed decisions on choices you might
need to make when installing Tomcat, so we spend the rest of the chapter on the
installation and startup procedures.
InChapter2,ConfiguringTomcat,weshowyouallaboutconfiguringTomcat.Wetalk
about when you should use Tomcat as a standalone web server and servlet container
and when it’s best to use Tomcat with the Apache httpd web server. Then, we show
youhowtoconfigurerealms,roles,users,servletsessions,andJNDIresources,includ-
ing JDBC DataSources. Next, we show how to turn on and off the auto-reloading of
servlets,howtorelocatethewebappsdirectory,andhowtomapuserhomedirectories
for access through Tomcat. Then, we go over how to enable and disable the example
web applications and how to enable common gateway interface scripting in Tomcat.
Andfinally,wecloseoutthechapterbyintroducingyoutotheTomcatadministration
web application, which allows you to configure Tomcat through your web browser.
With Tomcat installed and configured just the way you like it, you’re ready to learn
more about servlet and JSP web applications and how to deploy them into your
Tomcat. In Chapter3, Deploying Servlet and JSP Web Applications in Tomcat, we
showyouthelayoutofawebapplication,howtodeployawebapplication,andhow
to deploy individual servlets and JSP pages. Next, we show you how to build web
application archive files and how to deploy them. To make things less tedious, we
reviewhowtoautomatethedeploymentsofyourwebapplicationsbycopying,using
the built-in manager web application, and using the Jakarta Ant build tool.
OnceyouhaveTomcatservingyourwebapplication,youmaywanttodosomeper-
formance tuning. In Chapter4, Tomcat Performance Tuning, we show you how to
measure and improve your Tomcat’s performance. We go over adjusting the num-
ber of processor Threads, JVM and OS performance issues as they relate to Tomcat,
turning off DNS lookups, and how to speed up JSPs. We round out the chapter by
discussing how capacity planning can affect performance.
Tomcat works as a complete standalone web server. It supports static web pages,
externalCGIscripts,andmanyoftheotherparaphernaliaassociatedwithawebsite.
However,Tomcat’sforte,itsraisond’etre,istobethebestservletandJSPengineon
the block. These are the things it does best. If you already run Apache’s httpd web
server and don’t want to change everything all at once, Chapter5, Integration with
theApacheWebServer,coverstheuseofTomcatwithApachehttpdandtalksabout
theseveralwaysofmakingTomcatthrive“infrontof”or“behind”anApachehttpd
installation.
x | Preface
Whether you’re providing e-commerce, putting up a mailing list, or running a per-
sonalsite,whenyou’reconnectedtotheInternet,yoursiteisexposedtoalotofpeo-
ple, including a few weirdos who think it’s OK to exploit the vulnerabilities in your
server software for fun and/or profit. Because security is important, we devote
Chapter6,Tomcat Security, to the topic of how to keep the online thugs at bay.
In Chapter7, Configuration, we talk about the Tomcat configuration files, server.xml
and web.xml, as well as tomcat-users.xml, catalina.policy, catalina.properties, and con-
text.xml files. Each can be modified to control how Tomcat works.
When something goes wrong with your Tomcat or a web application, Chapter8,
DebuggingandTroubleshooting,showsyousomewaystodiagnosetheproblem.We
showyouwhattolookforinthelogfiles,howthewebbrowserinteractswithTom-
cat’swebserverduringarequest,howtogetverboseinformationaboutaparticular
request, and what to do if Tomcat just won’t shut down when you tell it to.
Not everyone wants to run a prebuilt binary release of Tomcat, so in Chapter9,
Building Tomcat from Source, we show you how to compile your own Tomcat. We
showyoustep-by-stephowtoinstalltheApacheAntbuildtool,downloadallneces-
sary support libraries, and build your Tomcat.
If you’ve got more request traffic than a single Tomcat can handle, or if you want
your site to keep serving requests even if one of your servers crashes, your site may
needtorunonmorethanoneTomcatserver,ormorethanoneApache,oracombi-
nation of the two. Sometimes the only solution is more hardware. In Chapter10,
TomcatClustering,weshowyousomeoptionsforrunningtwoormoreTomcatserv-
let containers in parallel for both fault tolerance and higher scalability, and we dis-
cuss the pros and cons of various clustering approaches.
InChapter11,FinalWords,wegiveanoverviewoftheTomcatopensourceproject’s
communityresources,includingdocs,mailinglists,otherwebsites,andmore.These
arevaluableresourcesforsolvinganyproblemsyoumayhavewithfutureversionsof
Tomcat, and they can also help you get more involved in the development of Tom-
cat if that is one of your goals.
Dependingonyouroperatingsystem,installingJavamaynotbeasstraightforwardas
youthink.ToensurethatTomcatrunswellonyourservercomputer,inAppendixA,
Installing Java, we show you step-by-step how to install a Java runtime, and explain
some Java issues to watch out for.
Preface | xi
Who This Book Is For
The book is written for anyone who wants to learn about the Tomcat servlet con-
tainer. You do not have to be a programmer to use Tomcat or this book; all of the
Javaprogrammingis,asmentionedabove,tuckedawayinsideservletsorothercom-
ponents. You may be a system or network administrator who wants to run a small
simple web site. You may be an experienced Apache Web Server webmaster who
needs to run one or more servlets or JSPs as part of a larger site, or a programmer
who is developing Java web components and wants to get up to speed quickly on
using Tomcat as a web application server during development and in production.
Maybeyou’rerunningoneofthemanyJavaEEserversthatincludeTomcatastheir
web container. For any of these reasons and for any other readers, this book pro-
vides an excellent introduction to Tomcat.
Conventions Used in This Book
The following typographic devices are used:
Italic
Used for filenames, URLs, Java classes, and for new terms when they are defined.
Constant width
Used for code examples, XML elements, and commands.
constant width bold
Indicates user input or lines of particular note in code examples.
constant width italic
Indicates text that should be replaced with user-supplied values.
Indicates a tip, suggestion, or general note.
Indicates a warning or caution.
Additionally, the initials SRV with a dotted-decimal number after them refers to the
indicated section in the Servlet Specification, Version 2.5. For example, SRV.6.5
referstoSection6,subsection5oftheServletSpecification.Similarly,JSPwithadot-
tednumberreferstothegivensectionintheJSPspecification.Youcandownloadthe
servlet and JSP specifications from http://java.sun.com/products/servlet and http://
java.sun.com/products/jsp, respectively.
xii | Preface
Using Code Examples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,youmayusethecodein
this book in your programs and documentation. You do not need to contact us for
permissionunlessyou’rereproducingasignificantportionofthecode.Forexample,
writing a program that uses several chunks of code from this book does not require
permission.SellingordistributingaCD-ROMofexamplesfromO’Reillybooksdoes
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example
code from this book into your product’s documentation does require permission.
Weappreciate,butdonotrequire,attribution.Anattributionusuallyincludesthetitle,
author,publisher,andISBN.Forexample:“Tomcat:TheDefinitiveGuide,SecondEdi-
tion,byJasonBrittainwithIanF.Darwin.Copyright2008O’ReillyMedia,Inc.,978-0-
596-10106-0.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us atpermissions@oreilly.com.
We’d Like to Hear from You
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any addi-
tional information. You can access this page at:
http://www.oreilly.com/catalog/9780596101060
To comment or ask technical questions about this book, send email to:
bookquestions@oreilly.com
For more information about our books, conferences, Resource Centers, and the
O’Reilly Network, see our web site at:
http://www.oreilly.com
There are also web sites for this book by its authors:
http://tomcatbook.darwinsys.com
http://tomcatbook.brittainweb.org
Preface | xiii