100% found this document useful (1 vote)
43 views77 pages

Servlets and Javaserver Pages The J2ee Technology Web Tier 1st Edition Jayson Falkner Instant Download

The document is an overview of the book 'Servlets and JavaServer Pages: The J2EE Technology Web Tier' by Jayson Falkner and Kevin Jones, which covers the fundamentals of Java servlets and JSP technology. It includes links to various related ebooks and resources, as well as a detailed table of contents outlining the book's structure and topics. The book aims to provide essential knowledge for developers working with Java web applications.

Uploaded by

sadetarawase
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
43 views77 pages

Servlets and Javaserver Pages The J2ee Technology Web Tier 1st Edition Jayson Falkner Instant Download

The document is an overview of the book 'Servlets and JavaServer Pages: The J2EE Technology Web Tier' by Jayson Falkner and Kevin Jones, which covers the fundamentals of Java servlets and JSP technology. It includes links to various related ebooks and resources, as well as a detailed table of contents outlining the book's structure and topics. The book aims to provide essential knowledge for developers working with Java web applications.

Uploaded by

sadetarawase
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Servlets And Javaserver Pages The J2ee

Technology Web Tier 1st Edition Jayson Falkner


download

https://ebookbell.com/product/servlets-and-javaserver-pages-
the-j2ee-technology-web-tier-1st-edition-jayson-falkner-55582708

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Core Servlets And Javaserver Pages Volume 2 Advanced Technologies


Second Edition 2nd Edition Brown

https://ebookbell.com/product/core-servlets-and-javaserver-pages-
volume-2-advanced-technologies-second-edition-2nd-edition-
brown-22023746

Core Servlets And Javaserver Pages Vol 1 Core Technologies 2 Ed Nachdr


Hall

https://ebookbell.com/product/core-servlets-and-javaserver-pages-
vol-1-core-technologies-2-ed-nachdr-hall-22041744

More Servlets And Javaserver Pages 1st Hall Marty

https://ebookbell.com/product/more-servlets-and-javaserver-pages-1st-
hall-marty-5399044

J2ee Frontend Technologies A Programmers Guide To Servlets Javaserver


Pages And Enterprise Javabeans 1st Edition Lennart Jrelid Auth

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

The DevelopMentor Series—Essential Reading for the Serious Developer


Books in the DevelopMentor Series:

• 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.

Titles in the Series:


Essential ADO.NET, Bob Beauchemin, Essential IDL: Interface Design for COM, Martin
0201758660 Gudgin, 0201615959

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

Advanced Visual Basic 6: Hardcore Programming C# Primer: A Practical Approach, Stanley B.


Techniques, Matthew Curland, 0201707128 Lippman, 0201729555

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

Servlets and JavaServer Pages TM

The J2EETM Technology Web Tier

Jayson Falkner
Kevin Jones

Boston • San Francisco • New York • Toronto • Montreal


London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City
falkner.fm.qxd 8/21/03 5:16 PM Page iv

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:

U.S. Corporate and Government Sales


(800) 382-3419
[email protected]

For sales outside of the U.S., please contact:

International Sales
(317) 581-3793
[email protected]

Visit Addison-Wesley on the Web: www.awprofessional.com

Library of Congress Cataloging-in-Publication Data


Falkner, Jayson.
JAVA Servlets and JavaServer pages: the J2EE technology Web tier/Jason Falkner,
Kevin James
p. cm.
ISBN 0-321-13649-7 (alk. paper)
1. Java (Computer program language) 2. Servlets. 3. JavaServer pages. I. Jones, Kevin.
II. Title.

QA76.73.J3F355 2003
005.13'3—dc21 2003052156

Copyright © 2004 by Pearson Education, Inc.

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:

Pearson Education, Inc.


Rights and Contracts Department
75 Arlington Street, Suite 300
Boston, MA 02116
Fax: (617) 848-7047

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

Thanks to Teresa, Harry, Sam, and Alex. Without you


I couldn’t do what I do.
—Kevin Jones

To James and Joleen Falkner. Your support has produced yet


another sizable piece of gibberish. Words fail to express
how thankful I am for your love.
—Jayson Falkner
falkner.fm.qxd 8/21/03 5:16 PM Page vi
falkner.fm.qxd 8/21/03 5:16 PM Page vii

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

GET and POST 39


HTTP Response Codes 40
Coding a HttpServlet 41
Deploying a Servlet 43
Web Application Deployment Descriptor Structure 46
Servlet Configuration 47
Limitations of Configuration: web.xml Additions 50
Client/Server Servlet Programming 51
HttpServletRequest and HttpServletResponse 51
HttpServletResponse 52
HttpServletRequest 64
ServletContext 92
Initial Web Application Parameters 92
Servlet Event Listeners 102
Summary 106

3 JavaServer Pages 109


JSP 2.0 Specification 110
JSP 110
JavaBeans 110
Custom Tags and JSP Fragments 110
Expression Language 110
JSP Life Cycle 111
The Difference Between Servlets and JSP 112
JSP Syntax and Semantics 116
Elements and Template Data 116
Two Types of Syntax 116
Scripting Elements 117
Directives 126
JSP Configuration 133
Standard JSP Actions 136
White Space Preservation 145
Attributes 147
Comments 147
Quoting and Escape Characters 149
Implicit Objects 150
pageContext 153
out 154
config 157
page 159
JSP in XML Syntax 159
XML Rules 162
JSP Documents 162
Summary 165

viii CONTENTS
falkner.fm.qxd 8/21/03 5:16 PM Page ix

4 Exception Handling 167


Errors and Exceptions 168
Throwing Exceptions 169
Try, Catch, Finally 172
JSP and Servlet Exceptions 174
Web Application Exception Handling 176
Micro-Managing Exceptions 176
Macro-Managing Exceptions 181
Web Application Error Pages 182
Logging 191
The Problem with System.out.println() 192
JDK 1.4 Logging Versus Log4j 193
Using the java.util.logging Package 193
Handlers 196
Loggers 199
Logging and Performance 208
A General Philosophy for Exception Handling and Logging 208
Summary 210

5 JavaBeans and the JSP Expression Language 213


JavaBeans 214
Get and Set Methods 214
Why Get and Set Methods? 215
Servlets, JSP, and JavaBeans 217
<jsp:useBean/> 217
<jsp:getProperty/> and <jsp:setProperty/> 221
Good Use of JavaBeans 225
Design Patterns and JavaBeans 226
JSP. 2.0 Expression Language 227
Disabling the EL 227
JSP EL Syntax 228
Reserved Words 230
EL Functions 230
Good Uses of the JSP EL 231
Summary 234

6 JavaServer Pages Standard Tag Library 235


JSTL 1.0 Specification 235
Why You Should Use the JSTL 237
Installing the JSTL 237
JSTL Expression Language 238
Twin Libraries 239
Core Tags 239
General-Purpose Tags 239

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

7 Custom Tag Libraries 259


Why Custom Tags? 260
Tag Library Basics 261
How Are Tags Being Used? 262
New and Old Custom Tags 265
Tag Library Descriptors (TLDs) 265
What Is a Tag Library Descriptor? 266
Using a Tag Library Descriptor 267
Simple, JSP 2.0 Custom Tags 271
SimpleTag Interface 272
Attributes 275
Body Evaluation and Iteration 285
.tag Files 288
Cooperating Tags 299
Classic JSP Tag Handlers 300
Basic Tags 300
Coding a BasicTag 303
Reusing Tags 308
TryCatchFinally Interface 310
Cooperating Tags 311
Mixing New Tags with Classic Tags 313
Iteration Tags 315
Body Tags 321
Tag Scripting Variables 324
Tag Library Listeners 328
Validation 329
Summary

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

Filters That Provide JSP-Replacing Functionality 387


Summary 388

9 Managing State in a Web Application 389


HTTP and Session State 390
Using an ID to Identify Clients 391
javax.servlet.http.HttpSession 392
Cookies 395
Initializing Session Resources 406
Persistent State 411
Session Smearing 412
Sharing State Information via a Database 413
State and Thread Safety 414
Synchronizing 416
Protecting Servlet State 416
javax.servlet.SingleThreadModel 420
Protecting Session and Application State 421
Summary 422

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

11 Design Patterns 457


Why Use a Design Pattern? 458
Common Design Patterns 458
Model 1 459
Model 2 472
Good Model 2 Implementation 487
Jakarta Struts 490
Installing Struts 491
Struts Control Servlet 494
Actions 496

