Preface

Since I wrote the first edition of this book, servlets and the server-side Java platform have grown in popularity beyond everyone’s wildest expectations. Adoption is pervasive. Web server vendors now offer servlet support as a standard feature. The Java 2, Enterprise Edition (J2EE), specification has included servlets as a core component, and application server vendors wouldn’t be caught dead without a scalable servlet implementation. It’s more than just vendor-driven hype too. Servlets have become the basis for JavaServer Pages (JSP) and other frameworks, and servlet technology now supports such high-traffic sites as ESPN.com and AltaVista.com.

Not surprisingly, the servlet landscape looks somewhat different today than it did when the first edition went to print. The Servlet API has undergone two revisions, with a third revision on the way. The familiar startup companies Live Software and New Atlanta that once made money selling the JRun and ServletExec servlet engines (now called servlet containers) have gotten themselves noticed and were purchased by larger web-focused companies, Allaire and Unify, respectively. They now offer features above and beyond basic servlet support in an effort to differentiate themselves.

Amazingly, the official javax.servlet and javax.servlet.http packages have been the first Java classes to be officially released as open source. They were transferred to the Apache Software Foundation (ASF) and now reside at http://jakarta.apache.org. The packages continue to follow the Servlet API specification, but bug fixes and specification updates can now be handled by a set of trusted open source developers—including yours truly, who recently had the chance to fix a bug to improve conditional GET request handling in HttpServlet. In addition, the server that acts as the Servlet API reference implementation was also transferred to the ASF and made available as open source under the name Apache Tomcat. Tomcat has since become one of the most popular servlet containers. For more information, see http://opensource.org.

The servlet world has changed, and this book brings you up-to-date. It explains everything you need to know about Java servlet programming, from start to finish. The first five chapters cover the basics: what servlets are, what they do, and how they work. The following 15 chapters are where the true meat is—they explore the things you are likely to do with servlets and the tools you’re likely to use. You’ll find numerous examples, several suggestions, a few warnings, and even a couple of true hacks that somehow made it past technical review.

Servlet API 2.2

This edition of the book covers Version 2.2 of the Servlet API, which went to “public release” status in August 1999 and to “final release” status in December 1999. The first edition of this book covered Version 2.0. Changes between Versions 2.0 and 2.2 have been substantial:

  • Rules have been provided that define how servlets can be distributed across multiple backend servers.

  • Servlets now make use of pluggable web applications, which can be configured and deployed in a server-independent manner.

  • Servlet security has been greatly improved.

  • Servlets can now delegate request handling to other server components.

  • Servlets can now share information using their ServletContext.

  • There’s a way to abstract servlet resources to support distributed access.

  • Servlets now have more control over session management.

  • Response output buffering has been added.

  • Control over HTTP headers has been enhanced.

  • More advanced error handling can now be used.

  • The API has been “cleaned up” to make method names more consistent and predictable.

  • The Servlet API is now defined by a formal specification document, with future API updates managed by the formal Java Specification Request (JSR) process.

  • Servlets are now integrated into the umbrella Java 2 platform, Enterprise Edition (J2EE), specification.

All these changes, and many other more minor changes, are fully explained in this new edition. This second edition also has extensive coverage of the most exciting area of servlet development: techniques for building on the servlet base to easily and efficiently create dynamic content for real-world sites. In this edition you’ll find tutorials on five of the most popular open source servlet-based content creation technologies:

  • JavaServer Pages (JSP), the Sun standard, developed and released in conjunction with servlets

  • Tea, created by the Walt Disney Internet Group (formerly GO.com), used for high-traffic sites like ESPN.com, NFL.com, Disney.com, DisneyLand.com, GO.com, and Movies.com

  • WebMacro, created by Semiotek and used by the search engine AltaVista

  • XMLC, created by Lutris Technologies to leverage the power of XML technology for the Web, used by innovative sites like customatix.com

  • The Element Construction Set (ECS), created by Apache to handle the most demanding programming needs

This second edition also introduces WAP, the Wireless Application Protocol, and explains how to create servlet-based web applications for wireless devices.

Servlet API 2.3

At the time of the writing, Servlet API 2.3 is under development. However, it has not yet been finalized. Consequently, the text in this edition includes in various places a brief mention of the changes expected in the Servlet API 2.3. In addition, the final chapter of this book takes a thorough look at the October 2000 draft specification of the Servlet API 2.3, which should help you become familiar with the latest features that the Servlet API 2.3 will offer. We should point out, however, that these specifications are still subject to change, and the released version may differ slightly from the material presented here.

