Servlets and Javaserver Pages The J2ee Technology Web Tier 1st Edition Jayson Falkner Instant Download
Servlets and Javaserver Pages The J2ee Technology Web Tier 1st Edition Jayson Falkner Instant Download
https://ebookbell.com/product/servlets-and-javaserver-pages-
the-j2ee-technology-web-tier-1st-edition-jayson-falkner-55582708
https://ebookbell.com/product/core-servlets-and-javaserver-pages-
volume-2-advanced-technologies-second-edition-2nd-edition-
brown-22023746
https://ebookbell.com/product/core-servlets-and-javaserver-pages-
vol-1-core-technologies-2-ed-nachdr-hall-22041744
https://ebookbell.com/product/more-servlets-and-javaserver-pages-1st-
hall-marty-5399044
https://ebookbell.com/product/j2ee-frontend-technologies-a-
programmers-guide-to-servlets-javaserver-pages-and-enterprise-
javabeans-1st-edition-lennart-jrelid-auth-4592418
Core Servlets And Java Server Pages Marty Hall
https://ebookbell.com/product/core-servlets-and-java-server-pages-
marty-hall-1348738
Murachs Java Servlets And Jsp 2nd Edition 2nd Andrea Steelman
https://ebookbell.com/product/murachs-java-servlets-and-jsp-2nd-
edition-2nd-andrea-steelman-2216188
Murachs Java Servlets And Jsp 3rd Edition Joel Murach Michael Urban
https://ebookbell.com/product/murachs-java-servlets-and-jsp-3rd-
edition-joel-murach-michael-urban-5324730
Head First Servlets And Jsp Passing The Sun Certified Web Component
Developer Exam Scwcd 1st Edition Bryan Basham
https://ebookbell.com/product/head-first-servlets-and-jsp-passing-the-
sun-certified-web-component-developer-exam-scwcd-1st-edition-bryan-
basham-55583566
Head First Servlets And Jsp Passing The Sun Certified Web Component
Developer Exam Second Edition Bryan Basham
https://ebookbell.com/product/head-first-servlets-and-jsp-passing-the-
sun-certified-web-component-developer-exam-second-edition-bryan-
basham-1021536
falkner.fm.qxd 8/21/03 5:16 PM Page i
DM series page 7x9.25.qxd 6/16/03 5:15 PM Page 1
• Teach from the bottom up. Before you can learn “how to” you must learn "how it works."
Understanding how and why a technology works the way it does builds the problem-solving skills
essential for developing great software.
• Back theory with code. Analogies and abstractions are great, but the real test is “does the code
work?” Sample code is provided to illustrate all the concepts covered.
• Tell the story. Software concepts do not exist in arid isolation. They weave a story, and the best stories
are created by a community of developers learning from their experiences and finding the best way to
share their knowledge with their colleagues. DevelopMentor’s technical team has developed its
knowledge on real-world development projects in order to bring you the stories you need to truly
understand software.
• Give concise, valuable information. The DevelopMentor Series writing style is geared toward serious
developers. The books are clear and concise, and make core concepts immediately accessible. At the
same time, the material is dense and rich with insight. A second reading is often a totally different—
and equally valuable—experience from the first reading.
Essential COM, Don Box, 0201634465 Component Development for the Java™ Platform,
Stuart Dabbs Halloway, 0201753065
Essential XML: Beyond Markup, Don Box, Aaron
Skonnard, and John Lam, 0201709147 Effective Visual Basic: How to Improve Your
VB/COM+ Applications, Joe Hummel, Ted Pattison,
Programming Windows Security, Keith Brown, Justin Gehtland, Doug Turnure, and Brian A.
0201604426 Randell, 0201704765
Java™ Rules, Douglas Dunn, 020170916 Debugging Windows Programs: Strategies, Tools,
and Techniques for Visual C++ Programmers,
Transactional COM+: Building Scalable Everett N. McKay and Mike Woodring,
Applications, Tim Ewald, 0201615940 020170238X
Servlets and JavaServer Pages™: The J2EE™ Real World XML Web Services: For VB and VB
Technology Web Tier, Jayson Falkner and Kevin .NET Developers, Yasser Shohoud, 0201774259
Jones, 0321136497
Essential XML Quick Reference: A Programmer's
ASP Internals, Jon Flanders, 0201616181 Reference to XML, XPath, XSLT, XML Schema,
SOAP, and More, Aaron Skonnard and Martin
Developing Applications with Visual Studio .NET, Gudgin, 0201740958
Richard Grimes, 0201708523
Watch for future titles in the DevelopMentor Series and the Microsoft .NET Development Series.
falkner.fm.qxd 8/21/03 5:16 PM Page iii
Jayson Falkner
Kevin Jones
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark
claim, the designations have been printed with initial capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no expressed or implied
warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for inci-
dental or consequential damages in connection with or arising out of the use of the information or programs
contained herein.
The publisher offers discounts on this book when ordered in quantity for bulk purchases and special sales.
For more information, please contact:
International Sales
(317) 581-3793
[email protected]
QA76.73.J3F355 2003
005.13'3—dc21 2003052156
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or trans-
mitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without
the prior consent of the publisher. Printed in the United States of America. Published simultaneously in
Canada.
For information on obtaining permission for use of material from this work, please submit a written request
to:
ISBN 0-321-13649-7
Text printed on recycled paper
1 2 3 4 5 6 7 8 9 10—CRS—0706050403
First printing, September 2003
falkner.fm.qxd 8/21/03 5:16 PM Page v
Contents
Preface xv
1 Setting Up a Servlet and JSP Environment 1
A Quick History of Web Development 1
CGI 2
Java Servlets 4
Containers 4
Getting Java Support 6
Downloading the Java 2 Standard Edition 1.4 6
Installing J2SE 1.4 on Microsoft Windows 7
Installing J2SE 1.4 on Linux Distributions 7
Tomcat 9
Configuring Tomcat 17
Web Applications 19
/WEB-INF and web.xml 22
Java Classes and Source Files 24
Java Archive (JAR) Files 25
Web Application Resource (WAR) Files 25
Ant 26
What Does Ant Do? 26
Installing Ant 27
Using Ant 27
Summary 29
2 Java Servlets 31
What Servlets Are and Why You Would Want to
Use Them 32
Web Applications 32
Servlets and HTTP Servlets 32
Filters 33
Security 33
Internationalization 33
Servlet Life Cycle 33
Servlets for the World Wide Web 35
Requests, Responses, and Headers 36
vii
falkner.fm.qxd 8/21/03 5:16 PM Page viii
viii CONTENTS
falkner.fm.qxd 8/21/03 5:16 PM Page ix
CONTENTS ix
falkner.fm.qxd 8/21/03 5:16 PM Page x
Iteration 243
Conditionals 247
URL Manipulation 250
I18N-Capable Text Formatting 255
XML Manipulation 255
SQL Tags 256
Justification for Skipping the SQL Tags 256
Summary 258
8 Filters 333
Introducing Filters 334
What Is a Filter? 334
The Filter Life Cycle 335
Coding a Simple Filter 336
Wrappers 352
Request Wrapping 353
Response Wrapping 357
x CONTENTS
falkner.fm.qxd 8/21/03 5:16 PM Page xi
10 Security 423
What Do We Mean by Security? 424
Declarative Security 425
Role-Based Security 426
Configuring Realms 430
The Big Picture 432
Configuring Basic or Digest Authentication 437
Custom Form-Based Authentication 438
Programmatic Security in a Servlet/JSP 440
Secure, Encrypted Communication 443
Specifying HTTPS 448
How Secure Is Security? 452
Encryption and Compression and Caching 453
Summary 455
CONTENTS xi
falkner.fm.qxd 8/21/03 5:16 PM Page xii
12 Internationalization 513
Content Encoding 514
ISO-8859-1 514
Unicode 517
Working with Non-ISO-8859-1 Encoding 518
i18n Implementation Techniques 523
Language Detection 524
Multiple Pages 527
Content Abstraction 531
Number and Date Formatting 539
i18n Numbers and Dates at Runtime 540
Using DateFormat, NumberFormat, and MessageFormat 543
JSTL Number and Date Formatting Tags 549
Summary 550
xii CONTENTS
falkner.fm.qxd 8/21/03 5:16 PM Page xiii
Index 735
CONTENTS xiii
falkner.fm.qxd 8/21/03 5:16 PM Page xiv
falkner.fm.qxd 8/21/03 5:16 PM Page xv
Preface
The goal of this preface is to briefly but accurately introduce this book and its
content. The preface is broken into four main parts: about the authors, an
overview of the book’s content, a list of the conventions used throughout the
book, and an explanation of the book’s cover. All parts are relevant to the book;
however, not all parts may be of personal interest to you. It is suggested at least
the first two sections be read because they explain who wrote this book and what
the book is about. The last two sections are not helpful unless you decide to read
any portion of the book.
Jayson Falkner
Jayson is a J2EE developer from the United States. He started developing with
J2EE just before JSP 1.1 and Servlets 2.2 were released and has been focusing on
the technologies since. Jayson is best known as the Webmaster of JSP Insider,
http://www.jspinsider.com, and for asking far too many questions in the
popular Servlet and JSP forums. Jayson has worked on numerous JSP titles and
is constantly present at the popular Java conferences. Jayson participated on the
JSR 152 expert group, JSP 2.0, and helped with the Tomcat 5 reference imple-
mentation.
Jayson prefers to think of himself as a tax-dodging student, who is currently
working on a Ph.D. in bioinformatics at the University of Michigan; however, he
also works professionally as a J2EE consult with Amberjack Software LLC. Open-
xv
falkner.fm.qxd 8/21/03 5:16 PM Page xvi
source software and free Java development are Jayson’s specialties. You can thank
(or complain) to Jayson for dictating the use of Mozilla and Tomcat with this
book.
You can get in touch with Jayson by sending an email to jayson@jspin-
sider.com.
Kevin Jones
Kevin is a longtime Java developer and educator, and has been involved in the
training industry for the last twelve years. For the last eight years Kevin has been
involved in writing and delivering Java training and consulting on various Java
projects, and for the last four years has concentrated on J2EE and specifically Web
technologies.
Kevin spoke at JavaOne in 2000 and was invited to become a member of JSR
53, the “Java Servlet 2.3 and JavaServer Pages 1.2 Specifications” and also JSR 52
“A Standard Tag Library for JavaServer Pages”. Since then Kevin has successfully
spoken at JavaOne in 2001 and 2002 as well as participating in JSR 154 (Servlets
2.4) and, like Jayson, in JSR 152.
Kevin is responsible for the Java curriculum at DevelopMentor, where he
teaches the Essential Java Web Development class that covers much of the
material in this book, as well as many other Java classes.
You can reach Kevin at [email protected] or through his Web site at
http://kevinj.develop.com
xvi PREFACE
falkner.fm.qxd 8/21/03 5:16 PM Page xvii
primary competitor of Servlets and JSP, Microsoft’s .NET and Microsoft’s ASP
.NET, you will have no software costs, no licensing costs, and the freedom to
choose any operating system that supports Java, such as Linux, Windows, OSX,
and Solaris. Compared to other open-source solutions, namely PHP or Perl, this
book offers a truly robust solution to developing Web applications. You will get
everything you need, including built-in security, portability, and a Web server. A
Servlet and JSP-based Web application does not need an additional Web server,
such as IIS or Apache, installed to serve up Web pages and provide encryption for
secure connections. Additionally, Servlet and JSP-based code, even code for mul-
tiple Web sites being run on the same server, can literally be packaged up into one
big file and moved between a development environment and a production envi-
ronment, even if the two places are using different operating systems—you can
not do this with technologies such as PHP or Perl. Additionally, Servlets and JSP
are an official part of J2EE, Java’s solution to the hardest problems of application
programming. If you plan on programming the largest and most complex of Web
applications (including multi-server projects), this book still provides relevant
code—surely a bonus compared to other popular, open-source technologies that
are not meant for large Web applications.
The table of contents provides a complete list of the book’s contents, but the
titles of most chapters are meaningless to a new user of Servlets and JavaServer
Pages. Here is a complete description of the book’s content, divided by chapters,
explaining why the chapter is in this book:
• Setting Up a Servlet and JSP Environment (Chapter 1): Before
jumping straight to the technologies, you need to have two things:
knowledge of why Servlets and JSP are important and a devel-
opment environment (for Windows, Linux or OS X) for using
Servlets and JSP. These two topics are covered completely in
Chapter 1. While the content may not be something you will ever
reference again in the future, it is a required introduction for new
Servlet and JSP users.
• Java Servlets (Chapters 2) and JavaServer Pages (Chapter 3):
Chapters 2 and 3 provide detailed coverage of Servlets and
JavaServer Pages. The chapters are not the most exciting of the
book, but the material is needed as groundwork for the later
chapters.
• Exception Handling (Chapter 4): Web sites built using Servlets and
JavaServer Pages provide specialized methods of handling excep-
tions. The mechanism is required in order to appropriately show a
PREFACE xvii
falkner.fm.qxd 8/21/03 5:16 PM Page xviii
xviii PREFACE
falkner.fm.qxd 8/21/03 5:16 PM Page xix
PREFACE xix
falkner.fm.qxd 8/21/03 5:16 PM Page xx
InTextCode Style
When dealing with technical information there are times when terms are
ambiguous. One word in English might be spelled and pronounced exactly the
xx PREFACE
falkner.fm.qxd 8/21/03 5:16 PM Page xxi
same in code but refer to a completely different meaning. In cases where a literal
name or value of a technical term is used, it will always appear in the InTextCode
style. This style signifies that the word is a direct reference to a file, variable
name, Object type, or any other specific code reference.
Foo
Throughout the book there are many examples of code. These examples are all
thoroughly tested and are functional illustrations of a point at hand. For the most
part code is always intended to be helpful. However, sometimes an example relies
on having a particular situation or circumstance occur to be meaningful. In these
cases a slightly contrived bit of code might be required to illustrate what the
important example is doing. In these cases the contrived code is not meant to be
helpful beyond educational purposes. In order to distinguish clearly between
what code is slightly contrived and what code is actually helpful a convention is
used to flag purely educational code. Whenever the foo keyword appears in code,
you should be suspect of its practical use. Some examples of places where foo
appears include com.jspbook.foo package and code that is named with foo
appearing in the title. In the case of the com.jspbook.foo package the foo
keyword means code in this package is not too helpful on its own. Instead,
com.jspbook.foo classes are usually built to directly complement a helpful class
appearing in the com.jspbook package. When the foo keyword appears in the
title of code, perhaps a JSP named Foo.jsp, it signals the whole page is slightly
contrived. Be conscious of occurrences of the foo keyword and do not focus on
them but rather the point they illustrate.
PREFACE xxi
falkner.fm.qxd 8/21/03 5:16 PM Page xxii
Mozilla is the very popular open-source Web browser that is built with an
emphasis on compliance to Internet standards. The results of a JSP or Servlet are
almost always intended for rendering by a Web browser. In almost every
screenshot the Web browser is visible. This browser is Mozilla, http://www.
mozilla.org, unless specifically mentioned otherwise. Mozilla was chosen
because it is both a truly superb piece of software and because it behaves in a way
that is to be expected by other Web browsers.
Special Thanks
There are a few people who helped directly with this book, and there are
countless people who helped indirectly. To everyone who helped with this book:
thanks!
xxii PREFACE
falkner.fm.qxd 8/21/03 5:16 PM Page xxiii
Special thanks to Ann Sellers and Shelley Kronzek, our editors at Addison-
Wesley. You are both fantastic editors, and without you this book would never
have been published. It was a pleasure working with you.
Also special thanks to Kenyon Brown, Patrick Cash-Peterson, and Tyrrell
Albaugh, our production team at Addison-Wesley. Production sometimes seems
to take forever; thanks to them, it didn’t.
Special thanks to Eduardo Pelegri-Llopart and Mark Roth for leading the JSP
2.0 specification and for formalizing the ideas of the expert group and JSP com-
munity.
Special thanks to all of the members of the JSP and Servlet expert groups for
all the hard work involved with Servlets 2.4 and JavaServer Pages 2.0.
Special thanks to all the Servlet and JSP developers who have helped the tech-
nologies grow and thrive. You are the inspiration for this book.
Special thanks to Casey Kochmer. Casey is a longtime friend of Jayson’s, co-
founder of JSP Insider, and one of the inspirations for this book. Without you,
Casey, this book would never have been published.
Special thanks to the countless reviewers of this manuscript. We always had
plenty of good advice from the reviewers. Thanks for helping make this a better
book.
Special thanks to the instructors at DevelopMentor. This group of people
constantly challenge the way I think about software and software development.
Without them I would not be the person I am. In particular, thanks to Simon
Horrell for constantly playing “devil’s advocate” and forcing me to question all
my assumptions.
PREFACE xxiii
falkner.fm.qxd 8/21/03 5:16 PM Page xxiv
falkner.ch1.qxd 8/21/03 4:42 PM Page 1
Chapter 1
B efore you start developing with Servlets and JavaServer Pages, you need to
understand two very important things: Why is using the technology desirable,
and what is needed in order to use the technology? This chapter answers these
two questions, and in the process provides an introduction to the entire book. We
start with an introduction to traditional Web development. The discussion
describes why Servlets and JSP were initially created and why the technologies are
currently popular. The end of the discussion segues to the software needed in
order to run the book’s examples.
It is preferred that you follow the instructions in this chapter to ensure your
coding environment most closely matches the one all of the code examples of this
book have been tested against. If you are using an already established Servlet/JSP
environment, make sure it has support for JavaServer Pages 2.0, Servlets 2.4, and
the Java 2 Standard Edition 1.4. Examples in this book require these technologies
and some features covered are not backwards-compatible.
1
falkner.ch1.qxd 8/21/03 4:42 PM Page 2
CGI
The Common Gateway Interface, or CGI, is commonly referred to as one of the
first practical technologies for creating dynamic server-side content. With CGI a
server passes a client’s request to an external program. This program executes,
creates some content, and sends a response to the client. When first developed,
this functionality was a vast improvement over static content and greatly
expanded the functionality available to a Web developer. Needless to say CGI
quickly grew in popularity and became a standard method for creating dynamic
Web pages. However, CGI is not perfect.
CGI was originally designed to be a standard method for a Web server to
communicate with external applications. An interesting point to note is that the
functionality available for generating dynamic Web pages was really a side effect
of this design goal. This largely explains why CGI has maybe the worst life cycle
possible. As designed, each request to a CGI resource creates a new process on the
server and passes information to the process via standard input and environment
variables. Figure 1-1 provides a diagram of this single-phase CGI life cycle.
While it does work, the CGI life cycle is very taxing on server resources and
greatly limits the number of concurrent CGI users a server can support. In case
you are unfamiliar with operating systems and processes, a good analogy to use
would be starting up and shutting down a Web server each time a user makes a
request. As you probably know, this is almost never the case for a real Web
server. It takes a noticeable amount of time to start and stop the entire process.
A better solution is to start the server process once, handle all requests, and then
shut it down when there is no longer a need for a Web server. Starting and
stopping a Web server is like the single-phase life cycle of CGI, and it was a very
noticeable problem. CGI did not scale well and would often bring a Web server
to a halt.
Even with poor performance by today’s standards, CGI was a revolu-
tionary step in the evolution of server-side programming. Developers had a
cross platform method of creating dynamic content using most any of their
favorite scripting and programming languages. This popularity sparked
second-generation CGI implementations that attempted to counter the per-
formance problems of original CGI, namely FastCGI. While the single phase
life cycle still existed, CGI implementations improved efficiency by pooling
resources for requests. This eliminated the need to create and destroy
processes for every request and made CGI a much more practical solution.
Figure 1-2 shows the improved implementation of CGI. Instead of one request
per a process, a pool of processes is kept that continuously handle requests. If
one process finishes handling a request, it is kept and used to manage the next
incoming request rather than start a new process for each request.
This same pooling design can still be found in many of today’s CGI imple-
mentations. Using pooling techniques, CGI is a viable solution for creating
dynamic content with a Web server, but it is still not without problems. Most
notable is the difficulty in sharing resources such as a common logging utility or
server-side object between different requests. Solving these problems involves
using creative fixes that work with the specific CGI and are custom-made for
individual projects. For serious Web applications, a better solution, preferably
one that addresses the problems of CGI, was required.
Java Servlets
In the Java world, Servlets were designed to solve the problems of CGI and create
robust server-side environments for Web developers. Similar to CGI, Servlets
allow a request to be processed by a program and let the same program produce
a dynamic response. Servlets additionally defined an efficient life cycle that
included the possibility of using a single process for managing all requests. This
eliminated the multi-process overhead of CGI and allowed for the main process
to share resources between multiple Servlets and multiple requests. Figure 1-3
gives a diagram of a Web server with Servlet support.
The Servlet diagram is similar to that of second-generation CGI, but notice all
the Servlets run from one main process, or a parent program. This is one of the
keys to Servlet efficiency, and, as we will see later, the same efficiency is found with
JSP. With an efficient design and Java’s cross-platform support, Servlets solved the
common complaints of CGI and quickly became a popular solution to dynamic
server-side functionality. Servlets are still popular and are now also used as the
foundation for other technologies such as JSP. Currently, Servlets and JSP com-
bined make up the official “Web Tier” for the Java 2 Enterprise Edition, J2EE1.
Containers
Servlet performance can be attributed directly to a Servlet container. A Servlet
container, also called “container” or “JSP container”, is the piece of software
Web Server
Process
Request Servlet
Request Servlet
Request Servlet
1. This book’s title, The J2EE Technology Web Tier, comes directly from the marketing jargon Sun
uses. Logically, Web Tier means the code that interacts with the World Wide Web.
that manages the Servlet life cycle. Container software is responsible for inter-
acting with a Web server to process a request and passing it to a Servlet for a
response. The official definition of a container is described fully by both the
JSP and Servlet specifications. Unlike most proprietary technologies, the JSP
and Servlet specifications only define a standard for the functionality a con-
tainer must implement. There is not one but many different implementations
of Servlet and JSP containers from different vendors with different prices, per-
formance, and features. This leaves a Servlet and JSP developer with many
options for development software.
With containers in mind, the previous diagram of Servlets is better drawn
using a container to represent the single process that creates, manages, and
destroys threads running Servlets on a Web server. Note that this may or may not
be a separate physical process. Figure 1-4 shows a Web server using a Servlet con-
tainer.
Only Servlets are depicted in Figure 1-3, but in the next two chapters the
Servlet and JSP life cycles are covered in detail, and it will be clear that a con-
tainer manages JSP in exactly the same way as Servlets. For now it is safe to
assume that Servlets and JSP are the same technology. What Figure 1-4 does not
show is that in some cases a container also acts as the Web server rather than a
module to an existing server. In these cases the Web server and container in
Figure 1-3 are essentially the same thing.
Given you now know a little more about containers, it should be clear that a
container must be installed to run Servlets and JSP. Examples in this book require
a Servlet 2.4 and JSP 2.0-compatible container. If you do not have one, do not
worry. A walk-through is provided later in this chapter, explaining how to obtain
Web Server
Container
CONTAINERS 5
falkner.ch1.qxd 8/21/03 4:42 PM Page 6
the reference implementation JSP 2.0 and Servlet 2.4 container. If you have a pre-
viously installed container, make sure it supports the correct version of Servlets
and JSP; older containers do not support some of the features of JSP 2.0 and
Servlet 2.4 specifications. In this book specifically, all examples were created and
tested using the reference implementation container, Tomcat. Version 5 of
Tomcat is the reference implementation for both Servlets 2.4 and JSP 2.0. If you
need to install a compatible container, take the time to now download and install
Tomcat 5.
Java only needs to be installed once on your computer and only for the spe-
cific operating system you are using. It is not required that you read all of the
sections covering installation on all of the featured platforms. They exist only to
give readers a guide to their specific operating system. Complete coverage of the
Java 2 Standard Edition 1.4 is outside the scope of this book; however, later use
of the J2SDK by this book will not require comprehensive knowledge of the
tools provided by Sun. If you are looking for a detailed guide for this infor-
mation, refer to Thinking In Java, 3rd Edition2, by Bruce Eckel.
equivalent for your distribution, feel free to install it, make note of the instal-
lation directory, and skip to the next section of this chapter.
At the introduction to this section, you should have downloaded the J2SE 1.4
Linux binary installation file. The file should be named something similar to
j2sdk-1_4_0_01-linux-i586.bin with appropriate version numbers for the
latest release. Any post-1.4 release should be adequate; this guide uses version
1.4.0_01. From the command prompt make sure the file has executable permis-
sions and execute the program. These are what the commands would be to make
the file executable and then execute it; assume the download is in the
/root/download directory and you have proper permissions.
chmod +x /root/download/j2sdk-1_4_0_01-linux-i586.bin
/root/download/j2sdk-1_4_0_01-linux-i586.bin
When the file executes, Sun’s licensing terms are displayed and you have the
option of agreeing to continue the installation. Figure 1-5 shows an example
display of the licensing terms.
If you agree to the terms, files will automatically be unpacked to a
j2sdk1.4.0 directory created by the installation program. You can move this
directory to any location you prefer, but remember the location where the J2SDK
1.4 is because it will be needed later when the environment variables are set.
Installation of the standard Java development kit is now complete.
Tomcat
Tomcat, the reference implementation of Servlets and JSP, is part of the open
source Apache Jakarta project and is freely available for download from
http://jakarta.apache.org/tomcat3. Tomcat can be run on Windows, Linux,
Macintosh, Solaris, and most any of the other Unix distributions. You can use
Tomcat both commercially and non-commercially as specified by the Apache
Software Foundation License.
The next few sections provide a walk-through for installing Tomcat on
Windows, Linux distributions, and Macintosh OS X. If needed, follow the appro-
priate section to get Tomcat correctly set up for later examples.
3. This part of the book is perhaps the most important. If for any reason you are having trouble
installing Tomcat, please consult the book support site, http://www.jspbook.com, for a complete, up-
to-date Tomcat 5 installation guide.
Figure 1-6 should appear notifying you that the Tomcat Installer located a J2SDK
installation.
Click OK and continue on to the screen displaying the Apache Software
Foundation license. Read through the terms and make sure you agree with
Tomcat’s licensing. If you accept the terms, the installation continues and you can
choose what components you wish to install. The default ones should be fine, as
shown in Figure 1-7.
Proceed with the installation wizard to the next screen, and you can choose a
directory to install Tomcat. Figure 1-8 shows the corresponding installation
wizard screen. Choose any directory you prefer.
After choosing an installation directory, the wizard will ask for some initial
Tomcat configuration information, including a port number and administrative
access information. The default options are fine, but later on in the chapter we
will be changing the port Tomcat uses to be port 80 instead of 8080. You may
change the port to 80 via the installation wizard now or later on in the chapter.
Figure 1-9 displays the corresponding installation wizard screen.
The final piece of configuration information Tomcat requires is the location
of your Java Virtual Machine, which should be wherever you installed it earlier in
the chapter. By default Tomcat attempts to locate the most recent JVM for you,
as shown in Figure 1-10.
Figure 1-10 Installation Wizard Showing the Location of the Current JVM
The default JVM found by the installation wizard should be fine, but you can
change the location to be any JVM you desire (note a Java 1.4-compatible JVM is
required to execute this book’s examples). Finally, the installation wizard will
automatically install all the Tomcat files. Figure 1-11 shows the corresponding
installation wizard screen.
To complete the installation and run Tomcat, start the server by double-
clicking on the Tomcat icon or by executing the startup script startup.bat
found in the TOMCAT_HOME/bin directory. Check the service is running by
browsing to your local computer on port 8080 (or 80 if you changed Tomcat’s
port via the installation wizard), http://127.0.0.1:8080. A Tomcat welcome
page should be displayed4 as shown in Figure 1-12.
Installation of Tomcat is complete, and you are now ready to run book
examples. Tomcat comes bundled with documentation and examples of both
Servlets and JSP. Feel free to examine the bundled examples, but this book will
not cover them further. Before continuing, there are two important scripts to be
aware of.
4. Port 8080 should not be previously in use, but if it is, you will not be able to see the Tomcat
welcome page. If you are sure you have correctly installed Tomcat and think a port bind is causing
problems, consult the later section in this chapter which deals with changing the port Tomcat runs on.
5. A tarball is a commonly used Unix term for a file compressed using gzip and tar compression. The
de facto standard for distributing Unix and Linux programs is by means of a tarball because the com-
pression is often significantly better than only ZIP.
Tomcat is now ready to run. Start the server by executing the startup script
startup.sh found in the /usr/jakarta-tomcat-5.0/bin directory. Check the
service is running by browsing to your local computer on port 8080,
http://127.0.0.1:8080. A Tomcat welcome page should be displayed6 as shown
in Figure 1-13.
Installation of Tomcat is complete, and you are now ready to run book
examples. Tomcat comes bundled with documentation and examples of both
Servlets and JSP. Feel free to examine the bundled examples, but this book will
6. Port 8080 should not be previously in use, but if it is, you will not be able to see the Tomcat
welcome page. If you are sure you have correctly installed Tomcat and think a port bind is causing
problems, consult the later section in this chapter, which deals with changing the port Tomcat runs
on.
not cover them further. Before continuing on, there are two important scripts to
be aware of.
• startup.sh: The startup.sh script in the TOMCAT_HOME/bin
directory is used to start the Tomcat container and Web server.
Servlet and JSP code examples rely on Tomcat, and you must have
Tomcat turned on before testing them.
• shutdown.sh: The shutdown.sh script in the TOMCAT_HOME/bin
directory is used to terminate the Tomcat container and Web server.
It is important to be aware of these two scripts because from time to time
an example will require that Tomcat be restarted. When this is asked, it is
assumed Tomcat is currently running and implies that the shutdown.sh script
and then startup.sh be executed to reload the server. Also be aware that the
environment variables previously set will not persist between different ter-
minal sessions and need to either be included in a startup script or set for each
session.
Alternatively, you can also automate the redundant process of compiling
book examples and reloading Tomcat by using a build utility. Use of the Jakarta
Ant build utility is strongly encouraged with this book and is covered later in this
chapter.
Configuring Tomcat
Tomcat is a robust JSP and Servlet container. It not only provides complete
support for the JSP and Servlet specifications, but it can also act as a standalone
Web server. By default, this is exactly what Tomcat does, and the default configu-
ration is all we need for this book’s examples. Full instructions on configuring
Tomcat are outside the scope of this book. There are many different Servlet and
JSP containers available, and it is not very practical to devote a large part of this
book to Tomcat-specific information. There is only one important aspect of con-
figuring Tomcat that needs to be discussed. If you would like to learn more about
using Tomcat to its full potential, some good resources are listed at the end of this
section.
The entry is responsible for configuring Tomcat’s HTTP connector and the
port it listens on. Change the entry to use port 80 by replacing 8080 with 80:
<!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 -->
<Connector className="org.apache.coyote.tomcat5.CoyoteConnector"
port="80" minProcessors="5" maxProcessors="75"
enableLookups="true" redirectPort="8443"
acceptCount="10" debug="0"
connectionTimeout="20000"
useURIValidationHack="false" />
Tomcat will then listen for HTTP requests on port 80, which is assumed
when no port is specified. Shut down and restart Tomcat so that it uses the new
port. Both http://127.0.0.1 and http://127.0.01:80 will now display the
Tomcat welcome page. Likewise, all subsequent requests, which do not specify a
port, will be directed to Tomcat. Make sure to restart Tomcat before testing out
the changes7.
7. If another service, such as Apache or IIS, is running on port 80, Tomcat will not be able to use the
port. Either choose a different port, configure Tomcat to work with the service, terminate the con-
flicting service, or change the services default port. Additional help with configuring Tomcat to use
an existing Web server is outside the scope of this book.
Web Applications
A “Web Application”, not the commonly used “Web application” meaning any
Web-savvy program, is the proper term for a complete Servlet and/or JSP project.
Anytime you develop a JSP or Servlet, it is part of a larger Web Application. Each
Web Application has its own unique configuration files and resources for use.
WEB APPLICATIONS 19
falkner.ch1.qxd 8/21/03 4:42 PM Page 20
These files and resources are defined by the JSP specification and Servlet specifi-
cation and managed by your container. In summary they consist of:
• Configuration: Each Web Application includes a configuration file,
web.xml. This configuration file customizes the resources of a Web
Application in an efficient and structured fashion. Web Applications
keep web.xml private from outside visitors and also provide a place
for privately storing other custom configuration information.
• Static Files and JSP: A Web Application’s primary purpose is to
serve content on the World Wide Web. This content includes
dynamic resources such as Servlets and JSP, but it also includes
static resources such as HTML pages. A Web Application automati-
cally manages JSP and static resources deployed in it.
• Class Files and Packages: A Web Application also loads and
manages custom Java code. For application-specific class files such
as Servlets, a special location is designated from which a container
can load and manage compiled code. Web Applications define a
similar location for including Java Archive, JAR, files that contain
packaged resources.
By the end of the chapter, most of these configuration files and resources will
have been introduced and discussed, but an in-depth analysis of them cannot be
attempted without understanding more about JSP and Servlets. As the book pro-
gresses, all of the preceding will be fully defined and explored. But before dis-
cussing any part of a Web Application, one must be created.
Making a Web Application from scratch requires two things. First, a directory
to hold all of the files for the Web Application is needed. The directory can be
located anywhere on your local computer. For simplicity, create a directory
named jspbook under the /webapps directory of your Tomcat installation. The
webapps folder is Tomcat’s default location for storing Web Applications. To
make this a Web Application, you also need to add a web.xml configuration file.
To do this, go to the jspbook directory and create a subdirectory called WEB-INF.
Inside the /WEB-INF directory create a file called web.xml. Save Listing 1-1 as the
contents of web.xml.
Listing 1-1 web.xml Skeleton File
Do not worry about the details of this for now; this will all be explained later.
Next, the container needs to be informed that a new Web Application exists8.
With Tomcat this can be done in one of two ways: by adding an entry in the
server.xml file located in the /conf directory of a Tomcat installation, or by
placing an XML file containing the configuration into Tomcat’s /webapps
directory. Placing the file in the /webapps directory is the preferred option; it
makes upgrading Tomcat versions easier as changes to server.xml do not need
to be transferred. To configure a Web application, Tomcat requires a Context tag.
Create a file called jspbook.xml in TOMCAT_HOME/webapps directory with Listing
1-2 as its content.
Listing 1-2 Simple Web Application Deployment File for Tomcat
<html>
<head>
<title>Welcome!</title>
</head>
<body>
Welcome to the example Web Application for
<i>Servlets and JSP, the J2EE Web Tier</i>.
</body>
</html>
8. The following step is not strictly necessary as Tomcat automatically treats directories within its
/webapps directory as a webapp. This support does not include subdirectories of webapp.
WEB APPLICATIONS 21
falkner.ch1.qxd 8/21/03 4:42 PM Page 22
Refresh the Web browser you used to previously view the empty Web
Application directory. It now displays a little welcome message, as shown in
Figure 1-15, instead of the empty directory listing, as shown in Figure 1-14.
Any static content placed in the Web Application will be made available for
users to see. The index.html page happens to be the default page Tomcat displays
for a Web Application, and that is why it appeared by default when the empty
directory was refreshed. Notice that the URL automatically changed to http://
127.0.0.1/jspbook/index.html9. This behavior is not standard among all JSP
containers, but the behavior can always be configured on a per Web Application
basis. Web Application configuration involves using the Web Application
Deployment Descriptor file web.xml.
9. Microsoft’s Internet Explorer is notorious for improperly handling this. If the URL does not
change, do not worry. As long as the correct page is shown, everything is fine.
security restrictions to place on files. The Servlet specification also defines that
the entire /WEB-INF directory of any Web Application must be kept hidden from
users of the application. In other words, a user cannot browse to http://
127.0.0.1/jspbook/WEB-INF. Try it—any configuration information for your
Web Application is unattainable by a client unless you specifically create some-
thing to expose it.
You already have the skeleton of a Web Application configuration file.
Further configuration information can be placed in between the starting and
ending web-app tags. Try it out by adding Listing 1-4 to define the default page
that your Web Application displays.
Listing 1-4 web.xml welcome File Configuration
Save the changes and restart your container so the Web Application reflects
them. Use a Web browser to visit http://127.0.0.1/jspbook again. This time
the index.html page is not shown by default; a directory listing is shown instead
(see Figure 1-16), which includes index.html.
WEB APPLICATIONS 23
falkner.ch1.qxd 8/21/03 4:42 PM Page 24
The preceding outcome is the result of the new elements added to web.xml.
The welcome-file-list element defines a list of welcome files in descending
preference. The name of each welcome file is defined as the body of the welcome-
file element. In the meta-data just added, one specific file was listed as default
page: welcome.html. If file exists, the container would show it instead of the empty
directory. If you would like to experiment, try changing the name of index.html
to weclome.html and it will appear as the default page for the Web Application.
The rest of web.xml configuration is left for discussion in later sections of the
book. Both JSP and Servlets have many configuration elements that can be added
to web.xml. This book covers most all of them in examples, but a complete ref-
erence can always be found in the Servlet 2.4 schema.
will ignore the code when it is loading the Web Application. The second issue is
more problematic because the Web Application’s Servlets and JSP will not be able
to import and use the custom code.
The correct place to put custom code is in the /WEB-INF/classes directory
of a Web Application. Code that is placed in this directory is loaded by the con-
tainer when needed and can be imported for use by Servlets and JSP in the same
Web Application. Should the code be part of a package, create a directory
structure that matches the package names. An example of this would be if a class
were created for the com.foo.example package. The appropriate place to put the
compiled Java class is the /WEB-INF/classes/com/foo/example directory of a
Web Application. For now, create the /WEB-INF/classes directory so that it is
ready for later code examples.
WEB APPLICATIONS 25
falkner.ch1.qxd 8/21/03 4:42 PM Page 26
be appearing often in later chapters. WAR files are mentioned here for reasons of
completeness and because the online book support site packages all of this book’s
examples into a WAR. If you would like to skip retyping code examples from the
book, feel free to download the example WAR at http://www.jspbook.com/
jspbook.war.
If you would ever like to make a WAR file, simply ZIP compress an entire
working Web Application. For example, at any time you can create a WAR of your
progress through this book by ZIP-compressing all of the contents in the jspbook
directory. Using the ZIP utility on Linux, the following commands would be used:
zip -r jspbook.war jspbook
The zip utility would then compress the entire application into one file
named jspbook.war. In order to deploy this file with Tomcat, simply place
jspbook.war in the /webapps directory and restart Tomcat.
Note that WAR files are only as portable as you make them. Several times in
upcoming chapters notes will be made about this point. For example, if you
access a file using the file’s absolute path name, there is no guarantee a similar file
will be found on all servers with containers using your WAR. However, if a
custom file is packaged in a WAR, the file can always be accessed using the Servlet
API.
Ant
The Jakarta Ant project is popular with Java developers and for good reason. Ant is
a cross-platform build utility that is easy to use and configure. Ant uses an XML
configuration file typically called build.xml. If you are unfamiliar with build util-
ities, do not worry. This book does not rely on such knowledge. Ant is treated
purely as a complimentary tool. If you have used Ant before, you should appreciate
this, or if you have not used Ant, hopefully you will be glad we introduced the tool
to you. At any time you can opt to completely ignore Ant and simply compile .java
files by hand and reload Tomcat using the appropriate scripts. At no point will this
book tell you to use Ant to do this. Instead, an example will dictate that Tomcat, the
Web Application, or both need to be reloaded, or that code needs to be compiled.
In these cases it is implied you can use Ant if you so desire.
ebookbell.com