CONTENTS xi
falkner.fm.qxd 8/21/03 5:16 PM Page xii

Using Struts 507


Model 11⁄2 507
Abstracting DHTML via Custom Tags 510
Why Abstract DHTML with Custom Tags? 510
Coding DHTML Widget Custom Actions 511
Summary 512

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

13 Multi-Client Support 553


Who Should Read This Chapter 554
Separating Format from Content 555
Implementing Multi-Client Support 557
Templates 558
Transformations 563
Solving Multi-Client Problems 566
Creating a Multi-Client Interface 566
Non-Text Formats 586
Summary 588

14 Database Connectivity 591


What Is a Database? 592
SQL 594
CRUD 597
JDBC 605
javax.sql.DataSource 606
java.sql.Connection and java.sql.Statement 614
java.sql.ResultSet 617
A Simple JDBC-Based Application 624
Using JDBC Optimally 632
Connection Pooling 633
Optimized Statements 634
Database Administrators Are Expected to Know a Lot 638

xii CONTENTS
falkner.fm.qxd 8/21/03 5:16 PM Page xiii

JDBC Web Application Design Patterns 638


Data Access Object Design Pattern 640
Summary 649

15 Building a Complete Web Application 651


Designing a Web Application 652
Physical Implementation 654
Distributing the Workload: Dividing Up Who Does What 656
Practical Use of Web Application Labor Division 657
Implementing Database Support: Creating a Database and Using JDBC 658
Database Physical Design 658
Interfacing Without SQL 661
Implementing Business Logic: Filters and the Model 2 Design Pattern 662
Coding Model 2 Logic Classes and Populating
Request-Scope Variables 664
Dealing with Overly Complex Logic Components 687
Implementing Presentation Logic: JSP, Multi-Client Design, and
Internationalization 687
Building a Simple Presentation Page 688
Creating the Other Presentation Pages 696
Localized Content 703
(in Japanese) 709
Finishing the Site 711
Site-Wide Error Handling 712
Adding Security 715
Link Tracking 717
Caching and Compression 721
Adding the Egg 726
Summary 733

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.

About the Authors


Two authors collaborated on this book: Jayson Falkner and Kevin Jones. Both
Jayson and Kevin are well-known developers in the JavaServer Pages (JSP) and
Servlets communities, and both authors have worked extensively with the tech-
nologies. Servlets and JavaServer PagesTM: The J2EE TM Technology Web Tier origi-
nally started as Jayson’s project; however, during the JavaOne 2002 conference the
two authors met. It turns out Kevin was thinking of working on a similar title,
and the two decided to collaborate.

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

How the Book Is Organized


In this book you will find a few, hopefully delightful, things. The book is a com-
plete guide to Servlets and JavaServer Pages and their practical use for developers
familiar with HTML and basic Java. If you are unfamiliar with the terms Servlets
and JavaServer Pages, think of this book as a complete guide to building dynamic,
Java-based Web sites. It is assumed you understand Java and HTML. Never does
the book attempt to test these two skills; however, code examples in this book do
not include explanations of fundamental Java concepts and HTML syntax.
Before introducing the book’s content, there are a few points worth men-
tioning in relation to competing technologies, especially since you are likely
standing next to several books about building Web sites using the plethora of
other “superior” technologies. At all times this book follows the open-source
mindset—that is, software you need is free and you get all the source-code. It will
cost you or your development team absolutely nothing to get and use all the
software demonstrated, both directly and indirectly. In comparison to the

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

user-friendly error page when something goes wrong. Chapter 4


explains how Servlets and JSP extend the standard Java exception-
handling scheme. Since error handling is not commonly a well-
understood feature of Java, this chapter does not assume fluent use
of Java’s try-catch-finally statement.
• JavaBeans and the JSP Expression Language (Chapter 5): The
term “JavaBean” is used to mean many things in the Java world. As
applied to Servlets and JSP, JavaBeans are little more than a fancy
name for a simple Java class; however, the ambiguity of the term
combined with its popular use merits a complete discussion about
JavaBeans. Complementing this discussion is an introduction to the
JSP expression language (new in JSP 2.0). The JSP expression lan-
guage can greatly simplify the task JavaBeans were previously used
for. Chapter 5 provides a complete discussion of the new JSP EL,
and a discussion on good programming practices using both the
JSP EL and JavaBeans.
• JavaServer Pages Standard Tag Library (Chapter 6) and Custom
Tag Libraries (Chapter 7): Custom Tags is a popular feature of
JavaServer Pages that allow static text, such as HTML-like tags, to be
linked with Java classes. The functionality is at the center of several
popular JSP programming techniques, since it allows for a
developer to easily abstract code from pages designed to display
HTML. Understanding and using JSP custom tags is a skill every
JSP developer should have. Chapter 6 covers the standard set of
custom tags, and Chapter 7 is dedicated to explaining the mech-
anism of creating and using new custom tags.
• Filters (Chapter 8): A Filter is something that a developer can use
to cleanly intercept and modify requests and responses. The func-
tionality works well for caching and security reasons; however, it is
also conceptually a key part to building a good Web application.
Chapter 8 explains Filters and provides several examples of how
Filters are popularly used.
• Managing State in a Web Application (Chapter 9): The vast
majority of the World Wide Web relies on stateless protocols—that
is, communicating with one user twice is by default indistin-
guishable from communicating with two users once. However, most
every Web site relies on being able to keep track of who is receiving
information. Chapter 9 details both the problem and common solu-

xviii PREFACE
falkner.fm.qxd 8/21/03 5:16 PM Page xix

tions. Servlets and JavaServer Pages provide a seamless solution to


keeping state with a user, but it is very important as a Web
developer that you understand how the problem is solved. Without
such knowledge you may encounter unpredictable results from even
a simple Web application.
• Security (Chapter 10): Security is an all-important topic for an
obvious reason: if information communicated via the Internet
needs to be confidential something needs to guarantee confiden-
tiality. The task of providing security is always in check by the per-
sistence of people trying to break security. Servlets and JSP provide
a relatively simple method of using up-to-date security mecha-
nisms. Chapter 10 details how security works, how Servlets and JSP
implements security, and how to configure a secure Web site.
• Design Patterns (Chapter 11), Internationalization (Chapter 12),
and Multi-Client Support (Chapter 13): Understanding how tech-
nology works does not mean one knows how to best use the tech-
nology. Complimenting the earlier chapters of the book, several
popular tricks, techniques, and all-around good programming prac-
tices are explained in the last part of the book. This information is
exactly the type of information a developer needs, assuming one
understands the technology, and exactly the type of information
omitted from books that only detail a technology. Chapter 11,
Chapter 12, and Chapter 13 all explain popular approaches to using
Servlets and JSP to solve real world problems.
• Database Connectivity (Chapter 14): A database is almost always at
the center of a Web site, for good reason; however, the topic of data-
bases merits a full book. As a developer you will benefit from
understanding the basic theories of databases and how a database
can be used with Servlets and JSP. Chapter 14 provides a crash
course to basic use of a database and a detailed discussion of using
a database with Servlets and JSP. In practice Chapter 14 is no
replacement for a good book on your favorite database, but
Chapter 14 will enable you to create and use a database from
scratch.
• Building a Complete Web Application (Chapter 15): Ending the
book is one grand look at everything covered and a discussion on
how all the previous chapters are to be used in practice. How better
to accomplish this then by building a real Web application?

PREFACE xix
falkner.fm.qxd 8/21/03 5:16 PM Page xx

Chapter 15 uses all of the previous chapters to construct a book


support site for this book, the same Web application seen online
http://www.jspbook.com. The task is not difficult because it is little
more than a rehash of the concepts covered in this book and recy-
cling snippets of code, but the chapter nicely concludes the book
and really proves you can build a good Web application based on
the content of this manuscript.
You can do much with Servlets and JSP, and this book attempts to cover it all.
If you read through the whole text you will be fluent with the technologies and
able to take full advantage of them. Every chapter does rely on previous chapters.
Concepts and buzzwords are explained fully only once in the book, in what is
thought the appropriate place, and you are expected to read completely from the
start to the end.

The Book Support Web Site