Readers of the First Edition

Readers of Java Servlet Programming, 1st ed. will find this book comprehensively updated for Servlet API 2.2 and, where possible, Servlet 2.3. Every chapter has enjoyed substantial improvement from the first edition, and there are six new chapters covering servlet-based content creation techniques, as well a seventh new chapter, Enterprise Servlets and J2EE, that explains how servlets integrate into the J2EE platform.

Due to the significant impact the pluggable web applicationmodel has made across all aspects of servlet programming, we recommend readers of the first edition read each chapter of interest and take note of the new mechanisms that exist for accomplishing the traditional tasks. For readers whose time is limited, we include for your convenience a list of the most significant changes in Section P.5 later.

Audience

Is this book for you? It is if you’re interested in developing applications to be deployed on the Web. Specifically, this book was written to help:

J2EE programmers

Servlets are an integral part of the Java 2, Enterprise Edition, standard. Programmers developing for J2EE servers can learn how best to integrate servlets into other backend technologies.

JSP programmers

JavaServer Pages (JSP) are built on top of servlets. To take full advantage of JSP requires an understanding of servlets, which this book provides. This book also includes a tutorial on JSP as well as the four leading alternatives to JSP.

Java applet programmers

It has always been difficult for an applet to talk to a server. Servlets make it easier by giving the applet an easy-to-connect-to, Java-based agent on the server.

CGI programmers

CGI is a popular method of extending the functionality of a web server. Servlets provide an elegant, efficient alternative.

Other server-side programmers

There are many CGI alternatives including FastCGI, PHP, NSAPI, WAI, ISAPI, ASP, and now ASP+. Each of these has limitations regarding portability, security, performance, and/or integration with backend data sources. Servlets tend to excel in each of these areas.

What You Need to Know

When we first started writing this book, we found to our surprise that one of the hardest things was determining what to assume about you, the reader. Are you familiar with Java? Have you done CGI or other web application programming before? Or are you getting your feet wet with servlets? Do you understand HTTP and HTML, or do those abbreviations seem perfectly interchangeable? No matter what experience level we imagined, it was sure to be too simplistic for some and too advanced for others.

In the end, this book was written with the notion that it should contain predominantly original material: it could leave out exhaustive descriptions of topics and concepts that are well described online or in other books. Scattered throughout the text, you’ll find several references to these external sources of information.

Of course, external references only get you so far. This book expects you are comfortable with the Java programming language and basic object-oriented programming techniques. If you are coming to servlets from another language, we suggest you prepare yourself by reading a book on general Java programming, such as Learning Java, by Patrick Niemeyer and Jonathan Knudsen (O’Reilly). You may want to skim quickly the sections on applets and Swing (graphical) programming and spend extra time on network and multithreaded programming. If you want to get started with servlets right away and learn Java as you go, we suggest you read this book with a copy of Java in a Nutshell, by David Flanagan (O’Reilly), or another Java reference book at your side.

This book does not assume you have extensive experience with web programming, HTTP, and HTML. But neither does it provide a full introduction to or exhaustive description of these technologies. We’ll cover the basics necessary for effective servlet development and leave the finer points (such as a complete list of HTML tags and HTTP 1.1 headers) to other sources.

About the Examples

In this book you’ll find more than a hundred servlet examples. The code for these servlets is all contained within the text, but you may prefer to download the examples rather than type them in by hand. You can find the code online and packaged for download at http://www.oreilly.com/catalog/jservlet2. You can also see many of the servlets in action at http://www.servlets.com.

All the examples have been tested using the Apache Tomcat 3.2 server running in standalone mode, using the Java Virtual Machine (JVM) bundled with the Java Development Kit (JDK) 1.1.8 and 1.2.2, on both Windows and Unix. A few advanced examples require features that Tomcat does not support in standalone mode; in these cases the examples were tested against various other servers as noted in the text. The Apache Tomcat server is the official Servlet API reference implementation, available for free under an open source license from http://jakarta.apache.org.

This book also contains a set of utility classes—they are used by the servlet examples, and you may find them helpful for your own general-purpose servlet development. These classes are contained in the com.oreilly.servlet package. Among other things, there are classes to help servlets parse parameters, handle file uploads, generate multipart responses (server push), negotiate locales for internationalization, return files, manage socket connections, and act as RMI servers, as well as a class to help applets communicate with servlets. Since the first edition, there are also new classes to help servlets send email messages, cache responses, and autodetect servlet API support. The source code for most of the com.oreilly.servlet package is contained within the text; and the complete latest version is also available online (with javadoc documentation) for download from http://www.servlets.com.[1]

