On a historical timeline, the saga of Java as a server-side programmer’s tool of choice began in early 1997 when Sun Microsystems released the “Java™ Web Server” beta and Java Servlet Developers Kit.[1] Servlets are a type of Java class that executes on a server. Servlets dynamically handle networked requests and responses, mostly using the Hypertext Transfer Protocol (HTTP). In June 1999, Sun introduced JavaServer Pages (JSPs), which intermingled Java code with JavaScript and HTML template text.

JSPs, as they are now evolving (with JSP Version 2.0), are designed to encapsulate domain logic in standard and custom tags, and separate this domain layer from the JSP component’s presentation logic. The latter concept means “the stuff that people see” when they interact with a web application, such as HTML-related screen widgets. Ideally, a JSP uses tags to interact with databases and encapsulate domain rules, and static or dynamically generated template text, such as XML or XHTML, to create the visual page for the user.

During the late 1990s, I was a freelance, backend web developer using a number of different languages. When server-side Java appeared on the scene, I greeted the news with as much relief as joy. Designed from the bottom up as object-oriented and modular, Java represented a reassuring alternative to the ad hoc, ill-designed, albeit well-intentioned masses of web-related code I would often encounter when an organization brought me into the midst of a project.

Not only can you easily create your own reusable components for, say, sending email simply by designing and uploading to your web application one or more Java classes,[2] but you have the entire Java API at your disposal for dealing with essential, low-level items such as String-handling, file I/O, and Math calculations. What a deal!

The other big benefit Java provides is its cross-platform nature. Web developers can design their web applications, neatly package them in a special JAR file for web components called a Web Application Archive file, then install the WARs on various servers hosted by different operating systems (OSes). Java web components are not bound to a single OS or to a particular vendor’s server software like other web-related software technologies.

Jump ahead to the present. By late 2003, Java has achieved status as the granddaddy of server-side development. Servlets and JSPs are included in the Java 2 Enterprise Edition (J2EE), a widely accepted enterprise technology for network-based and distributed computing. Hundreds of thousands of developers throughout the world work on the “web tier” of J2EE-based technologies, using servlets, JSPs, and sometimes special web frameworks such as Struts.

In fact, many web developers now spend a fair amount of time getting to know various " application servers”—like BEA WebLogic, JBoss, or IBM’s WebSphere—that pull together the web tier, business or domain objects (such as components that handle weather data or a customer’s financial accounts), and Enterprise Information Systems (EIS). These application servers represent the software host for servlets and JSPs. Many web developers, including myself, spend a lot of time working on web components that are hosted on Tomcat, a popular open source ( servlet engine and “reference implementation” for the new servlet and JSP APIs.[3]

The rapid maturation and well-established nature of Java has naturally led to a “cookbook” approach for our book. This cookbook focuses on how to initiate certain web-related tasks in Java, rather than tutoring the reader on how to use the Java language, or explaining the servlet and JSP APIs in finely grained detail. Countless tutorial-oriented Java books still exist, however, in new or reissued form, which attests to the popularity of Java as a web-development platform.

What’s in the Book

In creating the recipes for this book, I tried to cover as many common and advanced web developer tasks as I could practically fit into one book. This amounts to about 230 different recipes. Each recipe shows how to implement a particular task using servlets, JSPs, and, in many cases, one or more supporting Java classes.

The recipes show how to:

  • Authenticate web clients

  • Interact with databases

  • Send email

  • Handle submitted data from a web form

  • Read and set “cookies”

  • Upload files from the client

  • Integrate JavaScript with servlets and JSPs

  • Embed multimedia files like digital movies and music in JSPs and servlets

  • Handle web clients whose users speak different languages (internationalization)

  • Log messages from servlets and JSPs

  • Dynamically include chunks of content, as in traditional server-side include (SSI) code

  • Interact with Enterprise JavaBeans (EJBs) from a JSP and servlet

  • Use’s and’s Web Services APIs from a servlet or JSP

I have also included numerous technology-specific recipes, such as:

  • Using “sessions” in your Java web applications (a concept that represents the tracking of a user’s progress through a web site)

  • Working with “filters”

  • Using the open source ANT tool to build web applications

  • Binding Java objects to a session or web application so they can be used as information or data containers

  • Creating your own custom tags for JSPs

  • Using the JavaServer Pages Standard Tag Library (JSTL), which is a large set of prebuilt tags you can use in JSPs

In short, the book is designed to help guide Java web developers in their everyday tasks, and to provide quick solutions to typical web-related problems.

BEA WebLogic Recipes

Because Java web developers tend to work with both Tomcat and a proprietary application server, I’ve included a number of different recipes to show how to implement common tasks with BEA WebLogic. As a practical matter, I could not cover the several other application servers that are available, such as IBM’s WebSphere, JBoss, Jetty, Oracle 9i application server, or commercial servlet engines such as New Atlanta ServletExec and Caucho Resin. But I wanted to include recipes covering “how the other half lives” in terms of using various vendor tools for managing everyday web-application tasks. Solutions involving the deployment or revision of web components and deployment descriptors using visual interfaces such as WebLogic’s Administration Console or WebLogic Builder can be quite different from those used with Tomcat.

As a result, this book includes a collection of basic WebLogic-related recipes, such as deploying web applications on WebLogic, and using a servlet to access a WebLogic DataSource. Chapter 25 shows how a servlet can interact with an EJB installed on WebLogic.


The recipes are mainly designed for experienced developers who design, build, deploy, and revise Java-based web applications. This includes JSP, servlet, and JavaBean developers.

The book is also appropriate for experienced web developers who are just learning Java and migrating from another web programming platform, such as Active Server Pages, PHP, or Perl. These developers are usually knowledgable about the underlying mechanisms, such as sessions, cookies, file uploads, login authentication, and handling HTTP POST requests, but may not yet know how to implement these tasks in Java. The cookbook allows them to quickly look up a solution to a problem that they have probably already dealt with using another language.