Servlets and JavaServerTM Pages: The J2EETM Technology Web Tier is not a perfect
book, nor is everything the book covers best put in text. In a best attempt effort
at ensuring the book is top quality, even after publication, a book support site is
maintained at http://www.jspbook.com. At the book support site you will find
numerous things including current updates, FAQ, news about the book, working
code examples, references, and a method to reach the authors. This book support
site is not the standard publisher-supported site (and Addison-Wesley’s site is
quite nice), but it is something created and supported completely by the authors.
You are encouraged to use the book support site as a place to aid your reading of
the book and communicate with the authors.

Conventions Used in the Book


For clarity, a few arbitrary conventions are followed by this book. As authors our
goal is to try and convey our thoughts and experiences clearly. Where possible we
attempt to follow standardized or de-facto coding methods and writing tech-
niques. In cases where we have to make up a method of conveying information it
needs to be clear that we are doing just that. Documented here are all of the arbi-
trarily official standards that are used in this book.

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.

Mozilla and Tomcat


For consistency two primary pieces of software, Mozilla and Tomcat, are used
throughout the book and will be indirectly visual in examples. As further
explained later, all JSP and Servlets rely on a main piece of software called a con-
tainer. The reference container for JSP is Tomcat, http://jakarta.apache.org/
tomcat. All code in this book is tested against Tomcat, and many screenshots
show common behavior of the container. Be aware that Tomcat is the specific
container in all of these cases, and different containers might have slightly dif-
ferent results. This warning does not imply that the code would not work in other
containers; code should seamlessly work on any JSP 2.0 and Servlet 2.4 container.
The mention is solely to prevent possible confusion that might arise from
examples that give different styles of the same result when executed.

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.

The Book’s Cover


The cover of this book shows 3⁄4 of a yard-gnome. A yard-gnome1 is a ceramic
gnome that is intended to decorate a yard. Gnomes themselves are fictitious crea-
tures that have little if anything to do with yards. A question you might be asking
is “What do yard-gnomes have to do with Servlets and JSP or the J2EE Web Tier?”
The answer is absolutely nothing. The cover resulted from a style restriction we
had to use for this book and a bad joke that has obviously eluded far too many
people.

Yard-Gnomes on Holiday and Yard-Gnomes in France


Being that a yard-gnome does appear on the cover, two things are suggested of
creative readers. Traditionally yard-gnomes are hidden in the background of pic-
tures, particularly vacation pictures. Take a picture with this book hidden in the
background and email it to the book support site. Your picture will be displayed
unless it grossly violates the laws that govern common sense. Additionally, it is
fun to note that in France there is a serious problem of gangs stealing yard-
gnomes and returning them to “their natural habitat” or forested areas, particu-
larly city parks. If you can think of some way to replicate this phenomena using
the gnome on this book’s cover, please send a picture via email to the book
support site.

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!

1. Garden-gnome in the United Kingdom.

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

Setting Up a Servlet and JSP


Environment

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.

A Quick History of Web Development


The Servlet and JSP environment extends past the need for basic Java support. Any
computer running JSP or Servlets needs to also have a container. A container is a
piece of software responsible for loading, executing, and unloading the Servlets
and JSP. The reasons for this are largely related to the history of server-side Web
development. A quick overview of one of the earliest and most prominent server-
side dynamic content solutions, CGI, and the differences between it and Servlets

1
falkner.ch1.qxd 8/21/03 4:42 PM Page 2

is very helpful in understanding why a JSP/Servlet container is required. The exact


life cycle events that are managed by a container are discussed in Chapter 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

CGI Web Server

Request CGI Process

Request CGI Process

Request CGI Process

Figure 1-1 CGI Life Cycle

2 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 3

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.

CGI Web Server


CGI Process Pool

Request CGI Process

Request CGI Process

Request CGI Process

Figure 1-2 Pooled CGI Resources

A QUICK HISTORY OF WEB DEVELOPMENT 3


falkner.ch1.qxd 8/21/03 4:42 PM Page 4

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

Figure 1-3 Servlet Web Server Diagram

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.

4 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 5

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

Request CGI Process

Request CGI Process

Request CGI Process

Figure 1-4 Container Process

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.

Getting Java Support


Servlets and JavaServer Pages, also meaning all containers, rely on the Java pro-
gramming language. In the case of Servlets, the code is nothing more than a Java
class that implements the appropriate interface(s). Compiling a Servlet is iden-
tical to compiling a Java class. JSP is slightly more abstract. JSP, is compiled and
used exactly like a Servlet, but the process is almost always done automatically,
without a JSP developer noticing. When authoring a JSP, a developer uses a com-
bination of markup and code to make a page that usually resembles an HTML or
XML document. This page is compiled into a class file by the Servlet container
and automatically loaded.
The official Java platform is designed, owned, and managed by Sun
Microsystems. Unlike most other programming languages, Java is not designed
for you to compile to platform-specific instructions. Instead Java is compiled
down to byte code that gets interpreted by the computer running your Java
program. This means a Java program developed and compiled on one computer
will run on any other computer with Java support; Servlets and JSP can be com-
piled and run on most any operating system. This includes most all the Windows,
Linux, and Macintosh operating systems. This book assumes you are installing a
JSP environment on one of these systems and instructions are provided for
installation on each.

Downloading the Java 2 Standard Edition 1.4


Java 2 Standard Edition 1.4 (J2SE 1.4) support is required for code examples in
this book. Sun Microsystems provides a free reference implementation of Java 1.4
online. Unless you are using Macintosh OS X, go to http://java.sun.com/
j2se/1.4/ and download the latest Java distribution for your computer.
Macintosh OS X has proprietary support for Java 2. If you are running OS X, no
additional downloads are needed.

6 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 7

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.

Installing J2SE 1.4 on Microsoft Windows


Microsoft Windows comes in many varieties, with early versions having a big dis-
tinction between a desktop computer and a computer designed to be a server.
Practically speaking, a desktop computer running Windows 95 or Windows 98 is
a not a good choice for installing a production environment for Servlets and JSP,
but a Windows 95 or Windows 98 computer will suffice in order to try this book’s
examples. The Java distribution for Microsoft Windows will run on all versions
of the operating system excluding Windows 3.x. In this book, the focus is on
installing Java on a Windows NT, 2000, or XP computer. However, we realize that
many readers have a desktop PC running Windows 95 or Windows 98 at home.
An attempt will be made to help you if this is the case.
After downloading the J2SE 1.4, it must be installed on your system. The
download should be an executable file that can be run by double-clicking it.
Double-click on this file and follow the installation wizard through all the steps.
It does not matter where you install the J2SE 1.4, but it is worth noting the
location, as it is needed in a later part of this chapter.
Installation of the Java 2 Standard Development Kit 1.4 is now complete. Skip
ahead to the section entitled, “Tomcat”.

Installing J2SE 1.4 on Linux Distributions


Linux comes in far more varieties than Windows and operates on many more
hardware architectures. A walk-through installation guide for all Linux distribu-
tions is not attempted, but this guide should work on the vast majority of distri-
butions. Specifically this section gives a walk-through of installing the J2SE 1.4
on Red Hat Linux 7.3. It will greatly resemble installation on any Linux distri-
bution for x86 processors, as an RPM is not used. If you downloaded the RPM or

2. A free copy of the book can be found online, http://www.mindview.net/Books/TIJ/.

GETTING JAVA SUPPORT 7


falkner.ch1.qxd 8/21/03 4:42 PM Page 8

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.

Figure 1-5 Sun’s J2SDK 1.4 Licensing Terms

8 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 9

For Non-x86 Users: Compiling Java for Yourself


It is possible you are either an advanced user who dislikes non-optimized code or
that you do not have an x86 microprocessor. Both of these cases are largely
outside the scope of this book, but a quick pointer should get you well on your
way if that is what you seek. The “official” Java Linux code is maintained at
Blackdown Linux, http://www.blackdown.org. Visit Blackdown Linux if you
need the source code to either optimize your Java distribution or compile it for a
different architecture.

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.

Installing Jakarta Tomcat 5 on Windows


The Tomcat installation for Windows greatly resembles installing any other piece
of Windows software. The process involves downloading the Tomcat installation
executable file and running it to launch the Windows installation wizard. After a
few simple clicks, the wizard will have set up Tomcat to work with your Windows
distribution.
If you have not done so already, download the Windows executable file for the
Tomcat installation. You can find it at the following URL, http://jakarta.
apache.org/builds/jakarta-tomcat/release/. Simply follow the links to the
latest Tomcat 5 Windows executable file—as of this writing, the 5.0.2 beta release
of Tomcat is at http://jakarta.apache.org/builds/jakarta-tomcat/release/
v5.0.2-alpha/bin/jakarta-tomcat-5.0.2.exe. After downloading the exe-
cutable, double-click on it to start the installation wizard. A screen similar to

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.