Organization

This book consists of 20 chapters and 6 appendixes, as follows:

Chapter 1

Explains the role and advantage of Java servlets in web application development. The second edition has been updated with additional server information.

Chapter 2

Provides a quick introduction to HTTP and the things an HTTP servlet can do. Demonstrates basic web page generation and introduces the notion of pluggable web applications. The second edition covers web applications and their XML-based deployment descriptors.

Chapter 3

Explains the details of how and when a servlet is loaded, how and when it is executed, how threads are managed, and how to handle the synchronization issues in a multithreaded system. Persistent state capabilities are also covered. The second edition includes new rules for context reloading and registering servlets, a new section on server-side caching, and a new sidebar on super.init(config).

Chapter 4

Introduces the most common methods a servlet uses to receive information—about the client, the server, the client’s request, and itself. Also demonstrates a reusable class to handle file uploads. The second edition discusses setting information in the deployment descriptor, getting a servlet’s name, accessing temporary directories, handling context init parameters, determining the Servlet API version, assigning servlet mappings, and accessing abstract resources. It also demonstrates an improved, more flexible file upload component.

Chapter 5

Describes how a servlet can generate HTML, return errors and other status codes, buffer responses, redirect requests, write data to the server log, and send custom HTTP header information. The second edition contains new coverage of response buffering, a truly useful redirection example, and new sections on configuring error pages and error handling.

Chapter 6

Looks at some of the interesting things a servlet can return: WAP/WML content for wireless devices, dynamically generated images, compressed content, and multipart responses. The second edition adds the WAP/WML coverage, welcome file lists, a discussion of PNG, an improved server-side image cache, and more details on generating compressed content.

Chapter 7

Shows how to build a sense of state on top of the stateless HTTP protocol. The first half of the chapter demonstrates the traditional session-tracking techniques used by CGI developers; the second half shows how to use the built-in support for session tracking in the Servlet API. The second edition includes the rules for web application sessions, material on new session method names, a discussion of how to manage timeouts, and applet-based session tracking.

Chapter 8

Explains the security issues involved with distributed computing. Demonstrates how to make use of standard servlet hooks for user account management and how to build a more powerful system using custom authentication and authorization. Also explains a servlet’s role in secure SSL communication. Has been updated in its entirety in this second edition.

Chapter 9

Shows how servlets can be used for high-performance web-database connectivity. Includes a tutorial on JDBC. The second edition contains a demonstration of configuring connections with a properties file, a new guestbook example, and a new section on JDBC 2.0.

Chapter 10

Describes how servlets can be leveraged by an applet that needs to communicate with the server. Updated for this second edition.

Chapter 11

Discusses why servlets need to communicate with one another and how they can collaborate by sharing information or making calls on one another. Has been updated in its entirety in this second edition.

Chapter 12

Discusses advanced servlet features needed for enterprise sites: distribution of load and J2EE component integration. New in the second edition.

Chapter 13

Shows how a servlet can read and generate multilingual content. The second edition explains how to use javac to manage encodings and how to use new API methods to manage locales.

Chapter 14

Demonstrates the Tea framework, an elegant yet powerful templating engine. New in the second edition.

Chapter 15

Discusses the WebMacro framework, similar to Tea but with several different design decisions. New in the second edition.

Chapter 16

Gives short coverage on ECS, an object-oriented approach to page creation. New in the second edition.

Chapter 17

Provides an overview of XMLC, a page creation approach with an XML bent. New in the second edition.

Chapter 18

Explains JSP, the Sun standard technology in which web pages are autocompiled into servlets. New in the second edition.

Chapter 19

Presents a junk drawer full of useful servlet examples and tips that don’t really belong anywhere else. The second edition includes a localized parameter parser, a new email class, an updated regular expression section, a new third-party tool section, and additional performance tips.

Chapter 20

Illustrates the upcoming changes in the 2.3 version of the Servlets API, which is expected to be released in mid-2001. New in the second edition.

Appendix A

Contains a full description of the classes, methods, and variables in the javax.servlet package. The second edition has been updated for Servlet API 2.2.

Appendix B

Contains a full description of the classes, methods, and variables in the javax.servlet.http package. The second edition has been updated for Servlet API 2.2.

Appendix C

Presents an annotated reference for the web.xml deployment descriptor’s Document Type Definition. New in the second edition.