Java developers who need to know how to implement new servlet API 2.4 and JSP 2.0 features (such as some of the new web.xml filter-mapping elements for request dispatchers and embedding the Expression Language [EL] in a JSP’s template text) will also find the cookbook handy.

What You Need to Know

Readers should know the basics of the Java language or be learning how to program with Java.

Chapter 1, includes brief introductions to servlets, JSPs, and deployment descriptors for readers who are not yet up to speed on these concepts. However, since the cookbook’s focus is on concise solutions to specific problems, it does not include long tutorials on the servlet and JSP APIs. Each recipe includes an introduction that provides enough information to get started with the various technologies and code samples. The recipes also include numerous references to online information resources, such as Javadoc pages and tutorials, for readers who need to explore a topic in greater depth.

Readers will benefit from having already been introduced to various J2EE subject areas such as Java Database Connectivity (JDBC), the Java Naming and Directory Interface (JNDI), and Enterprise JavaBeans (I have included one recipe that involves connecting a web component with EJBs using JNDI) .

Finally, a working knowledge of XML is also helpful, as Java web development involves XML-based deployment descriptors and configuration files.


The book begins with three chapters that cover the nuts and bolts of writing servlets and JSPs, deploying servlets and JSPs, naming or registering your servlets, and using the Ant tool.

I then explore several basic topics on web development, such as dynamically including content in web pages, uploading files, handling data that has been posted from an HTML form, reading and setting cookies, tracking sessions, and integrating JavaScript with JSPs and servlets.

Next, the book includes some more advanced recipes, such as logging messages, authenticating clients, binding attributes, working with the client request, and creating servlet filters. Chapter 20, and Chapter 21, cover two common and complex web-development tasks with 20 different recipes.

Chapter 22, and Chapter 23 describe custom tags and the JSTL. Chapter 24, discusses the crucial topic of internationalizing your web applications with servlets and JSPs.

For web developers whose web components must interact with EJBs using the Java JNDI, Chapter 25, shows how to configure JNDI in both Tomcat and WebLogic, as well as how to access JNDI objects using both servers.

The book concludes with two chapters that describe different strategies for extracting data from web sites using Java web components. Chapter 26, has recipes on harvesting or “scraping” data from web pages. Chapter 27, describes how to use Google’s and’s web services APIs.

Conventions Used in This Book

The following typographical conventions are used in this book:


Indicates new terms, example URLs, email addresses, filenames, file extensions, pathnames, directories, and Unix utilities.

Constant width

Indicates commands, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, XML tags, HTML tags, macros, the contents of files, or the output from commands.

Constant width bold

Shows commands or other text that should be typed literally by the user, and is used to emphasize code in examples.

Constant width italic

Shows text that should be replaced with user-supplied values. In some cases where text is already italicized, user-supplied values are shown in angled brackets (< >)


This icon signifies a tip, suggestion, or general note.


This icon indicates a warning or caution.

Using Code Examples

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does 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.

O’Reilly & Associates and the author both appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Java Servlet and JSP Cookbook, by Bruce Perry. Copyright 2004 O’Reilly & Associates, Inc., 0-596-00572-5.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

Comments and Questions

Please address comments and questions concerning this book to the publisher:

O’Reilly & Associates, 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)

O’Reilly has a web page for this book, where errata, examples, and any additional information is listed. You can access this page at:

To comment or ask technical questions about this book, send email to:

For more information about O’Reilly books, conferences, Resource Centers, and the O’Reilly Network, see our web site at:


One night, more than a year ago, I dispatched an email to O’Reilly with an idea for a book. At that time, the likelihood that this casual email would eventually give rise to a published book seemed very remote. After numerous emailed “back and forths” between me and a couple of O’Reilly Java editors, and then several months of gentle nudging, solid editing, occasional reconceptualizations, and (of course) writing, writing, and more writing, the seed of the book idea germinated and reached fruition. Voilá, a cookbook is born!

The shaping of a book is always a collaboration among several people. This book probably would not have left the launching pad without my editor Brett McLaughlin’s succinct and continuous reminders about what differentiates a cookbook from other book types. Brett is also a fine “word by word” copy editor, and having an editorial background myself, I appreciated his efforts from the writer’s side. Also, Brett’s knowledge of Java is deep, and his comments helped me avoid some awkward code design decisions.

I am very fortunate to have Jason Hunter and Sang Shin as technical editors. They are both well-known Java experts, and this is a much better book since they have read and commented on large chunks of it. Their review had a really short deadline, and this is a big book. I was amazed at the comprehensive coverage with such a short turnaround. As a technical writer, I am indebted to those who rescue me from embarrassing mistakes!

Some of us save our family members for last in acknowledging those who help us. Maybe that is because the last paragraph is the foundation on which the rest of the language sits, just as the family is every writer’s foundation, giving them support and shielding them from distractions as they immerse themselves in prose and technology. This book would not have been created without the help from my wife Stacy, daughter Rachel, and even Scott, who inspires me from the tender vantage point of being less than one year old. I’ll also repeat what I said in my AppleScript book; I thank my parents Robert and Anne Perry for installing in me a love of writing and books.

[1] See Sun Microsystems Java milestones and history at:

[2] For example, the installation of a binary Active Server Pages (ASP) component often required the scrutiny and permission of the hosting Internet Service Provider (ISP), because a badly written or malicious ASP component could wreak havoc on the server machine.

[3] A reference implementation is software that is based on a commonly agreed upon specification, and is freely available to software developers and others as a demonstration of how the specified software system is designed to function.

Get Java Servlet & JSP Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.