GETTING JAVA SUPPORT 9


falkner.ch1.qxd 8/21/03 4:42 PM Page 10

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-6 Windows Installation Wizard

10 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 11

Figure 1-7 Installation Wizard Choosing Tomcat’s Components

Figure 1-8 Installation Wizard for Installing Tomcat

GETTING JAVA SUPPORT 11


falkner.ch1.qxd 8/21/03 4:42 PM Page 12

Figure 1-9 Installation Wizard for Configuring Tomcat

Figure 1-10 Installation Wizard Showing the Location of the Current JVM

12 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 13

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.

Figure 1-11 Installation Wizard for Installing Tomcat Files

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.

GETTING JAVA SUPPORT 13


falkner.ch1.qxd 8/21/03 4:42 PM Page 14

Figure 1-12 Tomcat Welcome Page after Completing the Installation

• startup.bat: The startup.bat 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.bat: The shutdown.bat 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.bat script and then
startup.bat be executed to reload the server. Alternatively you can also use an
automated utility like Ant, which is discussed later in this chapter, to manage
reloading, compiling, and other repetitive aspects of developing Servlets and JSP.

Windows 9X/ME “out of environment space”


Just because you are using Windows 9x, or Millennium, does not mean you will
have a problem, but be aware that a common problem does exist. If when exe-
cuting startup.bat or shutdown.bat, an “out of environment space” error

14 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 15

occurs, do the following. Right-click on the startup.bat and shutdown.bat files.


Click on Properties then on the Memory tab. For the Initial environment field,
enter 4096. After you click apply, Windows will create shortcuts in the directory
which you can use to start and stop the container. Use these shortcuts to start and
stop Tomcat.
What is happening is that the batch file is not allocating enough memory to
execute its commands. The fix is to simply add more memory. The Tomcat devel-
opers are aware of this problem and are trying to incorporate fixes into
startup.bat and shutdown.bat.

Installing Jakarta Tomcat 5 on Linux and Macintosh OS X


The Tomcat project is continuously expanding the different types of installation
packages in which Tomcat releases are available. If you notice a Tomcat instal-
lation package that matches special installation software for your specific Linux
distribution, feel free to download and use the appropriate file. For this walk-
through, installation will be of the compiled Java code packaged in a tarball5.
Download the Tomcat tarball jakarta-tomcat-5.0.tar.gz" from http://
jakarta.apache.org/builds/jakarta-tomcat/release/. Installation is as easy
as decompressing the Tomcat binaries and setting two environment variables.
Decompress the tarball by using the tar and gzip compression utilities from
the command prompt. Here is what the command would look like if you had
placed the download in the /usr directory.
gunzip -c /usr/jakarta-tomcat-5.0.tar.gz | tar xvf -

The Tomcat binaries will be available in the /usr/jakarta-tomcat-5.0


directory or a similarly named directory that matches the version of Tomcat you
downloaded. For the rest of this walk-through, it is assumed this is the directory
you are also using. If not, change the directory name in examples to match the
location where you uncompressed Tomcat.
Before starting Tomcat, two environment variables need to be set: JAVA_HOME
and TOMCAT_HOME. The JAVA_HOME variable corresponds to the directory of the
J2SDK 1.4 installed earlier in this chapter. The TOMCAT_HOME variable corresponds
to the directory into which you just uncompressed Tomcat. Set and export the

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.

GETTING JAVA SUPPORT 15


falkner.ch1.qxd 8/21/03 4:42 PM Page 16

Figure 1-13 Tomcat Welcome Page Appears after Starting Tomcat

two environment variables. The commands would be similar to the following if


the J2SDK is installed in the /usr/java/jdk1.4 directory and Tomcat 5 is
installed in the /usr/jakarta-tomcat-5.0 directory; replace each variable
accordingly to match your specific case:
JAVA_HOME=/usr/java/jdk1.4
TOMCAT_HOME=/usr/jakarta-tomcat-5.0
export JAVA_HOME TOMCAT_HOME

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.

16 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 17

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.

Switching Tomcat to Port 80, the Default HTTP Port


For all practical purposes it does not matter what port you run Tomcat on.
Ports 8080, 80, 1234, and 9999 all work the same. However, any port besides 80,
which is being used for HTTP, comes with some slight annoyances that it
would be nice to avoid. Specifically, the default port for HTTP is port 80. Recall

GETTING JAVA SUPPORT 17


falkner.ch1.qxd 8/21/03 4:42 PM Page 18

the previously used URL for Tomcat’s welcome page, http://127.0.0.1:8080/


index.html. The localhost address, 127.0.0.1, is universal, but the 8080 is
required because Tomcat’s HTTP connector is not listening on port 80; the
default configuration for Tomcat is for it to listen on port 8080. The 8080 is
slightly annoying, especially when needing to add the 8080 to all local absolute
links in your Web application.
In order to simplify the book examples and to avoid confusion, we will now
configure Tomcat to use port 80, which is the default HTTP port. This is done by
editing Tomcat’s configuration file, /conf/server.xml. Open this file with your
favorite text editor and do a search for ‘8080’; you should find the following
entry:
<!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 -->
<Connector className="org.apache.coyote.tomcat5.CoyoteConnector"
port="8080" minProcessors="5" maxProcessors="75"
enableLookups="true" redirectPort="8443"
acceptCount="10" debug="0"
connectionTimeout="20000"
useURIValidationHack="false" />

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.

18 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 19

Tomcat User’s Guide


The Tomcat’s User’s Guide is the official documentation for Tomcat. This should
be the first place you look for help when configuring and using Tomcat. The
Tomcat User’s Guide can be found online at the Jakarta Tomcat Web site,
http://jakarta.apache.org/tomcat.

Tomcat User Mailing List


The Tomcat user mailing list is the best place to find community support for con-
figuring and using Tomcat. This mailing list consists of most all the Tomcat
developers and many of the current users of Tomcat. By posting a question on
this mailing list, you can try to solicit information from the current Tomcat
experts. You can subscribe to this mailing list by following the instructions on the
Jakarta Mailing List page, http://jakarta.apache.org/site/mail.html.
Be warned the Tomcat user mailing list generates a lot of traffic. A hundred
or more emails a day is not uncommon; however, it is only an issue if you do not
wish to deal with that volume of email. There are many benevolent people, which
is obvious on the Tomcat user mailing list because of the unbelievable amount of
questions they answer. An alternative to using the Tomcat user mailing list is to
consult the online archives, which can be found using the same link.

Book Support Site


For the most current information and updates of this chapter’s walk-through
guides, use the book support site, http://www.jspbook.com. Along with the
latest versions of the walk-through guides, this site also contains a Frequently
Asked Question (FAQ) section for questions relating to this book. Many of
these questions answer problems relating to Tomcat configuration issues for
various software environments. Additionally, the book support site is intended
to provide a place that can deal with any unexpected issues occurring after
publication.

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

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4">


</web-app>

20 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 21

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

<Context path="/jspbook" docBase="jspbook" debug="0"/>

Restart Tomcat to reflect the changes made in the server.xml configuration


file and to load the new Web Application. You can now browse to the newly
created jspbook Web Application by using the following URL, http://
127.0.0.1/jspbook/. Because nothing has been placed in this Web Application,
an empty directory is displayed as shown in Figure 1-14.
The jspbook Web Application is used for examples throughout the rest of the
book. Until you know a little more about JSP and Servlets, it will be difficult to
create dynamic content using this Web Application; however, nothing stops you
from using static resources such as an HTML file. Try creating a simple HTML
page that welcomes a visitor. Copy and name the following HTML code Listing
1-3 as index.html and place it in the /webapps/jspbook directory of the Tomcat
installation.
Listing 1-3 index.html

<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

Figure 1-14 Empty Directory Listing for jspbook Web Application

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.

/WEB-INF and web.xml


The Servlet specification defines a configuration file called a deployment
descriptor that contains meta-data for a Web Application and that is used by the
container when loading a Web Application. This file is always located in the
/WEB-INF directory of a Web Application and must be named web.xml. When a
container loads a Web Application, it checks this file. As noted, web.xml contains
application meta-data, such as default pages to show, Servlets to load, and

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.

22 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 23

Figure 1-15 index.html Rendered by Web Browser

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

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4">