Appendix D

Lists the status codes specified by HTTP, along with the mnemonic constants used by servlets.

Appendix E

Lists the character entities defined in HTML, along with their equivalent Unicode escape values.

Appendix F

Lists the suggested charsets servlets may use to generate content in several different languages.

Please feel free to read the chapters of this book in whatever order you like. Reading straight through from front to back ensures that you won’t encounter any surprises, as efforts have been made to avoid forward references. If you want to skip around, however, you can do so easily enough, especially after Chapter 5—the rest of the chapters all tend to stand alone. One last suggestion: read Section 19.7 of Chapter 19 if at any time you find a piece of code that doesn’t work as expected.

Conventions Used in This Book

Italic is used for:

  • Pathnames, filenames, and program names.

  • New terms where they are defined.

  • Internet addresses, such as domain names and URLs.

Boldface is used for:

  • Particular keys on a computer keyboard.

  • Names of user interface buttons and menus.

Constant width is used for:

  • Anything that appears literally in a Java program, including keywords, datatypes, constants, method names, variables, class names, and interface names.

  • All Java code listings.

  • HTML documents, tags, and attributes.

Constant width italic is used for:

  • General placeholders that indicate that an item is replaced by some actual value in your own program.

Constant width bold is used for:

  • Command-line entries.

Request for Comments