<welcome-file-list>
<welcome-file>welcome.html</welcome-file>
</welcome-file-list>
</web-app>

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

Figure 1-16 Directory Listing

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.

Java Classes and Source Files


Throughout the book examples will be taking advantage of existing Java APIs as
well as creating new Java classes. One of the most common mistakes new Servlet
and JSP developers make is where they place Java source code and compiled Java
classes. The intuitive approach is to place these files in the same directory as that
in which static content is placed for the Web Application. While it may seem
logical at first, this approach has two problems. The first is that any individual
browsing to your Web site will, by default, be able to access any files not in the
/WEB-INF directory. This means your code is freely available for people to
download and use or possibly abuse. The second problem is that the container

24 SETTING UP A SERVLET AND JSP ENVIRONMENT


falkner.ch1.qxd 8/21/03 4:42 PM Page 25

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.

Java Archive (JAR) Files


A Java Archive file is a convenient method for consolidating a set, usually a
package, of Java class files into one compressed, portable file. The Java specifica-
tions define the exact rules of a JAR file, but an easy way to think of them is
nothing more than a set of Java classes ZIP-compressed together. JAR files are a
very popular method of distributing Java code and are commonly used by Web
Applications. As defined in the Servlet specification, any JAR file placed in the
/WEB-INF/lib directory of a Web Application is made available for use by code
in the same Web Application. Later examples in this book will give some concrete
examples of using this functionality. The complete specifications for creating and
using a basic JAR are not in the scope of this book. You can find a complete guide
to creating JAR files in the J2SE documentation included with your J2SE
download. The task is not hard but is outside the scope of this text.

Web Application Resource (WAR) Files


Web Application Resource files are functionally similar to JAR files, but are used
to consolidate an entire Web Application into one compressed and portable file.
WAR files are officially defined by the Servlet specification. The compression
used for a WAR file is also ZIP; using existing JAR utilities in the Standard Java
Development Kit can easily make WAR files. WAR files are a great solution for
packaging a Web Application and they are commonly used to bundle documen-
tation with examples for JSP and Servlet-related software.
Most of the examples found in later chapters deal with expanding and
enhancing existing Web Applications. WAR files are only helpful to either start a
Web Application or to package a finished one. For this reason WAR files will not

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.

What Does Ant Do?


Ant performs “tasks”, any number of them, and in any order, possibly dependent
on previously accomplished tasks. There are many default tasks that Ant defines;
Ant also allows for Java developers to code custom tasks. In use, Ant takes a

26 SETTING UP A SERVLET AND JSP ENVIRONMENT


Random documents with unrelated
content Scribd suggests to you:
whittle out a long-handled wooden ladle with which to do the
basting.
By another device of his the roasting fowl was kept turning as
fast or as slowly as might seem desirable. This device consisted of
two very slender vines attached to the supporting vine at a point
several feet above the fire. One of the “twirlers,” as Dick called the
slender vines, was wrapped several times around the supporting
vine in one direction and the other in the opposite way.
Sitting on opposite sides of the fire, and each grasping a “twirler,”
Dick and Larry kept the turkey turning first one way and then the
other.
While they were engaged in this, an abundant supply of Tom’s
sweet potatoes were roasting in the ashes.
“Now we are at Quasi,” said Cal, just before the turkey was
declared “done to a turn”—“at Quasi, the object of all our hopes, the
goal of our endeavors, and the guiding star of all our aspirations
during a period of buffetings, trials and sore afflictions. We are
securely at Quasi, and our residence—which prosaic people might
call a hut, hovel or shanty, but which is to us a mansion—is
practically finished. It is only meet and fit, and in accordance with
Homeric custom, that we should celebrate the occasion and the
toilsome achievements that have made it possible, by all possible
lavishness of feasting. All of which means that I am going to make a
pot of robust and red-hot coffee to drink with the turkey and
‘taters.’”
It was a hungry company that sat down on the ground to eat
that supper, and if there was anything lacking in the bill of fare, such
appetites as theirs did not permit the boys to find out the fact.
“It is an inflexible rule of good housewives,” drawled Cal, when
the dinner was done, “that the ‘things’ as they call the dishes, pots,
pans, and the like, shall be cleared away and cleansed. So here
goes,” gathering up the palmete leaves that had served for plates
and tossing them, together with the bones and fragments of the
feast, upon the fire, where they quickly crackled into nothingness.
“There aren’t any cooking utensils, and as for these exquisitely
shaped agate iron cups, it is the function of each fellow to rinse the
coffee out of his own. Oh, yes, there’s the coffee pot I forgot it, and
by way of impressing the enormity of my fault upon a dull
intelligence I’ll clean that myself. A hurried scouring with some sand
and water, followed by a thorough rinsing, ought to do the business
finely.”
“I say, Cal,” said Dick, “I wish you would remember that this is
your off night.”
“I confess I don’t understand. Do you mean that I shall leave the
coffee pot for some other member of the company to scour?”
“No. I mean this is your off night for word-slinging. The professor
is going to tell us some things and we want to hear him. So, ‘dry
up.’”
“I bow my head in contriteness and deep humiliation. You have
the floor, Professor.”
“May I ask you young gentlemen not to call me ‘professor’?”
Dunbar asked very earnestly.
“Why, of course, we will do as you like about that,” answered
Larry; “we have been calling you ‘professor’ merely out of respect,
and you told us you were or had been a professor in a college.”
“Yes, I know, and I thank you for your impulse of courtesy. I
used the word descriptively when I told you I had been a ‘professor’
of Natural History. Used in that way it is inoffensive enough, but
when employed as a title—well, you know every tight-rope walker
and every trapeze performer calls himself ‘professor.’”
“Well, you must at least have a doctorate of some kind,” said
Dick, “and so you are entitled to be addressed as ‘Dr. Dunbar.’”
“No, not at all. Of course a number of colleges have offered me
baubles of that cheap sort—asking to make me ‘LL.D.,’ or ‘Ph. D.,’ or
‘L. H. D.,’ or some other sham sort of a doctor, but I have always
refused upon principle. I hate shams, and as to these things, they
seem to me to work a grievous injustice. No man ought to be called
‘Doctor’ unless he has earned the degree by a prescribed course of
study and examinations. Honorary degrees are an affront to the men
who have won real degrees by years of hard study. With two or
three hundred colleges in this country, each scattering honorary
degrees around and multiplying them every year, all degrees have
lost something of their value and significance.”
“How shall we address you then?” asked Larry.
“Simply as ‘Mr. Dunbar.’ The President of the United States is
entitled to no other address than ‘Mr. President.’ In a republic
certainly ‘Mr.’ ought to be title enough for any man. Call me ‘Mr.
Dunbar,’ please.”
“Well, now, Mr. Dunbar, won’t you go on and tell us what you
promised?”
“What was it? I have quite forgotten.”
“Why, you said you had been led to suspect that your fish—the
kind that takes wing and flies away into the bushes—had a sense of
taste. Did you mean to imply that fishes generally have no such
sense?”
“Yes, certainly. There are very few fishes that have capacity of
taste. They have no need of it, as they bolt their food whole, and
usually alive. There are curious exceptions, and—”
“But, Mr. Dunbar,” interrupted Tom, “is it only because they
swallow their food whole that you think they have no sense of taste?
Is there any more certain way of finding out?”
“Yes, of course. The sense of taste is located in certain nerves,
called for that reason ‘gustatory nerves,’ or ‘taste goblets.’ Now, as
the fishes generally have no gustatory nerves or taste goblets, we
know positively that they do not and cannot taste their food. That is
definite; but the other reason I gave is sufficient in itself to settle the
matter. The gustatory nerves cannot taste any substance until it is
partially dissolved and brought into contact with them in its dissolved
state. You can test that for yourself by placing a dry lump of sugar in
your mouth. Until the saliva begins to dissolve it you can no more
recognize any taste in it than in a similar lump of marble.”
“But why do they eat so voraciously then? What pleasure do they
find in it?” asked Dick.
“Chiefly the pleasure of distending the stomach, but there is also
the natural craving of every living organism for sustenance, without
which it must suffer and die. That craving for sustenance is
ordinarily satisfied only by eating, but it may be satisfied in other
ways. Sometimes a man cannot swallow because of an obstruction
in the canal by which food reaches the stomach. In such cases the
surgeons insert a tube through the walls of the body and introduce
food directly into the stomach. That satisfies the desire for
sustenance, though the patient has not tasted anything. When a fish
takes a run and jump at a minnow and swallows it whole at a gulp,
he is doing for himself much the same thing that the surgeon does
for his patient.”
“But, Mr. Dunbar,” Tom asked, “why is it then that the same
species of fish will take a particular kind of bait at one time of year
and won’t touch it at other times? In the very early spring I’ve
caught lots of perch on worms, while a little later they would take
nothing but live bait, and still later, when they were feeding on
insects on the surface, I’ve known them to nose even live bait out of
their way, refusing to take anything but the insects. If they don’t
taste their food, why do they behave in that way?”
“Frankly, I don’t know,” Dunbar answered. “I have formed many
conjectures on the subject, but all of them are unsatisfactory.
Perhaps somebody will solve the riddle some day, but at present I
confess I can’t answer it.”
Dunbar stopped as if he meant to say no more, and Tom became
apologetic.
“Won’t you please go on, Mr. Dunbar? I’m sorry I interrupted.”
“Oh, but you must interrupt. If you don’t interpose with
questions, how am I to know whether I’ve made my meaning clear
or not? And how am I to know what else you wish to hear? No, no,
no. Don’t withhold any question that comes into your mind, or I shall
feel that I’m making a bore of myself by talking too much.”
“You spoke,” said Dick, “of certain fishes that are exceptions to
the rule.”
“Oh, yes; thank you. I meant to come back to that but forgot it.
The chief exception I know of is the bullhead, a small species of
catfish that abounds in northern waters, particularly in the
Adirondack lakes. The bullhead has gustatory nerves all over him. He
can taste with his tail, or his side, or his head, as well as with his
mouth. Of course there’s a good reason for the difference.”
“I suppose so, but I can’t imagine what it is,” said Larry.
“Neither can I,” echoed Tom and Dick. Cal continued the silence
he had not broken by a word since Dunbar had begun. Observing
the fact, Dick was troubled lest his playful suppression of Cal at the
beginning had wounded him. So, rising, he went over to Cal’s side,
passed his arm around him in warm friendly fashion, and said under
his breath:
“Did you take me seriously, Cal? Are you hurt or offended?”
“No, you sympathetically sublimated idiot, of course not. It is
only that I want to hear all I can of Mr. Dunbar’s talk. You know I’ve
always been interested in fish—even when they refuse to take bait.
Hush. He’s about to begin again.”
“Oh, it is obvious enough when you think about it,” said Dunbar.
“It is a fundamental law of nature that every living thing, animal or
vegetable, shall tend to develop whatever organs or functions it has
need of, for defense against enemies or for securing the food it
needs. You see that everywhere, in the coloring of animals and in a
thousand other ways. The upper side of a flounder is exactly the
color of the sand on which he lies. That is to prevent the shark and
other enemies from seeing him and eating him up. But his under
side, which cannot be seen at all by his enemies, is white, because
there is no need of color in it. I could give you a hundred
illustrations, but there is no need. Your own daily observation will
supply them.”
Again Dunbar paused, as if his mind had wandered far away and
was occupying itself with other subjects. After waiting for a minute
or two Cal ventured to jog his memory:
“As we are not familiar with the bullhead—we who live down
South—we don’t quite see the application of what you’ve been
saying, Mr. Dunbar. Would you mind explaining?”
“Oh, certainly not,” quickly answered the man of science, rousing
himself as if from sleep. “I was saying—it’s very ridiculous, but I’ve
quite forgotten what I was saying. Tell me.”
“You were telling us about the bullhead’s possession—”
“Oh, yes, I remember now. You see fishes generally hunt their
prey by sight, in the clear upper water and in broad daylight. They
quit feeding as soon as it becomes too dark to see the minnows or
other things they want to eat. As they hunt only by sight, they have
no need of the senses of smell and taste, and so those senses are
not developed in them. With the bullhead the thing is exactly turned
around. He never swims or feeds in the upper waters. He lives
always on or very near the bottom of comparatively deep water, in
thick growths of grass, where sight would be of little use to him for
want of light. He feeds almost entirely at night, so that those who
fish for him rarely begin their sport before the dusk falls. In such
conditions Mr. Bullhead finds it exceedingly convenient to be able to
taste anything he may happen to touch in his gropings. So with him
the sense of taste is the food-finding sense, and in the long ages
since his species came into being that sense has been developed out
of all proportion to the others. He has very little feeling and his
nervous system is so rudimentary that if you leave him in a pail
without water and packed in with a hundred others of his species,
he seems to find very little to distress him in the experience. You
may keep him in the waterless pail for twenty-four hours or more,
and yet if you put him back into the pond or lake he will swim away
as unconcernedly as if nothing out of the ordinary had happened.
But then all species of fish are among the very lowest forms of
vertebrate creatures, so that they feel neither pain nor pleasure at
all keenly.”
Suddenly Dunbar ceased speaking for a minute. Then he seemed
to speak with some effort, saying:
“There are many other things I could tell you about fish, and if
you’re interested, I’ll do so at another time. I’m very sleepy now.
May I pass the night here?”
“Certainly. I’ll bring you some moss—”
“It isn’t at all necessary,” he answered, as he threw himself flat
upon the earth and fell instantly into a slumber so profound that it
lasted until Cal called him to breakfast next morning.
XXXI

DUNBAR’S STRANGE BEHAVIOR

Dunbar was very silent during breakfast. He answered courteously


when spoken to, as he always did, and there was no suggestion of
surliness in his silence. In response to inquiries he declared that he
had slept well and hoped the boys had done the same. But he added
no unnecessary word to anything he said, and made no inquiries as
to plans for the day. His manner was that of a person suffering
under grief or apprehension or both.
As soon as breakfast was over he started off into the woods in a
direction opposite to that in which his camp lay. He took neither his
rifle nor his butterfly net with him. He simply walked into the
woodlands and disappeared.
At dinner time he was nowhere to be found. As evening drew
near the boys agreed to postpone their supper to a later hour than
usual in anticipation of his return. But late as it was when at last
they sat down to their evening meal, he was still missing.
The boys were beginning to be alarmed about him, for they had
already learned to like the man and regard him as a friend.
“We must do something at once,” suggested Dick.
“But what can we do?” asked Larry. “I confess I can think of few
possibilities in the way of searching for him at this time of a very
dark night—for the clouds completely shut out the moonlight. Has
anybody a suggestion to offer? What say you, Cal?”
“First of all,” was the reply, “we must carefully consider all the
possibilities of the situation. Then we shall be better able to lay
plans of rescue that may result in something. Let’s see. To begin
with, he hasn’t left Quasi. He hasn’t any boat and there is absolutely
no land communication with the main. So he is somewhere on Quasi
plantation.
“Secondly, what can have happened to him? Not many things
that I can think of. Old woods wanderer that he is, it isn’t likely that
he has succumbed to any woodland danger, if there are any such
dangers here, as there aren’t. There isn’t any wild beast here more
threatening than a deer or a ’possum. He had no gun with him, so
he cannot have shot himself by accident. He may have got lost, but
that is exceedingly unlikely. He is used to finding his way in the
woods, and it is certain that he thoroughly explored Quasi during the
time he was marooned here and flying his distress signal. If by any
possible chance he is lost, he’ll soon find himself again. The only
other thing I think of is that he may have tripped and fallen,
breaking something.”
“I should doubt his doing that,” said Larry, “for he’s as nimble as
any cat I ever saw. Still, there’s the chance. What shall we do to
meet it?”
“We can’t scatter out and search the woods and thickets in the
dark,” suggested Dick.
“No,” said Tom; “if we did he would have to go in search of four
other lost fellows if he should happen to turn up. But we can keep
up a big fire and we can go out a little way into the woods, fire our
shotguns, give all the college yells we know, and then listen.”
“Good suggestion, that about shooting and yelling,” said Cal.
“Besides, I like to yell on general principles. But we shan’t need to
keep up a bonfire, and the night is very hot.”
“But he might see the bonfire,” answered Tom in defense of his
plan, “and he’d come straight to it, of course, if he’s lost.”
“We’ll put up something else that he can see farther and better.”
“What?”
“A fat pine torch.”
“Where?”
“Did you observe a catalpa tree that stands all alone over there
on the highest part of the bluff, which is also the highest point in the
whole land of Quasi?”
“Of course, if you mean over there, near the Hunkydory’s
anchorage.”
“Yes, I mean that. There isn’t another tree anywhere near it. I
can’t imagine how it came to grow out there on that bald bluff,
unless somebody planted it. However, that’s no matter. The tree is
there and a torch fixed in the top of it could be seen from almost
every nook and corner of Quasi, while here we are in a pocket of
trees and thick growths of every kind. A bonfire here could be seen
a very little way off.”
Cal’s modification of Tom’s plan was promptly approved as the
best possible for that night. The company went into the woods,
pausing at several points to fire their guns and to yell like demons.
No results following, they returned and set to work making huge
torches of fat pine, one of which was kept burning in the tree-top
throughout the night, a fresh one being lighted whenever an old one
burned out.
It was all to no purpose. Morning came and still there was no
sign of Dunbar.
Breakfast was cooked and eaten, together with a reserve supply
of food for the boys to carry with them on the search of the
plantation, which they had decided to make that day. Still no sign of
the missing man!
“Now, Cal,” said Larry, “this thing is becoming serious. We must
find poor Mr. Dunbar to-day whatever else happens. We must scour
the place till we accomplish that. We must scatter, but we must see
to it that we get together again. Suppose you suggest a plan of
procedure. You’re better than any of us at that.”
“I will,” said Cal, who had lost all disposition to be facetious. “He
may be along the shore somewhere, so two of us had better follow
the sealine, one going one way and the other in the opposite
direction. They can cover double ground by going through the
woods and open glades, only keeping near enough the shore to see
it well. The other two will need no directions. Their duty will be to
search the woods and thickets. Where the woods are open they can
cover the ground rapidly, and also in the old fields wherever they
haven’t grown up too thickly. But the denser woods and canebrakes
must be searched. Look particularly for trails. No one can possibly
pass into or through such growths without leaving a trail behind.
Look for trails and follow them; don’t bother about the unbroken
growths. Now as to getting back here. We must all come back well
before nightfall. No matter where we may be on Quasi, it will be
easy to find some point near from which the lone catalpa tree can be
seen. Make for that all of you and nobody will get lost. Finally, if any
of you find Mr. Dunbar and need help, fire three shots about half a
minute apart and we’ll all go to the point of firing. Now let’s be off.”
It was nearly sunset when Tom reached the catalpa tree on his
return. He had not found Dunbar, but for reasons of his own he
waited rather impatiently for the coming of his comrades. They were
not long delayed, but the blank, anxious face of each as he
appeared was a sufficient report to the others.
“The search is a failure!” said Larry, dejectedly.
“Absolutely,” answered Cal.
“No, not absolutely,” said Tom, feeling in his pocket. “I found
something, and I’ve waited till you should all be here before
speaking of it.”
“What is it? Tell us quick.”
“This,” answered Tom, drawing forth a letter, “and this,”
producing a pruning knife with a curved blade, which they had all
seen Dunbar use. “The letter was pinned to a tree with the point of
the knife blade.”
“Never mind that,” said Larry, impatiently; “read the letter.”
Tom read as follows:
“I expect to be with you young gentlemen very soon. But in case I
never see you again, please don’t think me ungrateful for all your
kindnesses. There are times when I cannot endure a human presence—
even the—”