Please help us to improve future editions of this book by reporting any errors, inaccuracies, bugs, misleading or confusing statements, and plain old typos that you find anywhere in this book. Email your bug reports and comments to us at: . (Before sending a bug report, however, you may want to check for an errata list at http://www.oreilly.com/catalog/jservlet2 to see if the bug has already been submitted.)

Please also let us know what we can do to make this book more useful to you. We take your comments seriously and will try to incorporate reasonable suggestions into future editions.

Acknowledgments

While I was working on this second edition, a friend said to me, “It must be easier for you to write a second edition; you already wrote the book once.” I thought about that for a minute, laughed, and replied, “It is easier, but not nearly as easy as I’d hoped!”

Looking back, I believe the reason has little to do with books and more to do with technology. The first edition covered Servlet API 2.0, a specification developed over about two years. This second edition covers Servlet API 2.2 and 2.3, representing roughly two years of additional design work. So it only makes sense from that perspective that if the first edition took a year of active writing, then the second edition should take something similar. And, in fact, it did: about nine months.

There are many who have helped in the writing of this book to whom I am profoundly indebted. First and foremost are the book’s technical reviewers: James Duncan Davidson, Servlet API Specification lead for APIs 2.1 and 2.2, and Danny Coward, lead for the upcoming API 2.3. I can’t say enough good things about James and Danny. Not only have they provided me with invaluable assistance and advice throughout the writing of the book, they have given us all a wonderful platform for web programming.

My thanks also to the many developers who donated their expertise to help with the content creation chapters (and in many cases actually created the technology being discussed): Reece Wilton and Brian O’Neill for Tea, Justin Wells for WebMacro, Jon Stevens for ECS, Mark Diekhans and Christian Cryder for XMLC, and Hans Bergsten and Craig McClanahan for JSP.

I’d also like to thank Bob Eckstein, the book’s editor, whose handwritten edits were always insightful, if sometimes unreadable. Bob took over editing duties from Paula Ferguson after she became responsible for managing O’Reilly’s web and scripting books.

My thanks also to Jim Grisham, who helped locate all varieties of machine and browser types for testing examples; Magnus Stenman of Orion, who explained how the Orion Server implements J2EE; Justyna Horwat, called by some the Tag Library Goddess, for answering questions about JSP tag libraries; and Ethan Henry, who helped with suggestions on servlet performance tuning.

I can’t forget Brett McLaughlin, author of Java and XML (O’Reilly) and the cocreator of JDOM. His cooperating with me on JDOM actually slowed down the book, but the speed with which he writes inspires me, and besides, with the acknowledgment he gave to me in his book, I have to say something here!

And finally, thanks to my girlfriend, Kathlyn Bautista, who didn’t complain if I worked Sundays but made me never want to.

Jason Hunter
November 2000

Acknowledgments from the First Edition

In a sense, this book began March 20, 1997, at the Computer Literacy bookstore in San Jose, California. There—after a hilarious talk by Larry Wall and Randall Schwartz, where Larry explained how he manages to automate his house using Perl—I met the esteemed Tim O’Reilly for the first time. I introduced myself and brazenly told him that someday (far in the future, I thought) I had plans to write an O’Reilly book. I felt like I was telling Steven Spielberg I planned to star in one of his movies. To my complete and utter surprise, Tim replied, “On what topic?” So began the rollercoaster ride that resulted in this book.

There have been several high points I fondly remember: meeting my editor (cool, she’s young too!), signing the official contract (did you know that all of O’Reilly’s official paper has animals on it?), writing the first sentence (over and over), printing the first chapter (and having it look just like an O’Reilly book), and then watching as the printouts piled higher and higher, until eventually there was nothing more to write (well, except the acknowledgments).

There have been a fair number of trying times as well. At one point, when the book was about half finished, I realized the Servlet API was changing faster than I could keep up. I believe in the saying, “If at first you don’t succeed, ask for help,” so after a quick talent search I asked William Crawford, who was already working on Java Enterprise in a Nutshell, if he could help speed the book to completion. He graciously agreed and in the end helped write two chapters, as well as portions of the appendixes.

There are many others who have helped in the writing of this book, both directly and indirectly. I’d like to say thank you to Paula Ferguson, the book’s editor, and Mike Loukides, the Java series editor, for their efforts to ensure (and improve) the quality of this book. And to Tim O’Reilly for giving me the chance to fulfill a dream.

Thanks also to my managers at Silicon Graphics, Kathy Tansill and Walt Johnson, for providing more encouragement and flexibility than I had any right to expect.

I can’t say thank you enough to the engineers at Sun who were tremendously helpful in answering questions, keeping me updated on changes in the Servlet API and promptly fixing almost every bug I reported: James Duncan Davidson (who looks the spitting image of James Gosling), Jim Driscoll, Rob Clark, and Dave Brownell.

Thanks also to the members of the mailing list, whose questions and answers have shaped the content of this book; Will Ramey, an old friend who didn’t let friendship blind his critical eye; Mike Engber, the man to whom I turned when I had run out of elegant workarounds and was ready to accept the crazy things he comes up with; Dave Vandegrift, the first person to read many of the chapters; Bill Day, author of Java Media Players, who helped intangibly by going through the book writing process in parallel with me; Michael O’Connell and Jill Steinberg, editors at JavaWorld, where I did my first professional writing; Doug Young, who shared with me the tricks he learned writing seven technical books of his own; and Shoji Kuwabara, Mieko Aono, Song Yung, Matthew Kim, and Alexandr Pashintsev for their help translating “Hello World” for Chapter 13.

I’d like to say a big thank you to the book’s technical reviewers, whose constructive criticism has done much to improve this work: Mike Slinn, Mike Hogarth, James Duncan Davidson, Dan Pritchett, Dave McMurdie, and Rob Clark. I’m still in shock that it took one reviewer just three days to read what took us a full year to write!

Finally, thanks to Mom and Dad, for your love and support and for the time you spent long ago teaching me the basics of writing. And thanks to Kristi Taylor, who made the small time away from work a pleasure.

And Grandpa, I wish you could have seen this.

Jason Hunter
June 1998

First and foremost, thanks to Shelley Norton, Dr. Isaac Kohane, Dr. James Fackler, and Dr. Richard Kitz (plus a supporting cast whose contributions were invaluable), whose assistance and early support have made everything since possible. Also, to Martin Streeter of Invantage, Inc., for his support during this project.

Without Rob Leith, Roger Stacey, and Fred Strebeigh, I would probably still be stuck in the passive voice. Dale Dougherty offered me money in exchange for words, a twist of events that I still haven’t gotten over. Andy Kwak, Joel Pomerantz, and Matthew Proto, brave souls all, were willing to read drafts and listen to complaints at one o’clock in the morning.

And, of course, to Mom and Dad for their years of support, and to my sister Faith for (usually) letting me get away with being a nerd.

William Crawford
July 1998


[1] This book does not come with a CD-ROM. Bundling a CD-ROM increases the cost of production and the cost to you. It’s our belief anyone reading this book has access to an Internet connection, and you’d rather save your money and simply download the example code off the Web. Plus, we don’t see much point in bundling evaluation copies of the various web and application servers. Considering the breakneck pace of innovation in the servlet market, the bundled servers would be obsolete before the book went to press. The same evaluation versions are available online, and we recommend you download the latest releases yourself. Just remember, if you plan to read the book offline, you might want to download the example code and a copy of the Apache Tomcat web server the next chance you get. The download links are at http://www.servlets.com.

Get Java Servlet Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.