Tom stopped reading, and explained:


“It breaks off right there, and there is no signature, or address,
or anything else.”
The boys stared at each other in amazement, and for a time
uttered no word. When they begun talking again it was only to
wonder and offer conjectures, and the conjectures seemed so futile
that at last the little company ceased to try to read the riddle. Then
Larry said:
“Come on. There’s nothing more to be done to-night and we’re
all half famished. We must have a good hearty supper, and then
perhaps we’ll think of something more that we can do.”
“I doubt that,” said Cal; “but I say, Tom, you have a positive
genius for finding things—turtles’ eggs, smugglers’ camps, sweet
potato patches, letters hidden in the woods, and everything else.
Perhaps you’ll find poor Mr. Dunbar yet.”
“I was just thinking of some other things that we ought to find,
and that right away.”
“What things?”
“Why, Mr. Dunbar’s. You know he has never brought any of them
to our camp, and we know he writes and draws and all that. He
must have some place up near his old bivouac where he can keep
his papers and drawings and specimens dry. It seems to me we
ought—”
“Of course we ought,” broke in Cal. “There may be something
there to give us a clue. What do you say, Larry?”
“It is a good suggestion of Tom’s, and we’ll act upon it at once.”
Turning in a direction opposite to that which led to their own
camp the boys visited the spot where Dunbar had lived before they
came to Quasi. They searched in every direction, but found no trace
of any of the man’s belongings. It was rapidly growing dark when at
last they gave up the work of exploring, and decided to resume it
again in the morning.
As they approached their camp through the woods and thickets,
they were surprised to see their camp-fire blazing up briskly, though
none of them had been near it since the early morning. As they
came out of the bushes, they were still more astonished to see
Dunbar busying himself with supper preparations. Larry had just
time enough before Dunbar saw them to say to the others in an
undertone:
“Not a word about this, boys, until he asks.”
“Good evening, young gentlemen,” was Dunbar’s greeting,
delivered in a cheery voice; “I have taken the liberty of getting
supper under way in anticipation of your coming. I am sure you
must be tired and hungry after a hard day’s shooting. By the way, a
cup of tea is always refreshing when one is tired, and fortunately I
have a little packet of the fragrant herb among my things. I’ll run up
there and fetch it.”
As he spoke he started off briskly and nimbly.
“Evidently he isn’t tired, anyhow,” suggested Dick.
“And evidently he has some dry place in which to keep his
things,” added Cal, “and I mean to ask him about it.”
“Don’t,” said Larry, earnestly. “That would be grossly
impertinent.”
“Not at all, if it’s done in the proper way,” Cal replied, “and I’ll do
it in that way.”
And he did. When Dunbar returned, he carried the tea, closely
sealed up in tin foil.
“Is that thin tin foil sufficient to keep tea dry?” Cal asked.
“If you keep the packet in a dry place it is,” Dunbar answered.
“The tin-foil prevents the delicate aroma of the tea from escaping,
and at the same time forbids the leaves to absorb moisture from the
air. When I’m moving about in a boat I carefully wrap any tea I may
have in my waterproof sheets, but that is apt to give it an
undesirable flavor, so my first care upon landing is to provide a dry
storage place for my tea, my ammunition, my papers and whatever
else I may have that needs protection. By the way, I’ve never shown
you my locker up there. I’ll do so to-morrow morning. I’ll not forget,
as I must go there for writing and drawing materials. I have some
things in my mind that I simply must put down on paper at once.”
At that moment he thrust his hand into his pocket and felt there
for some seconds. Then he said:
“That’s very unfortunate. I’ve managed to lose my knife.”
“I think I must have found it, then,” said Tom, holding it out;
“isn’t that it?”
“Yes, thank you. I’m particularly glad to get it again, as it is the
only one I have at Quasi. I usually buy half a dozen at a time, and
so the loss of one doesn’t annoy me. But just now I have only this
one.”
He did not ask where or when Tom had found the knife, nor did
he seem in the least surprised that it was found. The circumstance
did not seem to remind him of his letter or of anything else.
The boys were full of wonder and curiosity, but they asked no
questions.
XXXII

A RAINY DAY WITH DUNBAR

Dunbar was in excellent spirits that evening. He seemed indeed


like one who has had some specially good fortune happen to him, or
one suddenly relieved of some distress or sore annoyance.
Throughout the evening he talked with the boys in a way that
greatly interested them. He made no display of learning, but they
easily discovered that his information was both vast and varied, and
better still, that his thinking was sound, and that he was a master of
the art of so presenting his thought that others easily grasped and
appreciated it.
When at last the evening was completely gone, he bade his
companions a cheery good night, saying that he would go over to
the bluff and sleep near the catalpa tree.
“You see there are no sand flies to-night,” he explained, “and I
like to smell the salt water as I sleep.”
“What do you make of him, Larry?” Dick asked as soon as their
guest was beyond hearing.
“I don’t know. I’m puzzled. What’s your opinion?”
“Put it in the plural, for I’ve a different opinion every time I think
about it at all.”
“Anyhow,” said Tom, “he must be crazy. Just think—”
“Yes,” interrupted Cal, “but just think also how soundly he thinks.
Let’s just call him eccentric and let it go at that. And who wouldn’t
be eccentric, after living alone in the woods for so long?”
“After all,” Dick responded, “we’re not a commission in lunacy,
and we’re not under the smallest necessity of defining his mental
condition.”
“No,” Cal assented; “it’s a good deal better to enjoy his company
and his talk than to bother our heads about the condition of his. He’s
one of the most agreeable men I ever met—bright, cheerful, good
natured, scrupulously courteous, and about the most interesting
talker I ever listened to. So I for one give up trying to answer
conundrums, and I’m going to bed. I wouldn’t if he were here to go
on talking, but after an evening with him to lead the conversation, I
find you fellows dull and uninteresting. Good night. Oh, by the way,
I’ll slip away from here about daylight and get some pan fish for
breakfast.”
Early as Cal was in setting out, he found Dunbar on the shore
ready to go with him.
“I hope to get a shark,” the naturalist said, “one big enough to
show a well-developed jaw, and they’re apt to bite at this early hour.
I’ve a line in the boat there with a copper wire snell.”
“Are you specially interested in sharks?”
“Oh, no, not ordinarily. It is only that I must make a careful
drawing or two, illustrative of the mechanical structure and action of
a shark’s jaw and teeth, to go with an article I’m writing on the
general subject of teeth in fishes, and I wish to draw the illustrations
from life rather than from memory. It will rain to-day, and I’m going
to avail myself of your hospitality and make the drawings under your
shelter.”
“Then perhaps you’ll let us see them?”
“Yes, of course, and all the other drawings I have in my portfolio,
if they interest you.”
“They will, if you will explain and expound a little.”
Dunbar gave a pleased little chuckle as he answered:
“I’ll do that to your heart’s content. You know, I really think I like
to hear myself talk sometimes.”
“Why shouldn’t you? Your talk would delight anybody else.”
“Here’s my shark,” excitedly cried Dunbar, as he played the fish.
“He’s nearly three feet long, too—a bigger one than I hoped for. Now
if I can only land him.”
“I’ll help you,” said Cal, leaning over the rail with a barbed gaff
hook in his hand. “Play him over this way—there, now once more
around—here he is safe and sound.”
As he spoke he lifted the savage-looking creature into the boat
and Dunbar managed, with some little difficulty, to free the hook
from his jaws without himself having a thumb or finger bitten off.
“Not a tooth broken!” he exclaimed with delight. “I’ll dissect out
the entire bony structure of the head to-day and make a drawing of
it. Then I’m going to pack it carefully in a little box that I’ll whittle
out, and present it—if you don’t mind—to young Wentworth. He may
perhaps value it as a souvenir of his visit to Quasi.”
Cal assented more than gladly, and the two busied themselves
during the next half hour completing their catch of whiting and
croakers for breakfast. When they reached the camp the rain Dunbar
had predicted had set in.
As soon as breakfast was over Dunbar redeemed his promise to
show the boys his lockers.
“I’m going over there now,” he said, “to get some paper, pencils
and drawing board. Suppose you go with me, if you want to see
some of my woodland devices.”
They assented gladly. They were very curious to see where and
how their guest cared for his perishable properties, the more
because their own search for the lockers had completely failed.
The matter proved simple enough. Dunbar led them a little way
into the woods and then, falling upon his knees, crawled into the
end of a huge hollow log. After he had reached the farther end of
the hollow part he lighted a little bunch of fat pine splinters to serve
as a torch, and invited his companions to look in. They saw that he
had scraped away all the decaying wood inside the log, leaving its
hard shell as a bare wall. In this he had fitted a number of little
wooden hooks, to each of which some of his belongings were
suspended.
It was a curious collection. There were cards covered with
butterflies, moths and beetles, each impaled upon a large pin. There
were the beaks and talons of various birds of prey, each carefully
labeled. There were bunches of feathers of various hues, some dried
botanical specimens and much else of similar sorts.
From the farther end of the hollow he brought forth several
compact little portfolios, each so arranged that no rain could
penetrate it when all were bound together and carried like a
knapsack.
“I’ll take two of these portfolios with me to your shelter,” he said,
taking them under his arm. “One of them contains the writing and
drawing materials that I shall need to-day. The other is filled with my
drawings of various interesting objects. Some of them may be
interesting to you during this rainy day, and each has a description
appended which will enable you to understand the meaning of it.”
But the boys had a rather brief time over the drawings that day.
They ran through a part of the portfolio while Dunbar was writing,
but after an hour he put his writing aside and began dissecting the
shark’s head, stopping now and then to make a little sketch of some
detail. After that the boys had no eyes but for the work he was
doing and no ears but for the things he said.
“You see there are comparatively few species of fish that have
any teeth at all. They have no need of teeth and therefore have
never developed them.”
“But why is that,” asked Tom; “I should think some of the
toothless varieties of fish would have developed teeth accidentally,
as it were.”
“Development is never accidental in that sense, Tom. It is
Nature’s uniform law that every species of living thing, animal or
vegetable, shall tend to develop whatever is useful to it, and nothing
else. That is Nature’s plan for the perpetuation of life and the
improvement of species.”
After pausing in close attention to some detail of his work,
Dunbar went on:
“You can see the same dominant principle at work in the varying
forms of teeth developed by different species. The sheepshead
needs teeth only for the purpose of crushing the shells of barnacles
and the like, and in that way getting at its food. So in a
sheepshead’s mouth you find none but crushing teeth. The shark, as
you see, has pointed teeth so arranged in rows that one row closes
down between two other rows in the opposite jaw, and by a
muscular arrangement the shark can work one jaw to right and left
with lightning-like rapidity, making the saw-like row of teeth cut
through almost anything after the manner of a reaping machine.
Then there is the pike. He has teeth altogether different from either
of the others. The pike swallows very large fish in proportion to his
own size, and his need is of teeth that will prevent his prey from
wriggling out of his mouth and escaping while he is slowly trying to
swallow it. Accordingly his teeth are as small and as sharp as
cambric needles. Moreover, he has them everywhere in his mouth—
on his lips, on his tongue, and even in his throat. However, this is no
time for a lecture. If you are interested in the subject you can study
it better by looking into fishes’ mouths than by listening to anybody
talk or by reading books on the subject.”
Again Dunbar paused in order that his attention might be closely
concentrated upon some delicate detail of his work.
When the strain upon his attention seemed at last to relax, Cal
ventured to say something—and it was startling to his comrades.
“Of course you’re right about the books on such subjects,” he
said. “For example, the most interesting of all facts about fish isn’t
so much as mentioned in any book I can find, though I’ve searched
through several libraries for it.”
“What is your fact?” asked Dunbar, suspending his work to listen.
“Why that fish do not die natural deaths. Not one of them in a
million ever does that.”
“But why do you think that, Cal? What proof is there—”
“Why, the thing’s obvious on its face. A dead fish floats, doesn’t
it? Well, in any good fishing water, such as the Adirondack lakes,
where I fished with my father one summer, there are millions of fish
—big and little—scores of millions, even hundreds of millions, if you
count shiners and the other minnows, that of a clear day lie in banks
from the bottom of the water to its surface. Now, if fish died natural
deaths in anything like the proportion that all other living things do,
the surface of such lakes would be constantly covered with dead
fish. Right here at Quasi and in all these coast waters the same thing
is true. Every creek mouth is full of fish and every shoal is alive with
them, so that we know in advance when we go fishing that we can
catch them as fast as we can take them off the hook. If any
reasonable rate of natural mortality prevailed among them every
flood tide would strew the shores with tons of dead fish. As nothing
of the kind happens, it seems to me certain that as a rule fish do not
die a natural death. In fact, most of them have no chance to do that,
as they spend pretty nearly their entire time in swallowing each
other alive.”
“You are a close observer, Cal. You ought to become a man of
science,” said Dunbar with enthusiasm. “Science needs men of your
kind.”
“Oh, I don’t know,” answered Cal. “I imagine Science can get on
very comfortably without any help of mine.”
“How did you come to notice all that, anyhow, Cal?” asked Dick.
“Oh, it didn’t take much to suggest that sort of thing, when the
facts were staring me in the face. Besides, I may be all wrong. What
do you think of my wild guess, Mr. Dunbar?”
“It isn’t a wild guess. Your conclusion may be right or wrong—I
must think of the subject carefully before I can form any opinion as
to that. But at any rate it is a conclusion reasoned out from a careful
observation of facts, and that is nothing like a wild guess.”
Thus the conversation drifted on throughout the long rainy day,
and when night came the boys were agreed that they had learned to
know Dunbar and appreciate him more than they could have done in
weeks of ordinary intercourse.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like