SlideShare a Scribd company logo
Developing Java Servlets 2nd Edition James
Goodwill download
https://ebookgate.com/product/developing-java-servlets-2nd-
edition-james-goodwill/
Get Instant Ebook Downloads – Browse at https://ebookgate.com
Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats
Apache Jakarta Tomcat 1st Edition James Goodwill
https://ebookgate.com/product/apache-jakarta-tomcat-1st-edition-
james-goodwill/
Murach s Java Servlets and JSP 3rd Edition Edition Joel
Murach
https://ebookgate.com/product/murach-s-java-servlets-and-jsp-3rd-
edition-edition-joel-murach/
Java 2 micro edition Java in small things James White
https://ebookgate.com/product/java-2-micro-edition-java-in-small-
things-james-white/
Developing a Dream Destination James Mak
https://ebookgate.com/product/developing-a-dream-destination-
james-mak/
The Java Language Specification Third Edition James
Gosling
https://ebookgate.com/product/the-java-language-specification-
third-edition-james-gosling/
Developing Applications with Java TM and UML 1st
Edition Paul R. Reed
https://ebookgate.com/product/developing-applications-with-java-
tm-and-uml-1st-edition-paul-r-reed/
Developing Web Services with Java APIs for XML 1st
Edition Robert Hablutzel
https://ebookgate.com/product/developing-web-services-with-java-
apis-for-xml-1st-edition-robert-hablutzel/
The Java Language Specification Java SE 8 Edition James
Gosling & Bill Joy & Guy L. Steele
https://ebookgate.com/product/the-java-language-specification-
java-se-8-edition-james-gosling-bill-joy-guy-l-steele/
Java 9 Modularity Patterns and Practices for Developing
Maintainable Applications 1st Edition Sander Mak
https://ebookgate.com/product/java-9-modularity-patterns-and-
practices-for-developing-maintainable-applications-1st-edition-
sander-mak/
Developing Java Servlets 2nd Edition James Goodwill
James Goodwill
800 East 96th St., Indianapolis, Indiana, 46240 USA
Developing Java™
Servlets
Developing Java™
Servlets,
Second Edition
Copyright © 2001 by Sams Publishing
All rights reserved. No part of this book shall be reproduced, stored in a
retrieval system, or transmitted by any means, electronic, mechanical, photo-
copying, recording, or otherwise, without written permission from the pub-
lisher. No patent liability is assumed with respect to the use of the information
contained herein. Although every precaution has been taken in the preparation
of this book, the publisher and author assume no responsibility for errors or
omissions. Nor is any liability assumed for damages resulting from the use of
the information contained herein.
International Standard Book Number: 0-672-32107-6
Library of Congress Catalog Card Number: 00-111799
Printed in the United States of America
First Printing: June 2001
04 03 02 01 4 3 2 1
Trademarks
All terms mentioned in this book that are known to be trademarks or service
marks have been appropriately capitalized. Sams Publishing cannot attest to
the accuracy of this information. Use of a term in this book should not be
regarded as affecting the validity of any trademark or service mark.
Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as
possible, but no warranty or fitness is implied. The information provided is on
an “as is” basis. The author and the publisher shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages aris-
ing from the information contained in this book.
PUBLISHER
Paul Boger
EXECUTIVE EDITOR
Michael Stephens
ACQUISITIONS EDITOR
Carol Ackerman
DEVELOPMENT EDITOR
Tiffany Taylor
MANAGING EDITOR
Matt Purcell
PROJECT EDITOR
Christina Smith
COPY EDITOR
Cynthia Fields
INDEXER
Erika Millen
PROOFREADER
Benjamin Berg
TECHNICAL EDITOR
Rob Tiffany
TEAM COORDINATOR
Lynne Williams
INTERIOR DESIGNER
Anne Jones
COVER DESIGNER
Aren Howell
PAGE LAYOUT
Ayanna Lacey
Heather Hiatt Miller
Stacey Richwine-DeRome
Overview
Contents at a Glance
Introduction 1
1 Web Applications and the Model View Controller (MVC) Design Pattern 7
PART I Servlet Fundamentals
2 Servlet Overview and Architecture 15
3 Servlet Basics 25
4 Servlets and HTML 33
5 Servlet Sessions 41
6 HTTP Tunneling 59
7 Servlets, JDBC, and Inter-Servlet Communications 85
8 Servlets and JavaMail 131
9 Servlet Security 143
10 Servlets and XML 151
11 Servlets and LDAP 163
12 Servlets and Enterprise JavaBeans 189
13 A Servlet Controller 225
PART II JSP Fundamentals
14 JSP Overview and Architecture 235
15 JSP Implicit Objects 247
16 JSP Standard Actions 261
17 Using JavaBeans and JSP Scopes 281
18 Handling JSP Errors 293
19 Custom JSP Tag Libraries 301
PART III Servlet and JSP Web Applications
20 Catalog Case Study 321
21 An LDAP Web Client 347
22 A Stock Trader 363
23 Wireless Application Development Using WAP 385
24 WML/WMLScript Development 397
PART IV Appendixes
A Web Applications and Configuring the Servlet Engine 419
B The javax.servlet Package 429
C The javax.servlet.http Package 461
D The javax.servlet.jsp Package 489
E The javax.servlet.jsp.tagext Package 513
F WML (The Wireless Markup Language) 543
G WMLScript 547
Index 559
Contents
Introduction 1
1 Web Applications and the Model View Controller (MVC)
Design Pattern 7
The Model View Controller (MVC) Design Pattern ..............................8
A Server-Side Implementation of the MVC............................................8
Servlets as MVC Controllers..............................................................9
JSPs as MVC Views ........................................................................10
Summary................................................................................................10
PART I Servlet Fundamentals
2 Servlet Overview and Architecture 15
Movement to Server-Side Java ..............................................................16
Definition of a Java Servlet ..................................................................16
Practical Applications for Java Servlets ................................................16
Java Servlet Alternatives........................................................................17
Common Gateway Interface ............................................................17
Proprietary APIs ..............................................................................18
Server-Side JavaScript......................................................................18
Microsoft’s Active Server Pages ......................................................18
Reasons to Use Java Servlets ................................................................19
Efficiency..........................................................................................19
Persistency........................................................................................19
Portability ........................................................................................19
Robustness........................................................................................19
Extensibility......................................................................................20
Security ............................................................................................20
The Java Servlet Architecture................................................................20
GenericServlet and HttpServlet........................................................20
Summary................................................................................................23
3 Servlet Basics 25
The Life Cycle of a Servlet ..................................................................26
The init() Method ............................................................................26
The service() Method ......................................................................26
The destroy() Method ......................................................................27
A Basic Servlet ......................................................................................27
The BasicServlet Source ..................................................................27
Dissecting the BasicServlet ..................................................................29
Where Does the BasicServlet Fit into the Servlet Framework? ......29
The Methods Overridden by the BasicServlet ................................30
Summary................................................................................................31
DEVELOPING JAVA SERVLETS, SECOND EDITION
vi
4 Servlets and HTML 33
Retrieving Form Data in a Servlet ........................................................34
Servicing the GET and POST Requests ..........................................34
How the FormServlet Works ............................................................38
Summary................................................................................................39
5 Servlet Sessions 41
What Is Session Tracking? ....................................................................42
Using Hidden Form Fields ....................................................................42
Working with Cookies ..........................................................................46
URL Rewriting ......................................................................................50
Session Tracking with the Servlet API..................................................51
Summary................................................................................................58
6 HTTP Tunneling 59
What Is HTTP Tunneling? ....................................................................60
Object Serialization................................................................................60
Creating an HTTP Tunneling Client......................................................66
Creating an HTTP Tunneling Servlet....................................................71
A Practical HTTP Tunneling Example..................................................73
The OrderStatusApplet ....................................................................74
The OrderStatusServlet ....................................................................80
Pros and Cons of Applet-to-Servlet Communication............................83
Summary................................................................................................84
7 Servlets, JDBC, and Inter-Servlet Communications 85
What is the JDBC? ................................................................................86
Two- and Three-Tier Database Access Models ....................................86
JDBC Driver Types................................................................................87
Type 1: JDBC-ODBC Bridge, Plus ODBC Driver ..........................88
Type 2: Native-API, Partly Java Driver............................................88
Type 3: JDBC-Net, Pure Java Driver ..............................................89
Type 4: Native-Protocol, Pure Java Driver ......................................90
JDBC Basics ........................................................................................92
Installing and Setting Up a Type 1 Driver ......................................92
Establishing a Database Connection ................................................93
Performing the Basic SQL Commands............................................94
A Basic JDBC Servlet ........................................................................107
A JDBC Connection Pool....................................................................112
Inter-Servlet Communications ............................................................123
Summary..............................................................................................130
CONTENTS
vii
8 Servlets and JavaMail 131
JavaMail and Internet E-mail ..............................................................132
JavaMail Services ..........................................................................132
Preparing to Use JavaMail ..................................................................133
A JavaMail Example............................................................................133
Using JavaMail in a Servlet ................................................................137
Summary..............................................................................................141
9 Servlet Security 143
Introduction to Security ......................................................................144
Roll Your Own ....................................................................................144
Basic Authentication............................................................................148
Digest Authentication ..........................................................................148
Secure Sockets Layer (SSL)................................................................149
Summary..............................................................................................150
10 Servlets and XML 151
XML and Java......................................................................................153
Using the SAX API ........................................................................153
Using XML in a Servlet ......................................................................159
Summary..............................................................................................162
11 Servlets and LDAP 163
A Brief Discussion of Directories ......................................................164
Attributes ........................................................................................165
Distinguished Names......................................................................165
LDAP ..................................................................................................165
JNDI ....................................................................................................166
Using JNDI to Access LDAP ..............................................................166
Installing Netscape Directory Server ............................................167
Connecting......................................................................................168
Searching the LDAP Server ..........................................................170
Adding an Object to an LDAP Server............................................174
Removing an Object ......................................................................176
Modifying Information Stored in LDAP........................................177
Accessing LDAP from a Servlet..........................................................184
Summary..............................................................................................188
12 Servlets and Enterprise JavaBeans 189
What Are Enterprise JavaBeans? ........................................................190
EJB Terminology ................................................................................191
Installing JRun ....................................................................................191
The Enterprise JavaBean......................................................................192
Interfaces and Classes ....................................................................192
Naming Conventions ......................................................................193
DEVELOPING JAVA SERVLETS, SECOND EDITION
viii
Session Beans ......................................................................................194
Stateless Versus Stateful ................................................................194
Session Bean Interfaces and Classes..............................................195
Deployment Descriptor ..................................................................200
Client View of a Session Bean ......................................................204
Session Bean Lifecycle ..................................................................205
Entity Beans ........................................................................................206
Who Handles the Persistence? ......................................................206
Entity Bean Interfaces and Classes ................................................207
Deployment Descriptor ..................................................................215
Client View of an Entity Bean........................................................217
Entity Bean Life Cycle ..................................................................217
Deploying Your EJB to Your Application Server ................................218
Packaging the jar File ....................................................................218
Deploying the jar File ....................................................................220
Viewing Deployed Beans ..............................................................220
Servlets as EJB Clients........................................................................220
Summary..............................................................................................224
13 A Servlet Controller 225
What Is a Controller? ..........................................................................226
A Servlet Controller ............................................................................226
The Service Interface ..........................................................................229
A Sample Service ................................................................................230
Summary..............................................................................................232
PART II JSP Fundamentals
14 JSP Overview and Architecture 235
What are JavaServer Pages? ................................................................236
The Components of a JavaServer Page ..............................................237
Directives........................................................................................238
Standard Actions ............................................................................240
Implicit Objects ..............................................................................241
JSP Scripting ..................................................................................242
Summary..............................................................................................246
15 JSP Implicit Objects 247
What are Implicit Objects?..................................................................248
The request Object ..............................................................................249
The response Object ............................................................................250
The pageContext Object ......................................................................251
The session Object ..............................................................................252
CONTENTS
The application Object ........................................................................254
Testing the JSPs..............................................................................256
The out Object ....................................................................................257
The config Object ................................................................................258
The page Object ..................................................................................260
The exception Object ..........................................................................260
Summary..............................................................................................260
16 JSP Standard Actions 261
What Are Standard Actions?................................................................262
JavaBean Standard Actions..................................................................262
The <jsp:useBean> Standard Action..............................................262
The <jsp:setProperty> Standard Action ........................................263
The <jsp:getProperty> Standard Action ........................................264
A JSP Example Using JavaBeans ..................................................264
Other Standard Actions........................................................................268
The <jsp:param> Standard Action ................................................268
The <jsp:include> Standard Action................................................269
The <jsp:forward> Standard Action ..............................................274
The <jsp:plugin> Standard Action ................................................278
Summary..............................................................................................279
17 Using JavaBeans and JSP Scopes 281
The Counter JavaBean ........................................................................282
page Scope ..........................................................................................283
request Scope ......................................................................................284
session Scope ......................................................................................286
application Scope ................................................................................289
Summary..............................................................................................291
18 Handling JSP Errors 293
JSP Translation-Time Errors................................................................294
JSP Request-Time Errors ....................................................................294
Creating a JSP Error Page..............................................................294
Using a JSP Error Page ..................................................................297
Summary..............................................................................................300
19 Custom JSP Tag Libraries 301
JSP Customs Tags................................................................................302
Deploying Tag Libraries ......................................................................302
Creating a Taglib Descriptor ..........................................................302
Deploying the Tag Handlers to Your Web Application ..................304
Adding a taglib Entry to Your Web Application ............................304
Adding the taglib Directive to Your JSP ........................................305
ix
DEVELOPING JAVA SERVLETS, SECOND EDITION
Developing Custom JSP Tags Handlers ..............................................306
Tags Without Bodies ......................................................................306
Tags with Bodies ............................................................................311
Tags with Attributes........................................................................314
Summary..............................................................................................317
PART III Servlet and JSP Web Applications
20 Catalog Case Study 321
Catalog Requirements..........................................................................322
Models..................................................................................................322
Shopping Cart ................................................................................325
Views....................................................................................................328
Catalog Layout ..............................................................................328
Index View......................................................................................332
Movie List View ............................................................................334
Shopping Cart View........................................................................335
Check Out View..............................................................................336
Controllers............................................................................................338
The ListMovies Service..................................................................338
The AddToCart Service..................................................................341
The EmptyCart Service ..................................................................343
The CheckOut Service....................................................................343
Using the Online Catalog ....................................................................344
Summary..............................................................................................345
21 An LDAP Web Client 347
Directory Requirements ......................................................................348
Models..................................................................................................348
Views....................................................................................................349
The Directory Layout ....................................................................349
Index View......................................................................................351
Directory View................................................................................352
Add View........................................................................................354
Controllers............................................................................................356
The LDAPDirectory Service ..........................................................356
The LDAPInsert Service ................................................................358
The LDAPDelete Service ..............................................................359
Using the LDAP Application ..............................................................360
Summary..............................................................................................361
22 A Stock Trader 363
Trader Requirements............................................................................364
Models..................................................................................................364
x
CONTENTS
Views....................................................................................................367
Trader Layout ................................................................................367
Index View......................................................................................370
Get Quote View ..............................................................................371
Buy/Sell View ................................................................................372
Controllers............................................................................................375
The GetQuote Service ....................................................................375
The Buy Service ............................................................................377
The Sell Service..............................................................................380
Using the Trader Application ..............................................................382
Summary..............................................................................................383
23 Wireless Application Development Using WAP 385
WAP History: Past, Present, and Future..............................................386
The Past: Handheld Device Markup Language (HDML)..............386
Present: WAP Hits the Street..........................................................387
The Future: WAP 1.2 and Beyond ................................................387
Why WAP? ..........................................................................................389
Screen Size Considerations ............................................................389
Network Considerations ................................................................390
Bandwidth Considerations..............................................................390
WAP Architecture ................................................................................391
Emulators, Browsers, and Developer Tools ........................................392
Online Emulators............................................................................392
WinWAP Browser ..........................................................................392
Emulators and Developer Tools ....................................................394
PDA WAP Browsers ......................................................................394
Application Servers ........................................................................395
Suggested Resources............................................................................395
Summary..............................................................................................396
24 WML/WMLScript Development 397
The Wireless Markup Language (WML) ............................................398
WML Language Basics..................................................................398
A WML Example ................................................................................401
WMLScript ..........................................................................................405
Calling WMLScript from WML ....................................................406
Language Basics ............................................................................406
Operators ........................................................................................407
Statements ......................................................................................407
The Standard Libraries ..................................................................408
WMLScript Example......................................................................409
xi
DEVELOPING JAVA SERVLETS, SECOND EDITION
Wireless Application Developing Using Servlets................................412
Configuring Server MIME Types ..................................................412
A Quick “Hello World!” WML Servlet ........................................413
Multiple Device Support ................................................................414
Maintaining a Site in XML ............................................................414
Summary..............................................................................................415
PART IV Appendixes
A Web Applications and Configuring the Servlet Engine 419
Web Applications ................................................................................420
The ServletContext in Relation to the Web Application................420
The Directory Structure..................................................................420
Web Application Deployment Descriptors ....................................421
Web Archive (WAR) Files ..................................................................422
Servlet Requirements ..........................................................................422
Apache Tomcat ....................................................................................422
Installing the Tomcat Server ..........................................................422
Adding the DJS Web Application ..................................................424
Building and Installing the BasicServlet........................................426
Summary..............................................................................................427
B The javax.servlet Package 429
The javax.servlet Interfaces ................................................................430
The RequestDispatcher Interface ..................................................431
The Servlet Interface ......................................................................432
The ServletConfig Interface ..........................................................433
The ServletContext Interface..........................................................434
The ServletRequest Interface ........................................................440
The ServletResponse Interface ......................................................445
The SingleThreadModel Interface..................................................448
Classes..................................................................................................448
The GenericServlet Class ..............................................................449
The ServletInputStream Class........................................................452
The ServletOutputStream Class ....................................................452
Exceptions............................................................................................456
The ServletException ....................................................................456
The UnavailableException ............................................................458
C The javax.servlet.http Package 461
Interfaces..............................................................................................462
The HttpServletRequest Interface ..................................................462
The HttpServletResponse Interface................................................468
The HttpSession Interface ..............................................................476
The HttpSessionBindingListener Interface ....................................479
xii
CONTENTS
Classes..................................................................................................479
The Cookie Class............................................................................479
The HttpServlet Class ....................................................................483
The HttpSessionBindingEvent Class..............................................486
The HttpUtils Class ........................................................................487
D The javax.servlet.jsp Package 489
Interfaces..............................................................................................490
The HttpJspPage Interface..............................................................490
The JspPage Interface ....................................................................491
Classes..................................................................................................492
The JspEngineInfo Class................................................................492
The JspFactory Class......................................................................492
The JspWriter Class........................................................................494
The PageContext Class ..................................................................502
Exceptions............................................................................................511
The JspError Exception..................................................................511
The JspException Exception ..........................................................512
E The javax.servlet.jsp.tagext Package 513
Interfaces..............................................................................................514
The Tag Interface............................................................................514
The BodyTag Interface ..................................................................520
Classes..................................................................................................522
The BodyContent Class..................................................................522
The BodyTagSupport Class............................................................523
The TagSupport Class ....................................................................525
The TagAttributeInfo Class ............................................................528
The TagData Class..........................................................................530
The TagExtraInfo Class..................................................................532
The TagInfo Class ..........................................................................533
The TagLibraryInfo Class ..............................................................537
The VariableInfo Class ..................................................................539
F WML (The Wireless Markup Language) 543
WML Elements....................................................................................544
G WMLScript 547
Lang Library ........................................................................................548
abort()—The abort Function ..........................................................548
abs()—The abs Function ................................................................548
characterSet()—The characterSet Function ..................................548
exit()—The exit Function ..............................................................548
float()—The float Function ............................................................548
xiii
DEVELOPING JAVA SERVLETS, SECOND EDITION
isFloat()—The isFloat Function ....................................................549
isInt()—The isInt Function ............................................................549
max()—The max Function ............................................................549
maxInt()—The maxInt Function ....................................................549
min()—The min Function ..............................................................549
minInt()—The minInt Function......................................................549
parseFloat()—The parseFloat Function..........................................549
parseInt()—The parseInt Function ................................................549
random()—The random Function ..................................................550
seed()—The seed Function ............................................................550
Float Library ........................................................................................550
ceil()—The ceil Function ..............................................................550
floor()—The floor Function ..........................................................550
int()—The int Function ..................................................................550
maxFloat()—The maxFloat Function ............................................550
minFloat()—The minFloat Function..............................................551
pow()—The pow Function ............................................................551
round()—The round function ........................................................551
sqrt()—The sqrt Function ..............................................................551
String Library ......................................................................................551
charAt()—The charAt Function ....................................................551
compare()—The compare Function ..............................................551
elementAt()—The elementAt Function..........................................551
elements()—The elements Function ..............................................552
find()—The find Function ..............................................................552
format()—The format Function......................................................552
insertAt()—The insertAt Function ................................................552
isEmpty()—The isEmpty Function ................................................552
length()—The length Function ......................................................552
removeAt()—The removeAt Function ..........................................552
replace()—The replace Function....................................................553
replaceAt()—The replaceAt Function............................................553
squeeze()—The squeeze Function..................................................553
subString()—The subString Function ............................................553
toString()—The toString Function ................................................553
trim()—The trim Function..............................................................553
URL Library ........................................................................................553
escapeString()—The escapeString Function..................................554
getBase()—The getBase Function..................................................554
getFragment()—The getFragment Function ..................................554
getHost()—The getHost Function..................................................554
getParameters()—The getParameters Function..............................554
xiv
CONTENTS
getPath()—The getPath Function ..................................................554
getPort()—The getPort Function....................................................555
getQuery()—The getQuery Function ............................................555
getReferer()—The getReferer Function ........................................555
getScheme()—The getScheme Function........................................555
isValid()—The isValid Function ....................................................555
loadString()—The loadString Function..........................................555
resolve()—The resolve Function....................................................555
unescapeString()—The unescapeString Function..........................555
WMLBrowser Library ........................................................................556
getCurrentCard()—The getCurrentCard Function ........................556
getVar()—The getVar Function......................................................556
go()—The go Function ..................................................................556
newContext()—The newContext Function ....................................556
prev()—The prev Function ............................................................556
refresh()—The refresh Function ....................................................556
setVar()—The setVar Function ......................................................556
Dialogs Library....................................................................................557
alert()—The alert Function ............................................................557
confirm()—The confirm Function..................................................557
prompt()—The prompt Function....................................................557
Index 559
xv
About the Authors
Lead Author
James Goodwill is the co-founder and chief architect at Virtuas Solutions, LLC., located in
Denver, Colorado. He has extensive experience in designing and architecting e-business appli-
cations. James is also the author of Pure JavaServer Pages, which provides a thorough exami-
nation of the JavaServer Pages technology. James is currently leading Virtuas’s efforts in
developing cutting edge tools designed for J2EE e-business acceleration.
You can find the source code and support for this text at the Virtuas Solutions Web site,
http://www.virtuas.com. Select the Publications link.
Contributing Author
Bryan Morgan is an experienced writer and software developer and founder of the Wireless
Developer Network (http://www.wirelessdevnet.com) in 1999. He is a respected voice in the
wireless industry, is a regular contributor to industry publications, and has been a featured
speaker at numerous events. He holds a B.S. in electrical engineering from Clemson University
and lives in Pensacola, FL with his wife Becky and beautiful daughter Emma.
Dedication
To my girls Christy, Abby, and Emma.
Acknowledgments
Before I start thanking those close to home, I need to thank the people who made this book
what it is. They are the people who took my words and molded and shaped them into some-
thing that I hope will help you become an effective Web application developer. I would like to
thank Carol Ackerman, my acquisitions editor, who answered all my questions and resolved
any issues that came up. I would especially like to thank Tiffany Taylor for her excellent edit-
ing. I would like to thank Rob Tiffany for his great technical comments and recommendations.
I would also like to thank Cynthia Fields for her excellent copy-editing. And finally, I would
like to thank Christina Smith for managing the entire project. Each and every person made this
book what it is.
On a closer note, I would first like to thank everyone at my company, Virtuas Solutions, Inc.
for their support while I was completing this text. The entire staff contributed by picking up
my assignments when my plate was too full. In particular I would like to thank those
“UNREAL” people that I worked with on a daily basis including Matthew “Deckard” Filios,
Karen “Blue Bullet” Jackson, Eric “Crazy Mary” Johnson, Jason “Cutt” Nordyke, David
“Busta” Goedecke, Mike “Ivan” Day, Gary “Monica” Goodrum, and especially Aaron “Ronin”
Bandell, for his contribution of Chapters 11 and 12.
Finally, the most important contributors to this book are my wife Christy, and our daughters
Abby and Emma. They supported me throughout the entire book, with complete understand-
ing. They listened to me complain and took care of things when I disappeared into the office.
With their support, I can do anything.
Tell Us What You Think!
As the reader of this book, you are our most important critic and commentator. We value your
opinion and want to know what we’re doing right, what we could do better, what areas you’d
like to see us publish in, and any other words of wisdom you’re willing to pass our way.
As an executive editor for Sams Publishing, I welcome your comments. You can fax, e-mail, or
write me directly to let me know what you did or didn’t like about this book—as well as what
we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this book,
and that due to the high volume of mail I receive, I might not be able to reply to every
message.
When you write, please be sure to include this book’s title and author’s name as well as your
name and phone or fax number. I will carefully review your comments and share them with the
author and editors who worked on the book.
Fax: 317-581-4770
E-mail: feedback@samspublishing.com
Mail: Michael Stephens
Executive Editor
Sams Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA
Introduction
Structure of This Book
Before you begin reading this book, you might want to take a look at its basic structure. This
will help you outline your reading plan, if you choose not to read it from cover to cover. This
introduction gives you an overview of what each chapter covers.
Chapter 1, “Web Applications and the Model View
Controller (MVC) Design Pattern”
Chapter 1 lays the foundation for the entire text. It introduces your to the Model View
Controller design pattern. It also introduces you to a server-side implementation of the MVC
and how both servlets and JSPs fit into this pattern
Chapter 2, “Servlet Overview and Architecture”
Chapter 2 introduces you to the Java servlet architecture. It talks about the movement to
server-side Java. It also details reasons why you should use Java servlets.
Chapter 3, “Servlet Basics”
Chapter 3 is where you begin to actually examine servlets. This chapter details the life cycle of
a servlet and shows you source code for a basic servlet.
Chapter 4, “Servlets and HTML”
Chapter 4 shows you how to link HTML forms to Java servlets and how you should retrieve
form data in a servlet.
Chapter 5, “Servlet Sessions”
Chapter 5 discusses several ways that you can maintain state while using servlets. The methods
that it discusses include hidden form fields, cookies, URL rewriting, and session tracking with
the Servlet API.
Chapter 6, “HTTP Tunneling”
Chapter 6 covers HTTP tunneling. It provides a definition of HTTP tunneling, describes object
serialization (which is required in tunneling), it describes the creation of a tunneling client and
server, and it gives a practical tunneling example. It also covers some of the pros and cons of
applet to servlet communications.
DEVELOPING JAVA SERVLETS
Chapter 7, “Servlets, JDBC, and Inter-Servlet
Communications”
Chapter 7 discusses how servlets can use the JDBC to interact with relational databases. It
gives a basic introduction to the JDBC and then combines the technology with servlets. It also
discusses a technique used to communicate between servlets.
Chapter 8, “Servlets and JavaMail”
Chapter 8 discusses JavaMail and how you to use it with servlets and other applications.
Chapter 9, “Servlet Security”
Chapter 9 describes security issues that you face when deploying an application to the Internet.
It covers the most popular security techniques. It also describes some of each technique’s pros
and cons.
Chapter 10, “Servlets and XML”
Chapter 10 covers the basics of Extensible Markup Language, or XML. It discusses how to use
Sun’s SAX parser. It also shows an example of how you would incorporate XML and servlets.
Chapter 11, “Servlets and LDAP”
Chapter 11 covers the Lightweight Directory Access Protocol (LDAP). It covers using JNDI to
access LDAP servers and it closes with an LDAP example integrated into a servlet.
Chapter 12, “Servlets and Enterprise JavaBeans”
Chapter 12 provides an introduction to Enterprise JavaBeans (EJB). It covers using EJBs from
an application as well as integrated into a servlet.
Chapter 13, “A Servlet Controller”
Chapter 13 shows you how to create a servlet class that acts as the Controller in the Model
View Controller design pattern.
Chapter 14, “JSP Overview and Architecture”
Chapter 14 takes a look at the basics of JSP and the components of JSPs. It shows you how to
create a JSP document and understand what is happening behind the scenes at request time. It
also discusses the process a JSP file goes through when it is first requested.
2
INTRODUCTION
Chapter 15, “JSP Implicit Objects”
Chapter 15 discusses the JSP implicit objects and how they are commonly used. It also talks
about how they are created in the JSP’s generated servlet.
Chapter 16, “Using JSP Standard Actions”
Chapter 16 covers the JSP standard actions, including how they are implemented and how you
can use them.
Chapter 17, “Using JavaBeans and JSP Scopes”
Chapter 17 covers how JSP beans are scoped. It discusses the different types of JSP scope. It
also covers how the life of a JSP bean is determined by its scope.
Chapter 18, “Handling JSP Errors”
Chapter 18 covers the types of errors that can occur in a JSP. It shows you how to handle and
respond to these errors using a JSP error page.
Chapter 19, “Custom JSP Tag Libraries”
Chapter 19 covers custom JSP tag libraries including tags with and without bodies. It also dis-
cusses how tags are packaged and deployed.
Chapter 20, “Catalog Case Study”
Chapter 20 provides an MVC case study using an online movie catalog as an example includ-
ing requirements, MVC components, and how to use the finished catalog.
Chapter 21, “An LDAP Web Client”
Chapter 21 provides an MVC case study using a LDAP client as an example including require-
ments, MVC components, and how to use the finished client.
Chapter 22, “A Stock Trader”
Chapter 22 provides an MVC case study using a stock trading application as an example
including requirements, MVC components, and how to use the finished application.
3
DEVELOPING JAVA SERVLETS
Chapter 23, “Wireless Application Development Using
WAP”
Chapter 23 introduces you to wireless application development using Java servlets and the
Wireless Application Protocol (WAP), including the wide variety of client and server tools
available to the WAP developer. It includes an example in which you create a dynamic wireless
application using servlets and WAP.
Chapter 24, “WML/WMLScript Development”
Chapter 24 illustrates how to develop dynamic wireless Web applications using Java servlets,
WML, and WMLScript.
Appendix A, “Web Applications and Configuring the
Servlet Engine”
Appendix A covers the steps involved in retrieving and configuring the Tomcat server neces-
sary to run the examples in this text.
Appendix B, “The javax.servlet Package”
Appendix B covers the classes, interfaces, and exceptions of the javax.servlet package.
Appendix C, “The javax.servlet.http Package”
Appendix C covers the classes, interfaces, and exceptions of the javax.servlet.http pack-
age.
Appendix D, “The javax.servlet.jsp Package”
Appendix D covers the classes, interfaces, and exceptions of the javax.servlet.jsp package.
Appendix E, “The javax.servlet.jsp.tagext
Package”
Appendix E covers the classes, interfaces, and exceptions of the javax.servlet.jsp.tagext
package.
Appendix F, “WML (The Wireless Markup Language)”
Appendix F provides a tag references for WML.
4
INTRODUCTION
Appendix G, “WMLScript”
Appendix G describes the libraries and functions used in WMLScript.
5
Developing Java Servlets 2nd Edition James Goodwill
CHAPTER
1
Web Applications and the
Model View Controller (MVC)
Design Pattern
IN THIS CHAPTER
• The Model View Controller (MVC) Design
Pattern 8
• A Server-Side Implementation of the MVC 8
This chapter is the foundation for this entire text. We will look at a design pattern that lever-
ages the strengths of both servlets and Java Server Pages (JSPs) to create maintainable and
reusable Web applications: the Model View Controller (MVC). In this study we will also look
at exactly where and why both servlets and JSPs fit in this pattern. Because you have not yet
covered servlet and JSP technologies, you will have to accept some of the statements made in
this chapter. My goal for the remainder of this text is to show how and why this pattern and
these technologies work so well when developing server-side Java Web applications.
The Model View Controller (MVC) Design Pattern
The MVC originated from Smalltalk and was used to design user interfaces. In such an inter-
face, the application was made up of three classes: a Model, a View, and a Controller. Each of
these classes is defined in Table 1.1.
TABLE 1.1 The Classes of the MVC
Class Definition
Model The Model represents the data or application object. It is what is
being manipulated and presented to the user.
View The View is the screen representation of the Model. It is the object
that presents the current state of the Model.
Controller The Controller defines the way the user interface reacts to the user’s
input. The Controller is the object that manipulates the Model.
The major advantage of using the MVC design pattern is that it separates the Views and
Models. As a result, you can separate presentation from business logic, and, in turn, create or
change Views without having to change the Models or the Controller logic that manipulates the
Models. The MVC also allows Models to be represented by multiple Views.
A Server-Side Implementation of the MVC
To implement the MVC server-side pattern in Java we must combine JSPs and servlets. In this
section, we define a high-level server-side implementation of the MVC, where the Model is a
JavaBean that represents the data being transmitted or received. The Controller is a servlet that
manipulates or transmits data, and the View is a JSP that presents the results of the performed
transaction. Figure 1.1 models the steps involved in a sever-side implementation of the MVC.
DEVELOPING JAVA SERVLETS
8
FIGURE 1.1
The steps in a server-side implementation of the MVC.
These steps are as follows:
1. The Web Client makes a request to the Web Server.
2. The Web Server passes the request to the Controller Servlet.
3. The servlet performs necessary manipulations to the JavaBean/EJB Model.
4. The Controller Servlet forwards the results to the JSP View.
5. The JSP View formats the Model for display and sends the HTML results back to the
Web Server.
6. The Web Server then conveys the information back to the Web Client.
Some benefits of using a server-side implementation of the MVC include
• A clear separation of the presentation and transaction layers, which gives you the ability
to change the look and feel of an application without recompiling.
• The ability to have multiple views for multiple clients.
• The ability to have a less experienced programmer develop and maintain the user inter-
face.
• A quicker time-to-market by allowing the Controller programmers to focus only on
transactions, whereas the View programmers can focus primarily on presentation.
Servlets as MVC Controllers
We have chosen to use servlets as MVC Controllers after examining some of their strengths
and weaknesses.
Web Applications and the Model View Controller (MVC) Design Pattern
CHAPTER 1
1
W
EB
A
PPLICATIONS
AND
THE
MVC
D
ESIGN
P
ATTERN
9
Web Client Web
Server
Servlet
(Controller)
JSP
(View)
DBMS
EJB/
BEAN
EJB/
BEAN
EJB/
BEAN
EJB/
BEAN
1.
6.
2.
5.
4.
3.
Application Server
Strengths of servlets as Controllers are as follows:
• Servlets have very robust server-side processing capabilities because they have access to
almost the entire Java SDK.
• The servlet architecture lends itself well to a transactional style of programming, which
is analogous to MVC Controllers.
Weaknesses of servlets as Controllers are as follows:
• Servlets require an advanced level of Java understanding that HTML programmers usu-
ally do not have.
• Servlets generally require recompilation in order to change the client presentation layer.
If we consider the previous lists, we can determine that servlets make prime candidates for
MVC Controllers, where there will be fewer changes because the presentation logic has been
abstracted.
JSPs as MVC Views
JavaServer Pages were chosen as MVC Views after a similar examination of their strengths and
weaknesses.
Strengths of JSPs as Views are as follows:
• JSPs do not require programmer recompilation after source changes.
• JSPs allow you to access Java objects that are stored in the HTTP session.
• JSPs allow you to embed Java code directly into HTML pages with scriptlets.
Weaknesses of JSPs as Views are as follows:
• As your JSP code becomes more complicated, so does your scriptlet code. This results in
confusing and difficult-to-maintain JSPs.
• If you plan to allow your HTML programmers to maintain your JSPs, which is very
common, they will require a good understanding of Java.
After examining the previous lists, we can determine that JSPs make great candidates for MVC
Views. This is because we can leverage a JSP’s access to Java objects, while conquering one of
their major weaknesses by limiting scriptlet code to presentation only.
Summary
In this chapter, we laid the foundation for the rest of this text. We looked at the MVC design
pattern and saw how we could combine servlets and JSPs to implement a server-side solution
for Web applications.
DEVELOPING JAVA SERVLETS
10
In the rest of this text we will study servlets and JSPs in the context of this model. We will
examine how servlets and JSPs work separately and then we will complete the text by combin-
ing what we have learned into Web application case studies that implement the MVC.
Web Applications and the Model View Controller (MVC) Design Pattern
CHAPTER 1
1
W
EB
A
PPLICATIONS
AND
THE
MVC
D
ESIGN
P
ATTERN
11
Developing Java Servlets 2nd Edition James Goodwill
IN THIS PART
2 Servlet Overview and Architecture
3 Servlet Basics
4 Servlets and HTML
5 Servlet Sessions
6 HTTP Tunneling
7 Servlets, JDBC, and Inter-Servlet Communications
8 Servlets and JavaMail
9 Servlet Security
10 Servlets and XML
11 Servlets and LDAP
12 Servlets and Enterprise JavaBeans
13 A Servlet Controller
Servlet Fundamentals
PART
I
Developing Java Servlets 2nd Edition James Goodwill
CHAPTER
2
Servlet Overview and
Architecture
IN THIS CHAPTER
• Movement to Server-Side Java 16
• Definition of a Java Servlet 16
• Practical Applications for Java Servlets 16
• Java Servlet Alternatives 17
• Reasons to Use Java Servlets 19
• The Java Servlet Architecture 20
Movement to Server-Side Java
When the Java language was first introduced by Sun Microsystems Inc., its purpose was to
embed greater interactivity into Web pages. Java has accomplished this through the use of
applets. Applets add functionality to Web pages, but because of compatibility and bandwidth
issues, businesses have started moving to server-side Java.
Java applets are programs that are embedded directly into Web pages. When a browser loads a
Web page, which contains a reference to an applet, the applet byte-code is downloaded to the
client computer and executed by the browser. This is fine for very thin clients, but as applets
grow in size the download times become unacceptable. Applets also have compatibility prob-
lems. To run an applet you must have a compatible browser. If your customer does not have a
compatible browser, applets will not be presented with the proper content. These issues have
forced businesses to take a look at server-side Java.
Server-side Java solves the problems that applets face. When the code is being executed on the
server side, no issues arise with browser compatibility or long download times. The Java appli-
cation on the server only sends the client small packets of information, including HTML,
WML, XML, and so on, that it can understand. Java servlets are one of the options for server-
side Java development.
Definition of a Java Servlet
Servlets are generic extensions to Java-enabled servers. Their most common use is to extend
Web servers, providing a very secure, portable, and easy-to-use replacement for CGI. A servlet
is a dynamically loaded module that services requests from a Web server. It runs entirely inside
the Java Virtual Machine. Because the servlet is running on the server side, it does not depend
on browser compatibility. Figure 2.1 graphically depicts the execution of a Java servlet.
Servlet Fundamentals
PART I
16
Web Browser
Web Server
Servlet
Request
Response
FIGURE 2.1
Execution of a Java Servlet.
Practical Applications for Java Servlets
Servlets can be used for any number of Web-related applications. After you start using servlets,
you will find more practical applications for them. The following are three examples that I
believe are some of the most important:
• Developing e-commerce “store fronts” will become one of the most common uses for
Java servlets. A servlet can build an online catalog based on the contents of a database. It
can then present this catalog to the customer using dynamic HTML. The customer will
choose the items to be ordered, enter the shipping and billing information, and then sub-
mit the data to a servlet. When the servlet receives the posted data, it will process the
orders and place them in the database for fulfillment. Every one of these processes can
easily be implemented using Java servlets.
• Servlets can be used to deploy Web sites that open up large legacy systems on the
Internet. Many companies have massive amounts of data stored on large mainframe sys-
tems. These businesses do not want to re-architect their systems, so they choose to pro-
vide inexpensive Web interfaces into them. Because you have the entire JDK at your
disposal and security provided by the Web server, you can use servlets to interface into
these systems using anything from TCP/IP to CORBA.
• Servlets also make very good HTTP-enabled clients to Enterprise Java Bean (EJB) appli-
cations. Using servlets as clients to EJB applications creates very secure Web applica-
tions that are able to handle very high volumes.
These are just a few examples of the power and practicality of using Java servlets. Servlets are
very viable options for most Web applications.
Java Servlet Alternatives
Some alternatives to using Java servlets are CGI, proprietary server APIs, server-side
JavaScript, or even Microsoft’s Active Server Pages. All these are viable solutions, but they
each have their own set of problems. The following sections examine some of these issues.
Common Gateway Interface
The Common Gateway Interface (CGI) is one of the most common server-side solutions used to
develop Web applications. A CGI application is an independent module that receives requests
from a Web server. The application processes the data it receives and sends it back to the server,
typically as HTML. The server then sends the data to the browser. CGI has become a standard
that is used by most of today’s Web servers. Figure 2.2 shows the interaction between the
browser, Web server, and CGI application when you implement this type of solution.
Although CGI is a widely used solution to dynamic Web development, it is also a very prob-
lematic solution. The following are some of the most common problems with CGI:
• A Web server creates a new process every time it receives a CGI request. This results in
a slower response time, because the server must create and initialize a new address space
for every process. You can also face the problem of running out of processes. Most
Servlet Overview and Architecture
CHAPTER 2
2
S
ERVLET
O
VERVIEW
AND
A
RCHITECTURE
17
servers are configured to run a limited number of processes. If the server runs out, it will
not be able to handle the client’s requests.
• Although CGI code can be implemented in almost any language, the most common plat-
form-independent language is Perl. Perl is very powerful at processing text, but it
requires the server to start a new interpreter for every request. This takes longer than
starting compiled code and still eats up available processes and resources.
• CGI runs in a completely separate process from the Web server. If a client submits a
request to a CGI program that terminates before responding to the Web server, the
browser has no way of knowing what happened. It just sits there waiting for a response
until it times out.
Servlet Fundamentals
PART I
18
Web Server
New CGI1 Process
Client
Request CGI1
New CGI1 Process
Client
Request CGI1
New CGI1 Process
Client
Request CGI1
FIGURE 2.2
The interaction of a CGI solution.
Proprietary APIs
Many Web servers include APIs that extend their functionality. The most common examples
include Netscape’s NSAPI, Microsoft’s ISAPI, and O’Reilly’s Web site API called WSAPI.
The problem with these solutions is that they are proprietary. You cannot decide to change
servers without porting your code. These APIs are also developed using languages such as C or
C++ that can contain memory leaks or core dumps that can crash the Web server.
Server-Side JavaScript
Server-side JavaScript is another solution for implementing dynamic Web sites. With this solu-
tion you embed JavaScript into precompiled HTML pages. By precompiling the Web pages
you improve performance, but the only servers that implement server-side JavaScript are
Netscape’s Enterprise, FastTrack Servers, and Microsoft’s IIS. This again ties you to a particu-
lar vendor.
Microsoft’s Active Server Pages
Microsoft has developed its own solution to the problem of dynamic Web content: Active
Server Pages (ASP). Like Server-side JavaScript, ASP is embedded into HTML pages, but it is
also similar to server-side JavaScript in that it is tied to a particular Web server: Microsoft’s
Internet Information Server. Some third-party products implement ASP, but you must purchase
them separately at additional costs.
Reasons to Use Java Servlets
Java servlets are one of the most exciting new technologies I have had the opportunity to work
with. Servlets are efficient, persistent, portable, robust, extensible, secure, and they are receiv-
ing widespread acceptance. If you use them only to replace CGI, you will have saved yourself
a lot of time and headache. Servlets solve many common problems you run into when using
CGI, and they prove to have a clear advantage over many of the other alternatives. The follow-
ing sections discuss some of the advantages offered by servlets.
Efficiency
A servlet’s initialization code is executed only the first time the Web server loads it. Once the
servlet is loaded, it is only a matter of calling a service method to handle new requests. This is
a much more efficient technique than loading a completely new executable with every request.
Persistency
Servlets can maintain state between requests. Once a servlet is loaded, it stays resident in
memory while serving incoming requests. A simple example of this is a Vector that holds a list
of categories used in an online catalog. When the servlet is initialized, it queries the database
for a list of categories and stores these categories in a Vector. As it services requests, the
servlet accesses the Vector that holds the categories instead of querying the database again.
Taking advantage of the persistent characteristics of servlets can improve your application’s
performance drastically.
Portability
Servlets are developed using Java; therefore, they are portable. This portability enables servlets
to be moved to a new operating system without changing the source. You can take code that
was compiled on a Windows NT platform and move it to a Solaris box without making any
changes.
Robustness
Because servlets are developed with access to the entire JDK, they are very powerful and
robust solutions. Java provides a well-defined exception hierarchy for error handling. It has a
garbage collector to prevent problems with memory leaks. In addition, it includes a very large
class library that includes network support, file support, database access, distributed object
components, security, and many other classes.
Servlet Overview and Architecture
CHAPTER 2
2
S
ERVLET
O
VERVIEW
AND
A
RCHITECTURE
19
Extensibility
Another advantage servlets gain by being developed in an object-oriented language such as
Java is that they can be extended and polymorphed into new objects that better suit your needs.
A good example of this is an online catalog. You might want to display the same catalog search
tool at the top of every dynamic page throughout your Web site. You definitely don’t want to
add this code to every one of your servlets. So, you implement a base servlet that builds and
initializes the search tool and then extend it to display transaction-specific responses.
Security
Servlets run on the server side, inheriting the security provided by the Web server. Servlets can
also take advantage of the Java Security Manager.
The Java Servlet Architecture
Two packages make up the servlet architecture: javax.servlet and javax.servlet.http. The
javax.servlet package contains the generic interfaces and classes that are implemented and
extended by all servlets. The java.servlet.http package contains the classes that are
extended when creating HTTP-specific servlets. An example of this is a simple servlet that
responds using HTML.
At the heart of this architecture is the interface javax.servlet.Servlet. It provides the frame-
work for all servlets. The Servlet interface defines five methods. The three most important are
the init() method, which initializes a servlet; the service() method, which receives and
responds to client requests; and the destroy() method, which performs cleanup. All servlets
must implement this interface, either directly or through inheritance. It is a very clean object-
oriented approach that makes the interface easy to extend. Figure 2.3 shows an object model
that gives a high-level view of the servlet framework.
GenericServlet and HttpServlet
The two main classes are the GenericServlet and HttpServlet classes. The HttpServlet
class is extended from GenericServlet. When you are developing your own servlets, you will
most likely be extending one of these two classes. Java servlets do not have a main() method,
which is why all servlets must implement the javax.servlet.Servlet interface. Every time a
server receives a request that points to a servlet it calls that servlet’s service() method.
If you decide to extend the GenericServlet class, you must implement the service() method.
The GenericServlet.service() method has been defined as an abstract method to force you
to follow this framework. The service() method prototype is defined as follows:
public abstract void service(ServletRequest req,
ServletResponse res) throws ServletException, IOException;s
Servlet Fundamentals
PART I
20
FIGURE 2.3
A high-level object model of the servlet framework.
The two objects that the service() method receives are ServletRequest and
ServletResponse. The ServletRequest object holds the information that is being sent to the
servlet, whereas the ServletResponse object is where you place the data you want to send
back to the client. Figure 2.4 diagrams the flow of a GenericServlet request.
Servlet Overview and Architecture
CHAPTER 2
2
S
ERVLET
O
VERVIEW
AND
A
RCHITECTURE
21
<<Interface>>
javax.servlet.Servlet
init()
getServletConfig()
service()
getServletInfo()
destroy()
<<Interface>>
java.io.Serializable
<<Interface>>
javax.servlet.ServletConfig
getInitParameter()
getServletContext()
getInitParameterNames()
getServletName()
javax.servlet.GenericServlet
getServletContext()
getInitParameter()
getInitParameterNames()
log()
getServletInfo()
init()
getServletConfig()
service()
destroy()
getServletName()
javax.servlet.http.HttpServlet
doDelete()
doGet()
doOptions()
doPost()
doPut()
doTrace()
getLastModified()
service()
BasicServlet
FIGURE 2.4
A GenericServlet Request.
Unlike the GenericServlet, when you extend HttpServlet, you don’t usually implement the
service() method. The HttpServlet class has already implemented it for you. The following
is the prototype:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException;
When the HttpServlet.service() method is invoked, it reads the method type stored in the
request and determines which method to invoke based on this value. These are the methods
that you will want to override. If the method type is GET, the service() method will call
doGet(). If the method type is POST, it will call doPost(). Five other method types exist; they
are discussed in Chapter 3, “Servlet Basics.” All these methods have the same parameter list as
the service() method.
You might have noticed the different request/response types in the parameter list of the
HttpServlet and the GenericServlet classes. The HttpServletRequest and
HttpServletResponse classes are just extensions of ServletRequest and ServletResponse
with HTTP-specific information stored in them. Figure 2.5 diagrams the flow of a
HttpServlet request.
Servlet Fundamentals
PART I
22
Web Server
Client
Request
Response
GenericServlet
service()*
* abstract method
Web Server
Client
Request
Response
doDelete()
doGet()
doOptions()
doPost()
doPut()
doTrace()
service()
HttpServlet
FIGURE 2.5
A HttpServlet Request.
Summary
In this chapter, you learned about Java servlet basics, practical applications for servlets, servlet
alternatives, reasons to use servlets over the alternatives, and the basic architecture of servlets.
At this point, you should have a high-level understanding of the flow of a servlet request and
what objects are involved.
In the next chapter we will look at the life cycle of a servlet. We will also create and dissect a
basic servlet.
Servlet Overview and Architecture
CHAPTER 2
2
S
ERVLET
O
VERVIEW
AND
A
RCHITECTURE
23
Developing Java Servlets 2nd Edition James Goodwill
CHAPTER
3
Servlet Basics
IN THIS CHAPTER
• The Life Cycle of a Servlet 26
• A Basic Servlet 27
• Dissecting the BasicServlet 29
The Life Cycle of a Servlet
The life cycle of a Java servlet is a very simple object-oriented design. A servlet is constructed
and initialized. It then services zero or more requests until the service that it extends shuts
down. At this point the servlet is destroyed and garbage is collected. This design explains why
servlets are such a good replacement for CGI: The servlet is loaded only once and it stays resi-
dent in memory while servicing requests.
The javax.servlet.Servlet interface declares this framework. The Servlet interface defines
the life cycle methods. These methods are the init(), the service(), and the destroy()
methods.
The init() Method
The init() method is where the servlet’s life begins. It is called by the server immediately
after the servlet is instantiated. It is called only once. In the init() method the servlet creates
and initializes the resources that it will be using while handling requests. The init() method’s
signature is defined as follows:
public void init(ServletConfig config) throws ServletException;
The init() method takes a ServletConfig object as a parameter. You should save this object
so that it can be referenced later. The most common way of doing this is to have the init()
method call super.init() passing it the ServletConfig object.
You will also notice that the init() method can throw a ServletException. If, for some rea-
son, the servlet cannot initialize the resources necessary to handle requests, the init() method
should throw a ServletException.
The service() Method
The service() method handles all requests sent by a client. It cannot start servicing requests
until the init() method has been executed. You will not usually implement this method
directly, unless you extend the GenericServlet abstract class.
The most common implementation of the service() method is in the HttpServlet class.
The HttpServlet class implements the Servlet interface by extending GenericServlet. Its
service() method supports standard HTTP/1.1 requests by determining the request type and
calling the appropriate method. The signature of the service() method is shown below.
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
Servlet Fundamentals
PART I
26
Other documents randomly have
different content
1027—The Finger of Suspicion
1028—The Crimson Clew
1029—Nick Carter Down East
1030—The Chain of Clews
1031—A Victim of Circumstances
1032—Brought to Bay
1033—The Dynamite Trap
1034—A Scrap of Black Lace
1035—The Woman of Evil
1036—A Legacy of Hate
1037—A Trusted Rogue
1038—Man Against Man
1039—The Demons of the Night
1040—The Brotherhood of Death
1041—At the Knife’s Point
1042—A Cry for Help
1043—A Stroke of Policy
1044—Hounded to Death
1045—A Bargain in Crime
1046—The Fatal Prescription
1047—The Man of Iron
1048—An Amazing Scoundrel
1049—The Chain of Evidence
1050—Paid with Death
1051—A Fight for a Throne
1052—The Woman of Steel
1053—The Seal of Death
1054—The Human Fiend
1055—A Desperate Chance
1056—A Chase in the Dark
1057—The Snare and the Game
1058—The Murray Hill Mystery
1059—Nick Carter’s Close Call
1060—The Missing Cotton King
1061—A Game of Plots
1062—The Prince of Liars
1063—The Man at the Window
1064—The Red League
1065—The Price of a Secret
1066—The Worst Case on Record
1067—From Peril to Peril
1068—The Seal of Silence
1069—Nick Carter’s Chinese Puzzle
1070—A Blackmailer’s Bluff
1071—Heard in the Dark
1072—A Checkmated Scoundrel
1073—The Cashier’s Secret
1074—Behind a Mask
1075—The Cloak of Guilt
1076—Two Villains in One
1077—The Hot Air Clew
1078—Run to Earth
1079—The Certified Check
1080—Weaving the Web
1081—Beyond Pursuit
1082—The Claws of the Tiger
1083—Driven from Cover
1084—A Deal in Diamonds
1085—The Wizard of the Cue
1086—A Race for Ten Thousand
1087—The Criminal Link
1088—The Red Signal
1089—The Secret Panel
1090—A Bonded Villain
1091—A Move in the Dark
1092—Against Desperate Odds
1093—The Telltale Photographs
1094—The Ruby Pin
1095—The Queen of Diamonds
1096—A Broken Trail
1097—An Ingenious Stratagem
1098—A Sharper’s Downfall
1099—A Race Track Gamble
1100—Without a Clew
1101—The Council of Death
1102—The Hole in the Vault
1103—In Death’s Grip
1104—A Great Conspiracy
1105—The Guilty Governor
1106—A Ring of Rascals
1107—A Masterpiece of Crime
1108—A Blow for Vengeance
1109—Tangled Threads
1110—The Crime of the Camera
1111—The Sign of the Dagger
1112—Nick Carter’s Promise
1113—Marked for Death
1114—The Limited Holdup
1115—When the Trap Was Sprung
1116—Through the Cellar Wall
1117—Under the Tiger’s Claws
1118—The Girl in the Case
1119—Behind a Throne
1120—The Lure of Gold
1121—Hand to Hand
1122—From a Prison Cell
1123—Dr. Quartz, Magician
1124—Into Nick Carter’s Web
1125—The Mystic Diagram
1126—The Hand that Won
1127—Playing a Lone Hand
1128—The Master Villain
1129—The False Claimant
1130—The Living Mask
1131—The Crime and the Motive
1132—A Mysterious Foe
1133—A Missing Man
1134—A Game Well Played
1135—A Cigarette Clew
1136—The Diamond Trail
1137—The Silent Guardian
1138—The Dead Stranger
1140—The Doctor’s Stratagem
1141—Following a Chance Clew
1142—The Bank Draft Puzzle
1143—The Price of Treachery
1144—The Silent Partner
1145—Ahead of the Game
1146—A Trap of Tangled Wire
1147—In the Gloom of Night
1148—The Unaccountable Crook
1149—A Bundle of Clews
1150—The Great Diamond
Syndicate
1151—The Death Circle
1152—The Toss of a Penny
1153—One Step Too Far
1154—The Terrible Thirteen
1155—A Detective’s Theory
1156—Nick Carter’s Auto Trail
1157—A Triple Identity
1158—A Mysterious Graft
1159—A Carnival of Crime
1160—The Bloodstone Terror
1161—Trapped in His Own Net
1162—The Last Move in the Game
1163—A Victim of Deceit
1164—With Links of Steel
1165—A Plaything of Fate
1166—The Key Ring Clew
1167—Playing for a Fortune
1168—At Mystery’s Threshold
1169—Trapped by a Woman
1170—The Four Fingered Glove
1171—Nabob and Knave
1172—The Broadway Cross
1173—The Man Without a
Conscience
1174—A Master of Deviltry
1175—Nick Carter’s Double Catch
1176—Doctor Quartz’s Quick Move
1177—The Vial of Death
1178—Nick Carter’s Star Pupils
1179—Nick Carter’s Girl Detective
1180—A Baffled Oath
1181—A Royal Thief
1182—Down and Out
1183—A Syndicate of Rascals
1184—Played to a Finish
1185—A Tangled Case
1186—In Letters of Fire
1187—Crossed Wires
1188—A Plot Uncovered
1189—The Cab Driver’s Secret
1190—Nick Carter’s Death Warrant
1191—The Plot that Failed
1192—Nick Carter’s Masterpiece
1193—A Prince of Rogues
1194—In the Lap of Danger
1195—The Man from London
1196—Circumstantial Evidence
1197—The Pretty Stenographer
Mystery
1198—A Villainous Scheme
1199—A Plot Within a Plot
1200—The Elevated Railroad
Mystery
1201—The Blow of a Hammer
1202—The Twin Mystery
1203—The Bottle With the Black
Label
1204—Under False Colors
1205—A Ring of Dust
1206—The Crown Diamond
1207—The Blood-red Badge
1208—The Barrel Mystery
1209—The Photographer’s Evidence
1210—Millions at Stake
1211—The Man and His Price
1212—A Double-Handed Game
1213—A Strike for Freedom
1214—A Disciple of Satan
1215—The Marked Hand
1216—A Fight with a Fiend
1217—When the Wicked Prosper
1218—A Plunge into Crime
1219—An Artful Schemer
1220—Reaping the Whirlwind
1221—Out of Crime’s Depths
1222—A Woman at Bay
1223—The Temple of Vice
1224—Death at the Feast
1225—A Double Plot
1226—In Search of Himself
1227—A Hunter of Men
1228—The Boulevard Mutes
1229—Captain Sparkle, Pirate
1230—Nick Carter’s Fall
1231—Out of Death’s Shadow
1232—A Voice from the Past
1233—Accident or Murder?
1234—The Man Who Was Cursed
1235—Baffled, But Not Beaten
1236—A Case Without a Clew
1237—The Demon’s Eye
1238—A Blindfold Mystery
1239—Nick Carter’s Swim to Victory
1240—A Man to Be Feared
1241—Saved by a Ruse
1242—Nick Carter’s Wildest Chase
1243—A Nation’s Peril
1244—The Rajah’s Ruby
1245—The Trail of a Human Tiger
1246—The Disappearing Princess
1247—The Lost Chittendens
1248—The Crystal Mystery
1249—The King’s Prisoner
1250—Talika, the Geisha Girl
1251—The Doom of the Reds
1252—The Lady of Shadows
1253—The Mysterious Castle
1254—The Senator’s Plot
1255—A Submarine Trail
1256—A War of Brains
1257—Pauline—A Mystery
1258—The Confidence King
1259—A Chase for Millions
1260—Shown on the Screen
1261—The Streaked Peril
1262—The Room of Mirrors
1263—A Plot for an Empire
1264—A Call on the Phone
In order that there may be no confusion, we desire to say that the
books listed below will be issued during the respective months to
New York City and vicinity. They may not reach the readers at a
distance promptly, on account of delays in transportation.
To be published in July, 1929.
1265—Nick Carter’s Convict Client
1266—The House of the Yellow
Door
1267—Nick Carter’s Round-up
To be published in August, 1929.
1268—A Masterly Trick
1269—For a Madman’s Millions
To be published in September,
1929.
1270—The Four Hoodoo Charms
1271—The Man in the Auto
To be published in October, 1929.
1272—The Jeweled Mummy
1273—The Vanishing Emerald
To be published in November, 1929.
1274—A Live Wire Clue
1275—The Vampire’s Trail
To be published in December, 1929.
1276—The Crimson Flash
1277—The Vanishing Heiress
BOOKS THAT NEVER GROW OLD
Alger Series
Clean Adventure Stories for Boys
The Most Complete List Published
The following list does not contain all the books that Horatio Alger
wrote, but it contains most of them, and certainly the best.
Horatio Alger is to boys what Charles Dickens is to grown-ups. His
work is just as popular to-day as it was years ago. The books have
a quality, the value of which is beyond computation.
There are legions of boys of foreign parents who are being helped
along the road to true Americanism by reading these books which
are so peculiarly American in tone that the reader cannot fail to
absorb some of the spirit of fair play and clean living which is so
characteristically American.
In this list will be included certain books by Edward Stratemeyer,
Oliver Optic, and other authors who wrote the Alger type of
stories, which are equal in interest and wholesomeness with those
written by the famous author after whom this great line of books
for boys is named.
ALL TITLES ALWAYS IN PRINT
By HORATIO ALGER, Jr.
1—Driven from Home
2—A Cousin’s Conspiracy
3—Ned Newton
4—Andy Gordon
5—Tony, the Tramp
6—The Five Hundred Dollar
Check
7—Helping Himself
8—Making His Way
9—Try and Trust
10—Only an Irish Boy
11—Jed, the Poorhouse Boy
12—Chester Rand
13—Grit, the Young Boatman of
Pine Point
14—Joe’s Luck
15—From Farm Boy to Senator
16—The Young Outlaw
17—Jack’s Ward
18—Dean Dunham
19—In a New World
20—Both Sides of the Continent
21—The Store Boy
22—Brave and Bold
23—A New York Boy
24—Bob Burton
25—The Young Adventurer
26—Julius, the Street Boy
27—Adrift in New York
28—Tom Brace
29—Struggling Upward
30—The Adventures of a New
York Telegraph Boy
31—Tom Tracy
32—The Young Acrobat
33—Bound to Rise
34—Hector’s Inheritance
35—Do and Dare
36—The Tin Box
In order that there may be no confusion, we desire to say that the
books listed below will be issued during the respective months in
New York City and vicinity. They may not reach the readers at a
distance promptly, on account of delays in transportation.
To be published in July, 1929.
37—Tom, the Bootblack
38—Risen from the Ranks
To be published in August, 1929.
39—Shifting for Himself
40—Wait and Hope
To be published in September,
1929.
41—Sam’s Chance
42—Striving for Fortune
To be published in October, 1929.
43—Phil, the Fiddler
44—Slow and Sure
To be published in November, 1929.
45—Walter Sherwood’s Probation
46—The Trials and Triumphs of
Mark Mason
47—The Young Salesman
To be published in December, 1929.
48—Andy Grant’s Pluck
49—Facing the World
NOW IN PRINT
By EDWARD STRATEMEYER
98—The Last Cruise of The
Spitfire
99—Reuben Stone’s Discovery
100—True to Himself
101—Richard Dare’s Venture
102—Oliver Bright’s Search
103—To Alaska for Gold
104—The Young Auctioneer
105—Bound to Be an Electrician
106—Shorthand Tom
108—Joe, the Surveyor
109—Larry, the Wanderer
110—The Young Ranchman
111—The Young Lumberman
112—The Young Explorers
113—Boys of the Wilderness
114—Boys of the Great Northwest
115—Boys of the Gold Field
116—For His Country
117—Comrades in Peril
118—The Young Pearl Hunters
119—The Young Bandmaster
121—On Fortune’s Trail
122—Lost in the Land of Ice
123—Bob, the Photographer
By OLIVER OPTIC
124—Among the Missing
125—His Own Helper
126—Honest Kit Dunstable
127—Every Inch a Boy
128—The Young Pilot
129—Always in Luck
130—Rich and Humble
131—In School and Out
133—Work and Win
135—Haste and Waste
136—Royal Tarr’s Pluck
137—The Prisoners of the Cave
138—Louis Chiswick’s Mission
139—The Professor’s Son
140—The Young Hermit
141—The Cruise of The Dandy
142—Building Himself Up
143—Lyon Hart’s Heroism
144—Three Young Silver Kings
145—Making a Man of Himself
146—Striving for His Own
147—Through by Daylight
148—Lightning Express
149—On Time
150—Switch Off
151—Brake Up
152—Bear and Forbear
153—The “Starry Flag”
154—Breaking Away
155—Seek and Find
156—Freaks of Fortune
157—Make or Break
158—Down the River
159—The Boat Club
160—All Aboard
161—Now or Never
162—Try Again
163—Poor and Proud
164—Little by Little
165—The Sailor Boy
166—The Yankee Middy
167—Brave Old Salt
175—Fighting for Fortune By Roy Franklin
176—The Young Steel Worker By Frank H. MacDougal
177—The Go-ahead Boys By Gale Richards
178—For the Right By Roy Franklin
179—The Motor Cycle Boys By Donald Grayson
180—The Wall Street Boy By Allan Montgomery
181—Stemming the Tide By Roy Franklin
182—On High Gear By Donald Grayson
183—A Wall Street Fortune By Allan Montgomery
184—Winning by Courage By Roy Franklin
185—From Auto to Airship By Donald Grayson
186—Camp and Canoe By Remson Douglas
187—Winning Against Odds By Roy Franklin
188—The Luck of Vance Sevier By Frederick Gibson
189—The Island Castaway By Roy Franklin
190—The Boy Marvel By Frank H. MacDougal
191—A Boy With a Purpose By Roy Franklin
192—The River Fugitives By Remson Douglas
READ
When you want real recreation in your leisure hours, read! Read
the Street & Smith Novels!
They are the cheapest and the most interesting reading matter
published in America to-day. No jazz—no sex—just big, clean,
interesting books. There are hundreds of different titles, among
which you will find a lot of exactly the sort of reading you want.
So, when you get tired of rolling around in your Lady Lizzie or
listening to the blah-blah of your radio, hie yourself to the nearest
news dealer, grab off a copy of a good detective, adventure or
love story, and then READ!
Read the Street & Smith Novels. Catalog sent upon request.
Street & Smith Corporation
79 Seventh Avenue New York City
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com

More Related Content

PPT
Ppt for Online music store
PDF
Developing A Java Web Application In A Day Step By Step Explanations With Ecl...
PDF
(Manning) --web development with javaserver pages, 2 nd ed---(2002)
PDF
(Ebook) Java server Pages by Hans Bergsten ISBN 9781565927469, 156592746X
PDF
(Ebook) Java server Pages by Hans Bergsten ISBN 9781565927469, 156592746X
PDF
Java Edge.2008.Web.Frameworks.Catagorized
PDF
Jsp2 ch5
PDF
Core Servlets and JavaServer Pages Vol 1 Core Technologies 2. ed., Nachdr Edi...
Ppt for Online music store
Developing A Java Web Application In A Day Step By Step Explanations With Ecl...
(Manning) --web development with javaserver pages, 2 nd ed---(2002)
(Ebook) Java server Pages by Hans Bergsten ISBN 9781565927469, 156592746X
(Ebook) Java server Pages by Hans Bergsten ISBN 9781565927469, 156592746X
Java Edge.2008.Web.Frameworks.Catagorized
Jsp2 ch5
Core Servlets and JavaServer Pages Vol 1 Core Technologies 2. ed., Nachdr Edi...

Similar to Developing Java Servlets 2nd Edition James Goodwill (20)

PDF
JavaServer Pages 2nd Edition Larne Pekowsky
PPTX
Platform for Enterprise Solution - Java EE5
PPT
Developing Java Web Applications
PDF
14 mvc
PPTX
Java web application development
PPTX
Engineering the Java Web Application (MVC)
PDF
Web Development With Java Using Hibernate Jsps And Servlets Tim Downey
PDF
Core JavaServer TM Faces 2nd Edition David Geary
PDF
JavaServer Pages 2nd Edition Larne Pekowsky
PPTX
Arpita industrial trainingppt
PPTX
Jsp and Servlets
PPTX
BITM3730Week12.pptx
PPTX
JSP APP DEVLOPMENT.pptx Related to Android App Development
PDF
Mvc15 (1)
POT
Beginning In J2EE
PPTX
Advance Java Topics (J2EE)
PDF
Introduction To J Boss Seam
PPTX
AJppt.pptx
PDF
Core java server faces
PDF
PDF JavaServer Pages 2nd Edition Larne Pekowsky download
JavaServer Pages 2nd Edition Larne Pekowsky
Platform for Enterprise Solution - Java EE5
Developing Java Web Applications
14 mvc
Java web application development
Engineering the Java Web Application (MVC)
Web Development With Java Using Hibernate Jsps And Servlets Tim Downey
Core JavaServer TM Faces 2nd Edition David Geary
JavaServer Pages 2nd Edition Larne Pekowsky
Arpita industrial trainingppt
Jsp and Servlets
BITM3730Week12.pptx
JSP APP DEVLOPMENT.pptx Related to Android App Development
Mvc15 (1)
Beginning In J2EE
Advance Java Topics (J2EE)
Introduction To J Boss Seam
AJppt.pptx
Core java server faces
PDF JavaServer Pages 2nd Edition Larne Pekowsky download
Ad

Recently uploaded (20)

PDF
RMMM.pdf make it easy to upload and study
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Sports Quiz easy sports quiz sports quiz
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
master seminar digital applications in india
PPTX
Final Presentation General Medicine 03-08-2024.pptx
RMMM.pdf make it easy to upload and study
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Computing-Curriculum for Schools in Ghana
TR - Agricultural Crops Production NC III.pdf
Microbial diseases, their pathogenesis and prophylaxis
Microbial disease of the cardiovascular and lymphatic systems
STATICS OF THE RIGID BODIES Hibbelers.pdf
Pharma ospi slides which help in ospi learning
O7-L3 Supply Chain Operations - ICLT Program
Module 4: Burden of Disease Tutorial Slides S2 2025
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
GDM (1) (1).pptx small presentation for students
Sports Quiz easy sports quiz sports quiz
VCE English Exam - Section C Student Revision Booklet
Pharmacology of Heart Failure /Pharmacotherapy of CHF
O5-L3 Freight Transport Ops (International) V1.pdf
Renaissance Architecture: A Journey from Faith to Humanism
master seminar digital applications in india
Final Presentation General Medicine 03-08-2024.pptx
Ad

Developing Java Servlets 2nd Edition James Goodwill

  • 1. Developing Java Servlets 2nd Edition James Goodwill download https://ebookgate.com/product/developing-java-servlets-2nd- edition-james-goodwill/ Get Instant Ebook Downloads – Browse at https://ebookgate.com
  • 2. Get Your Digital Files Instantly: PDF, ePub, MOBI and More Quick Digital Downloads: PDF, ePub, MOBI and Other Formats Apache Jakarta Tomcat 1st Edition James Goodwill https://ebookgate.com/product/apache-jakarta-tomcat-1st-edition- james-goodwill/ Murach s Java Servlets and JSP 3rd Edition Edition Joel Murach https://ebookgate.com/product/murach-s-java-servlets-and-jsp-3rd- edition-edition-joel-murach/ Java 2 micro edition Java in small things James White https://ebookgate.com/product/java-2-micro-edition-java-in-small- things-james-white/ Developing a Dream Destination James Mak https://ebookgate.com/product/developing-a-dream-destination- james-mak/
  • 3. The Java Language Specification Third Edition James Gosling https://ebookgate.com/product/the-java-language-specification- third-edition-james-gosling/ Developing Applications with Java TM and UML 1st Edition Paul R. Reed https://ebookgate.com/product/developing-applications-with-java- tm-and-uml-1st-edition-paul-r-reed/ Developing Web Services with Java APIs for XML 1st Edition Robert Hablutzel https://ebookgate.com/product/developing-web-services-with-java- apis-for-xml-1st-edition-robert-hablutzel/ The Java Language Specification Java SE 8 Edition James Gosling & Bill Joy & Guy L. Steele https://ebookgate.com/product/the-java-language-specification- java-se-8-edition-james-gosling-bill-joy-guy-l-steele/ Java 9 Modularity Patterns and Practices for Developing Maintainable Applications 1st Edition Sander Mak https://ebookgate.com/product/java-9-modularity-patterns-and- practices-for-developing-maintainable-applications-1st-edition- sander-mak/
  • 5. James Goodwill 800 East 96th St., Indianapolis, Indiana, 46240 USA Developing Java™ Servlets
  • 6. Developing Java™ Servlets, Second Edition Copyright © 2001 by Sams Publishing All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photo- copying, recording, or otherwise, without written permission from the pub- lisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-672-32107-6 Library of Congress Catalog Card Number: 00-111799 Printed in the United States of America First Printing: June 2001 04 03 02 01 4 3 2 1 Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages aris- ing from the information contained in this book. PUBLISHER Paul Boger EXECUTIVE EDITOR Michael Stephens ACQUISITIONS EDITOR Carol Ackerman DEVELOPMENT EDITOR Tiffany Taylor MANAGING EDITOR Matt Purcell PROJECT EDITOR Christina Smith COPY EDITOR Cynthia Fields INDEXER Erika Millen PROOFREADER Benjamin Berg TECHNICAL EDITOR Rob Tiffany TEAM COORDINATOR Lynne Williams INTERIOR DESIGNER Anne Jones COVER DESIGNER Aren Howell PAGE LAYOUT Ayanna Lacey Heather Hiatt Miller Stacey Richwine-DeRome
  • 7. Overview Contents at a Glance Introduction 1 1 Web Applications and the Model View Controller (MVC) Design Pattern 7 PART I Servlet Fundamentals 2 Servlet Overview and Architecture 15 3 Servlet Basics 25 4 Servlets and HTML 33 5 Servlet Sessions 41 6 HTTP Tunneling 59 7 Servlets, JDBC, and Inter-Servlet Communications 85 8 Servlets and JavaMail 131 9 Servlet Security 143 10 Servlets and XML 151 11 Servlets and LDAP 163 12 Servlets and Enterprise JavaBeans 189 13 A Servlet Controller 225 PART II JSP Fundamentals 14 JSP Overview and Architecture 235 15 JSP Implicit Objects 247 16 JSP Standard Actions 261 17 Using JavaBeans and JSP Scopes 281 18 Handling JSP Errors 293 19 Custom JSP Tag Libraries 301
  • 8. PART III Servlet and JSP Web Applications 20 Catalog Case Study 321 21 An LDAP Web Client 347 22 A Stock Trader 363 23 Wireless Application Development Using WAP 385 24 WML/WMLScript Development 397 PART IV Appendixes A Web Applications and Configuring the Servlet Engine 419 B The javax.servlet Package 429 C The javax.servlet.http Package 461 D The javax.servlet.jsp Package 489 E The javax.servlet.jsp.tagext Package 513 F WML (The Wireless Markup Language) 543 G WMLScript 547 Index 559
  • 9. Contents Introduction 1 1 Web Applications and the Model View Controller (MVC) Design Pattern 7 The Model View Controller (MVC) Design Pattern ..............................8 A Server-Side Implementation of the MVC............................................8 Servlets as MVC Controllers..............................................................9 JSPs as MVC Views ........................................................................10 Summary................................................................................................10 PART I Servlet Fundamentals 2 Servlet Overview and Architecture 15 Movement to Server-Side Java ..............................................................16 Definition of a Java Servlet ..................................................................16 Practical Applications for Java Servlets ................................................16 Java Servlet Alternatives........................................................................17 Common Gateway Interface ............................................................17 Proprietary APIs ..............................................................................18 Server-Side JavaScript......................................................................18 Microsoft’s Active Server Pages ......................................................18 Reasons to Use Java Servlets ................................................................19 Efficiency..........................................................................................19 Persistency........................................................................................19 Portability ........................................................................................19 Robustness........................................................................................19 Extensibility......................................................................................20 Security ............................................................................................20 The Java Servlet Architecture................................................................20 GenericServlet and HttpServlet........................................................20 Summary................................................................................................23 3 Servlet Basics 25 The Life Cycle of a Servlet ..................................................................26 The init() Method ............................................................................26 The service() Method ......................................................................26 The destroy() Method ......................................................................27 A Basic Servlet ......................................................................................27 The BasicServlet Source ..................................................................27 Dissecting the BasicServlet ..................................................................29 Where Does the BasicServlet Fit into the Servlet Framework? ......29 The Methods Overridden by the BasicServlet ................................30 Summary................................................................................................31
  • 10. DEVELOPING JAVA SERVLETS, SECOND EDITION vi 4 Servlets and HTML 33 Retrieving Form Data in a Servlet ........................................................34 Servicing the GET and POST Requests ..........................................34 How the FormServlet Works ............................................................38 Summary................................................................................................39 5 Servlet Sessions 41 What Is Session Tracking? ....................................................................42 Using Hidden Form Fields ....................................................................42 Working with Cookies ..........................................................................46 URL Rewriting ......................................................................................50 Session Tracking with the Servlet API..................................................51 Summary................................................................................................58 6 HTTP Tunneling 59 What Is HTTP Tunneling? ....................................................................60 Object Serialization................................................................................60 Creating an HTTP Tunneling Client......................................................66 Creating an HTTP Tunneling Servlet....................................................71 A Practical HTTP Tunneling Example..................................................73 The OrderStatusApplet ....................................................................74 The OrderStatusServlet ....................................................................80 Pros and Cons of Applet-to-Servlet Communication............................83 Summary................................................................................................84 7 Servlets, JDBC, and Inter-Servlet Communications 85 What is the JDBC? ................................................................................86 Two- and Three-Tier Database Access Models ....................................86 JDBC Driver Types................................................................................87 Type 1: JDBC-ODBC Bridge, Plus ODBC Driver ..........................88 Type 2: Native-API, Partly Java Driver............................................88 Type 3: JDBC-Net, Pure Java Driver ..............................................89 Type 4: Native-Protocol, Pure Java Driver ......................................90 JDBC Basics ........................................................................................92 Installing and Setting Up a Type 1 Driver ......................................92 Establishing a Database Connection ................................................93 Performing the Basic SQL Commands............................................94 A Basic JDBC Servlet ........................................................................107 A JDBC Connection Pool....................................................................112 Inter-Servlet Communications ............................................................123 Summary..............................................................................................130
  • 11. CONTENTS vii 8 Servlets and JavaMail 131 JavaMail and Internet E-mail ..............................................................132 JavaMail Services ..........................................................................132 Preparing to Use JavaMail ..................................................................133 A JavaMail Example............................................................................133 Using JavaMail in a Servlet ................................................................137 Summary..............................................................................................141 9 Servlet Security 143 Introduction to Security ......................................................................144 Roll Your Own ....................................................................................144 Basic Authentication............................................................................148 Digest Authentication ..........................................................................148 Secure Sockets Layer (SSL)................................................................149 Summary..............................................................................................150 10 Servlets and XML 151 XML and Java......................................................................................153 Using the SAX API ........................................................................153 Using XML in a Servlet ......................................................................159 Summary..............................................................................................162 11 Servlets and LDAP 163 A Brief Discussion of Directories ......................................................164 Attributes ........................................................................................165 Distinguished Names......................................................................165 LDAP ..................................................................................................165 JNDI ....................................................................................................166 Using JNDI to Access LDAP ..............................................................166 Installing Netscape Directory Server ............................................167 Connecting......................................................................................168 Searching the LDAP Server ..........................................................170 Adding an Object to an LDAP Server............................................174 Removing an Object ......................................................................176 Modifying Information Stored in LDAP........................................177 Accessing LDAP from a Servlet..........................................................184 Summary..............................................................................................188 12 Servlets and Enterprise JavaBeans 189 What Are Enterprise JavaBeans? ........................................................190 EJB Terminology ................................................................................191 Installing JRun ....................................................................................191 The Enterprise JavaBean......................................................................192 Interfaces and Classes ....................................................................192 Naming Conventions ......................................................................193
  • 12. DEVELOPING JAVA SERVLETS, SECOND EDITION viii Session Beans ......................................................................................194 Stateless Versus Stateful ................................................................194 Session Bean Interfaces and Classes..............................................195 Deployment Descriptor ..................................................................200 Client View of a Session Bean ......................................................204 Session Bean Lifecycle ..................................................................205 Entity Beans ........................................................................................206 Who Handles the Persistence? ......................................................206 Entity Bean Interfaces and Classes ................................................207 Deployment Descriptor ..................................................................215 Client View of an Entity Bean........................................................217 Entity Bean Life Cycle ..................................................................217 Deploying Your EJB to Your Application Server ................................218 Packaging the jar File ....................................................................218 Deploying the jar File ....................................................................220 Viewing Deployed Beans ..............................................................220 Servlets as EJB Clients........................................................................220 Summary..............................................................................................224 13 A Servlet Controller 225 What Is a Controller? ..........................................................................226 A Servlet Controller ............................................................................226 The Service Interface ..........................................................................229 A Sample Service ................................................................................230 Summary..............................................................................................232 PART II JSP Fundamentals 14 JSP Overview and Architecture 235 What are JavaServer Pages? ................................................................236 The Components of a JavaServer Page ..............................................237 Directives........................................................................................238 Standard Actions ............................................................................240 Implicit Objects ..............................................................................241 JSP Scripting ..................................................................................242 Summary..............................................................................................246 15 JSP Implicit Objects 247 What are Implicit Objects?..................................................................248 The request Object ..............................................................................249 The response Object ............................................................................250 The pageContext Object ......................................................................251 The session Object ..............................................................................252
  • 13. CONTENTS The application Object ........................................................................254 Testing the JSPs..............................................................................256 The out Object ....................................................................................257 The config Object ................................................................................258 The page Object ..................................................................................260 The exception Object ..........................................................................260 Summary..............................................................................................260 16 JSP Standard Actions 261 What Are Standard Actions?................................................................262 JavaBean Standard Actions..................................................................262 The <jsp:useBean> Standard Action..............................................262 The <jsp:setProperty> Standard Action ........................................263 The <jsp:getProperty> Standard Action ........................................264 A JSP Example Using JavaBeans ..................................................264 Other Standard Actions........................................................................268 The <jsp:param> Standard Action ................................................268 The <jsp:include> Standard Action................................................269 The <jsp:forward> Standard Action ..............................................274 The <jsp:plugin> Standard Action ................................................278 Summary..............................................................................................279 17 Using JavaBeans and JSP Scopes 281 The Counter JavaBean ........................................................................282 page Scope ..........................................................................................283 request Scope ......................................................................................284 session Scope ......................................................................................286 application Scope ................................................................................289 Summary..............................................................................................291 18 Handling JSP Errors 293 JSP Translation-Time Errors................................................................294 JSP Request-Time Errors ....................................................................294 Creating a JSP Error Page..............................................................294 Using a JSP Error Page ..................................................................297 Summary..............................................................................................300 19 Custom JSP Tag Libraries 301 JSP Customs Tags................................................................................302 Deploying Tag Libraries ......................................................................302 Creating a Taglib Descriptor ..........................................................302 Deploying the Tag Handlers to Your Web Application ..................304 Adding a taglib Entry to Your Web Application ............................304 Adding the taglib Directive to Your JSP ........................................305 ix
  • 14. DEVELOPING JAVA SERVLETS, SECOND EDITION Developing Custom JSP Tags Handlers ..............................................306 Tags Without Bodies ......................................................................306 Tags with Bodies ............................................................................311 Tags with Attributes........................................................................314 Summary..............................................................................................317 PART III Servlet and JSP Web Applications 20 Catalog Case Study 321 Catalog Requirements..........................................................................322 Models..................................................................................................322 Shopping Cart ................................................................................325 Views....................................................................................................328 Catalog Layout ..............................................................................328 Index View......................................................................................332 Movie List View ............................................................................334 Shopping Cart View........................................................................335 Check Out View..............................................................................336 Controllers............................................................................................338 The ListMovies Service..................................................................338 The AddToCart Service..................................................................341 The EmptyCart Service ..................................................................343 The CheckOut Service....................................................................343 Using the Online Catalog ....................................................................344 Summary..............................................................................................345 21 An LDAP Web Client 347 Directory Requirements ......................................................................348 Models..................................................................................................348 Views....................................................................................................349 The Directory Layout ....................................................................349 Index View......................................................................................351 Directory View................................................................................352 Add View........................................................................................354 Controllers............................................................................................356 The LDAPDirectory Service ..........................................................356 The LDAPInsert Service ................................................................358 The LDAPDelete Service ..............................................................359 Using the LDAP Application ..............................................................360 Summary..............................................................................................361 22 A Stock Trader 363 Trader Requirements............................................................................364 Models..................................................................................................364 x
  • 15. CONTENTS Views....................................................................................................367 Trader Layout ................................................................................367 Index View......................................................................................370 Get Quote View ..............................................................................371 Buy/Sell View ................................................................................372 Controllers............................................................................................375 The GetQuote Service ....................................................................375 The Buy Service ............................................................................377 The Sell Service..............................................................................380 Using the Trader Application ..............................................................382 Summary..............................................................................................383 23 Wireless Application Development Using WAP 385 WAP History: Past, Present, and Future..............................................386 The Past: Handheld Device Markup Language (HDML)..............386 Present: WAP Hits the Street..........................................................387 The Future: WAP 1.2 and Beyond ................................................387 Why WAP? ..........................................................................................389 Screen Size Considerations ............................................................389 Network Considerations ................................................................390 Bandwidth Considerations..............................................................390 WAP Architecture ................................................................................391 Emulators, Browsers, and Developer Tools ........................................392 Online Emulators............................................................................392 WinWAP Browser ..........................................................................392 Emulators and Developer Tools ....................................................394 PDA WAP Browsers ......................................................................394 Application Servers ........................................................................395 Suggested Resources............................................................................395 Summary..............................................................................................396 24 WML/WMLScript Development 397 The Wireless Markup Language (WML) ............................................398 WML Language Basics..................................................................398 A WML Example ................................................................................401 WMLScript ..........................................................................................405 Calling WMLScript from WML ....................................................406 Language Basics ............................................................................406 Operators ........................................................................................407 Statements ......................................................................................407 The Standard Libraries ..................................................................408 WMLScript Example......................................................................409 xi
  • 16. DEVELOPING JAVA SERVLETS, SECOND EDITION Wireless Application Developing Using Servlets................................412 Configuring Server MIME Types ..................................................412 A Quick “Hello World!” WML Servlet ........................................413 Multiple Device Support ................................................................414 Maintaining a Site in XML ............................................................414 Summary..............................................................................................415 PART IV Appendixes A Web Applications and Configuring the Servlet Engine 419 Web Applications ................................................................................420 The ServletContext in Relation to the Web Application................420 The Directory Structure..................................................................420 Web Application Deployment Descriptors ....................................421 Web Archive (WAR) Files ..................................................................422 Servlet Requirements ..........................................................................422 Apache Tomcat ....................................................................................422 Installing the Tomcat Server ..........................................................422 Adding the DJS Web Application ..................................................424 Building and Installing the BasicServlet........................................426 Summary..............................................................................................427 B The javax.servlet Package 429 The javax.servlet Interfaces ................................................................430 The RequestDispatcher Interface ..................................................431 The Servlet Interface ......................................................................432 The ServletConfig Interface ..........................................................433 The ServletContext Interface..........................................................434 The ServletRequest Interface ........................................................440 The ServletResponse Interface ......................................................445 The SingleThreadModel Interface..................................................448 Classes..................................................................................................448 The GenericServlet Class ..............................................................449 The ServletInputStream Class........................................................452 The ServletOutputStream Class ....................................................452 Exceptions............................................................................................456 The ServletException ....................................................................456 The UnavailableException ............................................................458 C The javax.servlet.http Package 461 Interfaces..............................................................................................462 The HttpServletRequest Interface ..................................................462 The HttpServletResponse Interface................................................468 The HttpSession Interface ..............................................................476 The HttpSessionBindingListener Interface ....................................479 xii
  • 17. CONTENTS Classes..................................................................................................479 The Cookie Class............................................................................479 The HttpServlet Class ....................................................................483 The HttpSessionBindingEvent Class..............................................486 The HttpUtils Class ........................................................................487 D The javax.servlet.jsp Package 489 Interfaces..............................................................................................490 The HttpJspPage Interface..............................................................490 The JspPage Interface ....................................................................491 Classes..................................................................................................492 The JspEngineInfo Class................................................................492 The JspFactory Class......................................................................492 The JspWriter Class........................................................................494 The PageContext Class ..................................................................502 Exceptions............................................................................................511 The JspError Exception..................................................................511 The JspException Exception ..........................................................512 E The javax.servlet.jsp.tagext Package 513 Interfaces..............................................................................................514 The Tag Interface............................................................................514 The BodyTag Interface ..................................................................520 Classes..................................................................................................522 The BodyContent Class..................................................................522 The BodyTagSupport Class............................................................523 The TagSupport Class ....................................................................525 The TagAttributeInfo Class ............................................................528 The TagData Class..........................................................................530 The TagExtraInfo Class..................................................................532 The TagInfo Class ..........................................................................533 The TagLibraryInfo Class ..............................................................537 The VariableInfo Class ..................................................................539 F WML (The Wireless Markup Language) 543 WML Elements....................................................................................544 G WMLScript 547 Lang Library ........................................................................................548 abort()—The abort Function ..........................................................548 abs()—The abs Function ................................................................548 characterSet()—The characterSet Function ..................................548 exit()—The exit Function ..............................................................548 float()—The float Function ............................................................548 xiii
  • 18. DEVELOPING JAVA SERVLETS, SECOND EDITION isFloat()—The isFloat Function ....................................................549 isInt()—The isInt Function ............................................................549 max()—The max Function ............................................................549 maxInt()—The maxInt Function ....................................................549 min()—The min Function ..............................................................549 minInt()—The minInt Function......................................................549 parseFloat()—The parseFloat Function..........................................549 parseInt()—The parseInt Function ................................................549 random()—The random Function ..................................................550 seed()—The seed Function ............................................................550 Float Library ........................................................................................550 ceil()—The ceil Function ..............................................................550 floor()—The floor Function ..........................................................550 int()—The int Function ..................................................................550 maxFloat()—The maxFloat Function ............................................550 minFloat()—The minFloat Function..............................................551 pow()—The pow Function ............................................................551 round()—The round function ........................................................551 sqrt()—The sqrt Function ..............................................................551 String Library ......................................................................................551 charAt()—The charAt Function ....................................................551 compare()—The compare Function ..............................................551 elementAt()—The elementAt Function..........................................551 elements()—The elements Function ..............................................552 find()—The find Function ..............................................................552 format()—The format Function......................................................552 insertAt()—The insertAt Function ................................................552 isEmpty()—The isEmpty Function ................................................552 length()—The length Function ......................................................552 removeAt()—The removeAt Function ..........................................552 replace()—The replace Function....................................................553 replaceAt()—The replaceAt Function............................................553 squeeze()—The squeeze Function..................................................553 subString()—The subString Function ............................................553 toString()—The toString Function ................................................553 trim()—The trim Function..............................................................553 URL Library ........................................................................................553 escapeString()—The escapeString Function..................................554 getBase()—The getBase Function..................................................554 getFragment()—The getFragment Function ..................................554 getHost()—The getHost Function..................................................554 getParameters()—The getParameters Function..............................554 xiv
  • 19. CONTENTS getPath()—The getPath Function ..................................................554 getPort()—The getPort Function....................................................555 getQuery()—The getQuery Function ............................................555 getReferer()—The getReferer Function ........................................555 getScheme()—The getScheme Function........................................555 isValid()—The isValid Function ....................................................555 loadString()—The loadString Function..........................................555 resolve()—The resolve Function....................................................555 unescapeString()—The unescapeString Function..........................555 WMLBrowser Library ........................................................................556 getCurrentCard()—The getCurrentCard Function ........................556 getVar()—The getVar Function......................................................556 go()—The go Function ..................................................................556 newContext()—The newContext Function ....................................556 prev()—The prev Function ............................................................556 refresh()—The refresh Function ....................................................556 setVar()—The setVar Function ......................................................556 Dialogs Library....................................................................................557 alert()—The alert Function ............................................................557 confirm()—The confirm Function..................................................557 prompt()—The prompt Function....................................................557 Index 559 xv
  • 20. About the Authors Lead Author James Goodwill is the co-founder and chief architect at Virtuas Solutions, LLC., located in Denver, Colorado. He has extensive experience in designing and architecting e-business appli- cations. James is also the author of Pure JavaServer Pages, which provides a thorough exami- nation of the JavaServer Pages technology. James is currently leading Virtuas’s efforts in developing cutting edge tools designed for J2EE e-business acceleration. You can find the source code and support for this text at the Virtuas Solutions Web site, http://www.virtuas.com. Select the Publications link. Contributing Author Bryan Morgan is an experienced writer and software developer and founder of the Wireless Developer Network (http://www.wirelessdevnet.com) in 1999. He is a respected voice in the wireless industry, is a regular contributor to industry publications, and has been a featured speaker at numerous events. He holds a B.S. in electrical engineering from Clemson University and lives in Pensacola, FL with his wife Becky and beautiful daughter Emma.
  • 21. Dedication To my girls Christy, Abby, and Emma. Acknowledgments Before I start thanking those close to home, I need to thank the people who made this book what it is. They are the people who took my words and molded and shaped them into some- thing that I hope will help you become an effective Web application developer. I would like to thank Carol Ackerman, my acquisitions editor, who answered all my questions and resolved any issues that came up. I would especially like to thank Tiffany Taylor for her excellent edit- ing. I would like to thank Rob Tiffany for his great technical comments and recommendations. I would also like to thank Cynthia Fields for her excellent copy-editing. And finally, I would like to thank Christina Smith for managing the entire project. Each and every person made this book what it is. On a closer note, I would first like to thank everyone at my company, Virtuas Solutions, Inc. for their support while I was completing this text. The entire staff contributed by picking up my assignments when my plate was too full. In particular I would like to thank those “UNREAL” people that I worked with on a daily basis including Matthew “Deckard” Filios, Karen “Blue Bullet” Jackson, Eric “Crazy Mary” Johnson, Jason “Cutt” Nordyke, David “Busta” Goedecke, Mike “Ivan” Day, Gary “Monica” Goodrum, and especially Aaron “Ronin” Bandell, for his contribution of Chapters 11 and 12. Finally, the most important contributors to this book are my wife Christy, and our daughters Abby and Emma. They supported me throughout the entire book, with complete understand- ing. They listened to me complain and took care of things when I disappeared into the office. With their support, I can do anything.
  • 22. Tell Us What You Think! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. As an executive editor for Sams Publishing, I welcome your comments. You can fax, e-mail, or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger. Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message. When you write, please be sure to include this book’s title and author’s name as well as your name and phone or fax number. I will carefully review your comments and share them with the author and editors who worked on the book. Fax: 317-581-4770 E-mail: feedback@samspublishing.com Mail: Michael Stephens Executive Editor Sams Publishing 201 West 103rd Street Indianapolis, IN 46290 USA
  • 23. Introduction Structure of This Book Before you begin reading this book, you might want to take a look at its basic structure. This will help you outline your reading plan, if you choose not to read it from cover to cover. This introduction gives you an overview of what each chapter covers. Chapter 1, “Web Applications and the Model View Controller (MVC) Design Pattern” Chapter 1 lays the foundation for the entire text. It introduces your to the Model View Controller design pattern. It also introduces you to a server-side implementation of the MVC and how both servlets and JSPs fit into this pattern Chapter 2, “Servlet Overview and Architecture” Chapter 2 introduces you to the Java servlet architecture. It talks about the movement to server-side Java. It also details reasons why you should use Java servlets. Chapter 3, “Servlet Basics” Chapter 3 is where you begin to actually examine servlets. This chapter details the life cycle of a servlet and shows you source code for a basic servlet. Chapter 4, “Servlets and HTML” Chapter 4 shows you how to link HTML forms to Java servlets and how you should retrieve form data in a servlet. Chapter 5, “Servlet Sessions” Chapter 5 discusses several ways that you can maintain state while using servlets. The methods that it discusses include hidden form fields, cookies, URL rewriting, and session tracking with the Servlet API. Chapter 6, “HTTP Tunneling” Chapter 6 covers HTTP tunneling. It provides a definition of HTTP tunneling, describes object serialization (which is required in tunneling), it describes the creation of a tunneling client and server, and it gives a practical tunneling example. It also covers some of the pros and cons of applet to servlet communications.
  • 24. DEVELOPING JAVA SERVLETS Chapter 7, “Servlets, JDBC, and Inter-Servlet Communications” Chapter 7 discusses how servlets can use the JDBC to interact with relational databases. It gives a basic introduction to the JDBC and then combines the technology with servlets. It also discusses a technique used to communicate between servlets. Chapter 8, “Servlets and JavaMail” Chapter 8 discusses JavaMail and how you to use it with servlets and other applications. Chapter 9, “Servlet Security” Chapter 9 describes security issues that you face when deploying an application to the Internet. It covers the most popular security techniques. It also describes some of each technique’s pros and cons. Chapter 10, “Servlets and XML” Chapter 10 covers the basics of Extensible Markup Language, or XML. It discusses how to use Sun’s SAX parser. It also shows an example of how you would incorporate XML and servlets. Chapter 11, “Servlets and LDAP” Chapter 11 covers the Lightweight Directory Access Protocol (LDAP). It covers using JNDI to access LDAP servers and it closes with an LDAP example integrated into a servlet. Chapter 12, “Servlets and Enterprise JavaBeans” Chapter 12 provides an introduction to Enterprise JavaBeans (EJB). It covers using EJBs from an application as well as integrated into a servlet. Chapter 13, “A Servlet Controller” Chapter 13 shows you how to create a servlet class that acts as the Controller in the Model View Controller design pattern. Chapter 14, “JSP Overview and Architecture” Chapter 14 takes a look at the basics of JSP and the components of JSPs. It shows you how to create a JSP document and understand what is happening behind the scenes at request time. It also discusses the process a JSP file goes through when it is first requested. 2
  • 25. INTRODUCTION Chapter 15, “JSP Implicit Objects” Chapter 15 discusses the JSP implicit objects and how they are commonly used. It also talks about how they are created in the JSP’s generated servlet. Chapter 16, “Using JSP Standard Actions” Chapter 16 covers the JSP standard actions, including how they are implemented and how you can use them. Chapter 17, “Using JavaBeans and JSP Scopes” Chapter 17 covers how JSP beans are scoped. It discusses the different types of JSP scope. It also covers how the life of a JSP bean is determined by its scope. Chapter 18, “Handling JSP Errors” Chapter 18 covers the types of errors that can occur in a JSP. It shows you how to handle and respond to these errors using a JSP error page. Chapter 19, “Custom JSP Tag Libraries” Chapter 19 covers custom JSP tag libraries including tags with and without bodies. It also dis- cusses how tags are packaged and deployed. Chapter 20, “Catalog Case Study” Chapter 20 provides an MVC case study using an online movie catalog as an example includ- ing requirements, MVC components, and how to use the finished catalog. Chapter 21, “An LDAP Web Client” Chapter 21 provides an MVC case study using a LDAP client as an example including require- ments, MVC components, and how to use the finished client. Chapter 22, “A Stock Trader” Chapter 22 provides an MVC case study using a stock trading application as an example including requirements, MVC components, and how to use the finished application. 3
  • 26. DEVELOPING JAVA SERVLETS Chapter 23, “Wireless Application Development Using WAP” Chapter 23 introduces you to wireless application development using Java servlets and the Wireless Application Protocol (WAP), including the wide variety of client and server tools available to the WAP developer. It includes an example in which you create a dynamic wireless application using servlets and WAP. Chapter 24, “WML/WMLScript Development” Chapter 24 illustrates how to develop dynamic wireless Web applications using Java servlets, WML, and WMLScript. Appendix A, “Web Applications and Configuring the Servlet Engine” Appendix A covers the steps involved in retrieving and configuring the Tomcat server neces- sary to run the examples in this text. Appendix B, “The javax.servlet Package” Appendix B covers the classes, interfaces, and exceptions of the javax.servlet package. Appendix C, “The javax.servlet.http Package” Appendix C covers the classes, interfaces, and exceptions of the javax.servlet.http pack- age. Appendix D, “The javax.servlet.jsp Package” Appendix D covers the classes, interfaces, and exceptions of the javax.servlet.jsp package. Appendix E, “The javax.servlet.jsp.tagext Package” Appendix E covers the classes, interfaces, and exceptions of the javax.servlet.jsp.tagext package. Appendix F, “WML (The Wireless Markup Language)” Appendix F provides a tag references for WML. 4
  • 27. INTRODUCTION Appendix G, “WMLScript” Appendix G describes the libraries and functions used in WMLScript. 5
  • 29. CHAPTER 1 Web Applications and the Model View Controller (MVC) Design Pattern IN THIS CHAPTER • The Model View Controller (MVC) Design Pattern 8 • A Server-Side Implementation of the MVC 8
  • 30. This chapter is the foundation for this entire text. We will look at a design pattern that lever- ages the strengths of both servlets and Java Server Pages (JSPs) to create maintainable and reusable Web applications: the Model View Controller (MVC). In this study we will also look at exactly where and why both servlets and JSPs fit in this pattern. Because you have not yet covered servlet and JSP technologies, you will have to accept some of the statements made in this chapter. My goal for the remainder of this text is to show how and why this pattern and these technologies work so well when developing server-side Java Web applications. The Model View Controller (MVC) Design Pattern The MVC originated from Smalltalk and was used to design user interfaces. In such an inter- face, the application was made up of three classes: a Model, a View, and a Controller. Each of these classes is defined in Table 1.1. TABLE 1.1 The Classes of the MVC Class Definition Model The Model represents the data or application object. It is what is being manipulated and presented to the user. View The View is the screen representation of the Model. It is the object that presents the current state of the Model. Controller The Controller defines the way the user interface reacts to the user’s input. The Controller is the object that manipulates the Model. The major advantage of using the MVC design pattern is that it separates the Views and Models. As a result, you can separate presentation from business logic, and, in turn, create or change Views without having to change the Models or the Controller logic that manipulates the Models. The MVC also allows Models to be represented by multiple Views. A Server-Side Implementation of the MVC To implement the MVC server-side pattern in Java we must combine JSPs and servlets. In this section, we define a high-level server-side implementation of the MVC, where the Model is a JavaBean that represents the data being transmitted or received. The Controller is a servlet that manipulates or transmits data, and the View is a JSP that presents the results of the performed transaction. Figure 1.1 models the steps involved in a sever-side implementation of the MVC. DEVELOPING JAVA SERVLETS 8
  • 31. FIGURE 1.1 The steps in a server-side implementation of the MVC. These steps are as follows: 1. The Web Client makes a request to the Web Server. 2. The Web Server passes the request to the Controller Servlet. 3. The servlet performs necessary manipulations to the JavaBean/EJB Model. 4. The Controller Servlet forwards the results to the JSP View. 5. The JSP View formats the Model for display and sends the HTML results back to the Web Server. 6. The Web Server then conveys the information back to the Web Client. Some benefits of using a server-side implementation of the MVC include • A clear separation of the presentation and transaction layers, which gives you the ability to change the look and feel of an application without recompiling. • The ability to have multiple views for multiple clients. • The ability to have a less experienced programmer develop and maintain the user inter- face. • A quicker time-to-market by allowing the Controller programmers to focus only on transactions, whereas the View programmers can focus primarily on presentation. Servlets as MVC Controllers We have chosen to use servlets as MVC Controllers after examining some of their strengths and weaknesses. Web Applications and the Model View Controller (MVC) Design Pattern CHAPTER 1 1 W EB A PPLICATIONS AND THE MVC D ESIGN P ATTERN 9 Web Client Web Server Servlet (Controller) JSP (View) DBMS EJB/ BEAN EJB/ BEAN EJB/ BEAN EJB/ BEAN 1. 6. 2. 5. 4. 3. Application Server
  • 32. Strengths of servlets as Controllers are as follows: • Servlets have very robust server-side processing capabilities because they have access to almost the entire Java SDK. • The servlet architecture lends itself well to a transactional style of programming, which is analogous to MVC Controllers. Weaknesses of servlets as Controllers are as follows: • Servlets require an advanced level of Java understanding that HTML programmers usu- ally do not have. • Servlets generally require recompilation in order to change the client presentation layer. If we consider the previous lists, we can determine that servlets make prime candidates for MVC Controllers, where there will be fewer changes because the presentation logic has been abstracted. JSPs as MVC Views JavaServer Pages were chosen as MVC Views after a similar examination of their strengths and weaknesses. Strengths of JSPs as Views are as follows: • JSPs do not require programmer recompilation after source changes. • JSPs allow you to access Java objects that are stored in the HTTP session. • JSPs allow you to embed Java code directly into HTML pages with scriptlets. Weaknesses of JSPs as Views are as follows: • As your JSP code becomes more complicated, so does your scriptlet code. This results in confusing and difficult-to-maintain JSPs. • If you plan to allow your HTML programmers to maintain your JSPs, which is very common, they will require a good understanding of Java. After examining the previous lists, we can determine that JSPs make great candidates for MVC Views. This is because we can leverage a JSP’s access to Java objects, while conquering one of their major weaknesses by limiting scriptlet code to presentation only. Summary In this chapter, we laid the foundation for the rest of this text. We looked at the MVC design pattern and saw how we could combine servlets and JSPs to implement a server-side solution for Web applications. DEVELOPING JAVA SERVLETS 10
  • 33. In the rest of this text we will study servlets and JSPs in the context of this model. We will examine how servlets and JSPs work separately and then we will complete the text by combin- ing what we have learned into Web application case studies that implement the MVC. Web Applications and the Model View Controller (MVC) Design Pattern CHAPTER 1 1 W EB A PPLICATIONS AND THE MVC D ESIGN P ATTERN 11
  • 35. IN THIS PART 2 Servlet Overview and Architecture 3 Servlet Basics 4 Servlets and HTML 5 Servlet Sessions 6 HTTP Tunneling 7 Servlets, JDBC, and Inter-Servlet Communications 8 Servlets and JavaMail 9 Servlet Security 10 Servlets and XML 11 Servlets and LDAP 12 Servlets and Enterprise JavaBeans 13 A Servlet Controller Servlet Fundamentals PART I
  • 37. CHAPTER 2 Servlet Overview and Architecture IN THIS CHAPTER • Movement to Server-Side Java 16 • Definition of a Java Servlet 16 • Practical Applications for Java Servlets 16 • Java Servlet Alternatives 17 • Reasons to Use Java Servlets 19 • The Java Servlet Architecture 20
  • 38. Movement to Server-Side Java When the Java language was first introduced by Sun Microsystems Inc., its purpose was to embed greater interactivity into Web pages. Java has accomplished this through the use of applets. Applets add functionality to Web pages, but because of compatibility and bandwidth issues, businesses have started moving to server-side Java. Java applets are programs that are embedded directly into Web pages. When a browser loads a Web page, which contains a reference to an applet, the applet byte-code is downloaded to the client computer and executed by the browser. This is fine for very thin clients, but as applets grow in size the download times become unacceptable. Applets also have compatibility prob- lems. To run an applet you must have a compatible browser. If your customer does not have a compatible browser, applets will not be presented with the proper content. These issues have forced businesses to take a look at server-side Java. Server-side Java solves the problems that applets face. When the code is being executed on the server side, no issues arise with browser compatibility or long download times. The Java appli- cation on the server only sends the client small packets of information, including HTML, WML, XML, and so on, that it can understand. Java servlets are one of the options for server- side Java development. Definition of a Java Servlet Servlets are generic extensions to Java-enabled servers. Their most common use is to extend Web servers, providing a very secure, portable, and easy-to-use replacement for CGI. A servlet is a dynamically loaded module that services requests from a Web server. It runs entirely inside the Java Virtual Machine. Because the servlet is running on the server side, it does not depend on browser compatibility. Figure 2.1 graphically depicts the execution of a Java servlet. Servlet Fundamentals PART I 16 Web Browser Web Server Servlet Request Response FIGURE 2.1 Execution of a Java Servlet. Practical Applications for Java Servlets Servlets can be used for any number of Web-related applications. After you start using servlets, you will find more practical applications for them. The following are three examples that I believe are some of the most important:
  • 39. • Developing e-commerce “store fronts” will become one of the most common uses for Java servlets. A servlet can build an online catalog based on the contents of a database. It can then present this catalog to the customer using dynamic HTML. The customer will choose the items to be ordered, enter the shipping and billing information, and then sub- mit the data to a servlet. When the servlet receives the posted data, it will process the orders and place them in the database for fulfillment. Every one of these processes can easily be implemented using Java servlets. • Servlets can be used to deploy Web sites that open up large legacy systems on the Internet. Many companies have massive amounts of data stored on large mainframe sys- tems. These businesses do not want to re-architect their systems, so they choose to pro- vide inexpensive Web interfaces into them. Because you have the entire JDK at your disposal and security provided by the Web server, you can use servlets to interface into these systems using anything from TCP/IP to CORBA. • Servlets also make very good HTTP-enabled clients to Enterprise Java Bean (EJB) appli- cations. Using servlets as clients to EJB applications creates very secure Web applica- tions that are able to handle very high volumes. These are just a few examples of the power and practicality of using Java servlets. Servlets are very viable options for most Web applications. Java Servlet Alternatives Some alternatives to using Java servlets are CGI, proprietary server APIs, server-side JavaScript, or even Microsoft’s Active Server Pages. All these are viable solutions, but they each have their own set of problems. The following sections examine some of these issues. Common Gateway Interface The Common Gateway Interface (CGI) is one of the most common server-side solutions used to develop Web applications. A CGI application is an independent module that receives requests from a Web server. The application processes the data it receives and sends it back to the server, typically as HTML. The server then sends the data to the browser. CGI has become a standard that is used by most of today’s Web servers. Figure 2.2 shows the interaction between the browser, Web server, and CGI application when you implement this type of solution. Although CGI is a widely used solution to dynamic Web development, it is also a very prob- lematic solution. The following are some of the most common problems with CGI: • A Web server creates a new process every time it receives a CGI request. This results in a slower response time, because the server must create and initialize a new address space for every process. You can also face the problem of running out of processes. Most Servlet Overview and Architecture CHAPTER 2 2 S ERVLET O VERVIEW AND A RCHITECTURE 17
  • 40. servers are configured to run a limited number of processes. If the server runs out, it will not be able to handle the client’s requests. • Although CGI code can be implemented in almost any language, the most common plat- form-independent language is Perl. Perl is very powerful at processing text, but it requires the server to start a new interpreter for every request. This takes longer than starting compiled code and still eats up available processes and resources. • CGI runs in a completely separate process from the Web server. If a client submits a request to a CGI program that terminates before responding to the Web server, the browser has no way of knowing what happened. It just sits there waiting for a response until it times out. Servlet Fundamentals PART I 18 Web Server New CGI1 Process Client Request CGI1 New CGI1 Process Client Request CGI1 New CGI1 Process Client Request CGI1 FIGURE 2.2 The interaction of a CGI solution. Proprietary APIs Many Web servers include APIs that extend their functionality. The most common examples include Netscape’s NSAPI, Microsoft’s ISAPI, and O’Reilly’s Web site API called WSAPI. The problem with these solutions is that they are proprietary. You cannot decide to change servers without porting your code. These APIs are also developed using languages such as C or C++ that can contain memory leaks or core dumps that can crash the Web server. Server-Side JavaScript Server-side JavaScript is another solution for implementing dynamic Web sites. With this solu- tion you embed JavaScript into precompiled HTML pages. By precompiling the Web pages you improve performance, but the only servers that implement server-side JavaScript are Netscape’s Enterprise, FastTrack Servers, and Microsoft’s IIS. This again ties you to a particu- lar vendor. Microsoft’s Active Server Pages Microsoft has developed its own solution to the problem of dynamic Web content: Active Server Pages (ASP). Like Server-side JavaScript, ASP is embedded into HTML pages, but it is
  • 41. also similar to server-side JavaScript in that it is tied to a particular Web server: Microsoft’s Internet Information Server. Some third-party products implement ASP, but you must purchase them separately at additional costs. Reasons to Use Java Servlets Java servlets are one of the most exciting new technologies I have had the opportunity to work with. Servlets are efficient, persistent, portable, robust, extensible, secure, and they are receiv- ing widespread acceptance. If you use them only to replace CGI, you will have saved yourself a lot of time and headache. Servlets solve many common problems you run into when using CGI, and they prove to have a clear advantage over many of the other alternatives. The follow- ing sections discuss some of the advantages offered by servlets. Efficiency A servlet’s initialization code is executed only the first time the Web server loads it. Once the servlet is loaded, it is only a matter of calling a service method to handle new requests. This is a much more efficient technique than loading a completely new executable with every request. Persistency Servlets can maintain state between requests. Once a servlet is loaded, it stays resident in memory while serving incoming requests. A simple example of this is a Vector that holds a list of categories used in an online catalog. When the servlet is initialized, it queries the database for a list of categories and stores these categories in a Vector. As it services requests, the servlet accesses the Vector that holds the categories instead of querying the database again. Taking advantage of the persistent characteristics of servlets can improve your application’s performance drastically. Portability Servlets are developed using Java; therefore, they are portable. This portability enables servlets to be moved to a new operating system without changing the source. You can take code that was compiled on a Windows NT platform and move it to a Solaris box without making any changes. Robustness Because servlets are developed with access to the entire JDK, they are very powerful and robust solutions. Java provides a well-defined exception hierarchy for error handling. It has a garbage collector to prevent problems with memory leaks. In addition, it includes a very large class library that includes network support, file support, database access, distributed object components, security, and many other classes. Servlet Overview and Architecture CHAPTER 2 2 S ERVLET O VERVIEW AND A RCHITECTURE 19
  • 42. Extensibility Another advantage servlets gain by being developed in an object-oriented language such as Java is that they can be extended and polymorphed into new objects that better suit your needs. A good example of this is an online catalog. You might want to display the same catalog search tool at the top of every dynamic page throughout your Web site. You definitely don’t want to add this code to every one of your servlets. So, you implement a base servlet that builds and initializes the search tool and then extend it to display transaction-specific responses. Security Servlets run on the server side, inheriting the security provided by the Web server. Servlets can also take advantage of the Java Security Manager. The Java Servlet Architecture Two packages make up the servlet architecture: javax.servlet and javax.servlet.http. The javax.servlet package contains the generic interfaces and classes that are implemented and extended by all servlets. The java.servlet.http package contains the classes that are extended when creating HTTP-specific servlets. An example of this is a simple servlet that responds using HTML. At the heart of this architecture is the interface javax.servlet.Servlet. It provides the frame- work for all servlets. The Servlet interface defines five methods. The three most important are the init() method, which initializes a servlet; the service() method, which receives and responds to client requests; and the destroy() method, which performs cleanup. All servlets must implement this interface, either directly or through inheritance. It is a very clean object- oriented approach that makes the interface easy to extend. Figure 2.3 shows an object model that gives a high-level view of the servlet framework. GenericServlet and HttpServlet The two main classes are the GenericServlet and HttpServlet classes. The HttpServlet class is extended from GenericServlet. When you are developing your own servlets, you will most likely be extending one of these two classes. Java servlets do not have a main() method, which is why all servlets must implement the javax.servlet.Servlet interface. Every time a server receives a request that points to a servlet it calls that servlet’s service() method. If you decide to extend the GenericServlet class, you must implement the service() method. The GenericServlet.service() method has been defined as an abstract method to force you to follow this framework. The service() method prototype is defined as follows: public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;s Servlet Fundamentals PART I 20
  • 43. FIGURE 2.3 A high-level object model of the servlet framework. The two objects that the service() method receives are ServletRequest and ServletResponse. The ServletRequest object holds the information that is being sent to the servlet, whereas the ServletResponse object is where you place the data you want to send back to the client. Figure 2.4 diagrams the flow of a GenericServlet request. Servlet Overview and Architecture CHAPTER 2 2 S ERVLET O VERVIEW AND A RCHITECTURE 21 <<Interface>> javax.servlet.Servlet init() getServletConfig() service() getServletInfo() destroy() <<Interface>> java.io.Serializable <<Interface>> javax.servlet.ServletConfig getInitParameter() getServletContext() getInitParameterNames() getServletName() javax.servlet.GenericServlet getServletContext() getInitParameter() getInitParameterNames() log() getServletInfo() init() getServletConfig() service() destroy() getServletName() javax.servlet.http.HttpServlet doDelete() doGet() doOptions() doPost() doPut() doTrace() getLastModified() service() BasicServlet
  • 44. FIGURE 2.4 A GenericServlet Request. Unlike the GenericServlet, when you extend HttpServlet, you don’t usually implement the service() method. The HttpServlet class has already implemented it for you. The following is the prototype: protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; When the HttpServlet.service() method is invoked, it reads the method type stored in the request and determines which method to invoke based on this value. These are the methods that you will want to override. If the method type is GET, the service() method will call doGet(). If the method type is POST, it will call doPost(). Five other method types exist; they are discussed in Chapter 3, “Servlet Basics.” All these methods have the same parameter list as the service() method. You might have noticed the different request/response types in the parameter list of the HttpServlet and the GenericServlet classes. The HttpServletRequest and HttpServletResponse classes are just extensions of ServletRequest and ServletResponse with HTTP-specific information stored in them. Figure 2.5 diagrams the flow of a HttpServlet request. Servlet Fundamentals PART I 22 Web Server Client Request Response GenericServlet service()* * abstract method Web Server Client Request Response doDelete() doGet() doOptions() doPost() doPut() doTrace() service() HttpServlet FIGURE 2.5 A HttpServlet Request.
  • 45. Summary In this chapter, you learned about Java servlet basics, practical applications for servlets, servlet alternatives, reasons to use servlets over the alternatives, and the basic architecture of servlets. At this point, you should have a high-level understanding of the flow of a servlet request and what objects are involved. In the next chapter we will look at the life cycle of a servlet. We will also create and dissect a basic servlet. Servlet Overview and Architecture CHAPTER 2 2 S ERVLET O VERVIEW AND A RCHITECTURE 23
  • 47. CHAPTER 3 Servlet Basics IN THIS CHAPTER • The Life Cycle of a Servlet 26 • A Basic Servlet 27 • Dissecting the BasicServlet 29
  • 48. The Life Cycle of a Servlet The life cycle of a Java servlet is a very simple object-oriented design. A servlet is constructed and initialized. It then services zero or more requests until the service that it extends shuts down. At this point the servlet is destroyed and garbage is collected. This design explains why servlets are such a good replacement for CGI: The servlet is loaded only once and it stays resi- dent in memory while servicing requests. The javax.servlet.Servlet interface declares this framework. The Servlet interface defines the life cycle methods. These methods are the init(), the service(), and the destroy() methods. The init() Method The init() method is where the servlet’s life begins. It is called by the server immediately after the servlet is instantiated. It is called only once. In the init() method the servlet creates and initializes the resources that it will be using while handling requests. The init() method’s signature is defined as follows: public void init(ServletConfig config) throws ServletException; The init() method takes a ServletConfig object as a parameter. You should save this object so that it can be referenced later. The most common way of doing this is to have the init() method call super.init() passing it the ServletConfig object. You will also notice that the init() method can throw a ServletException. If, for some rea- son, the servlet cannot initialize the resources necessary to handle requests, the init() method should throw a ServletException. The service() Method The service() method handles all requests sent by a client. It cannot start servicing requests until the init() method has been executed. You will not usually implement this method directly, unless you extend the GenericServlet abstract class. The most common implementation of the service() method is in the HttpServlet class. The HttpServlet class implements the Servlet interface by extending GenericServlet. Its service() method supports standard HTTP/1.1 requests by determining the request type and calling the appropriate method. The signature of the service() method is shown below. public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException; Servlet Fundamentals PART I 26
  • 49. Other documents randomly have different content
  • 50. 1027—The Finger of Suspicion 1028—The Crimson Clew 1029—Nick Carter Down East 1030—The Chain of Clews 1031—A Victim of Circumstances 1032—Brought to Bay 1033—The Dynamite Trap 1034—A Scrap of Black Lace 1035—The Woman of Evil 1036—A Legacy of Hate 1037—A Trusted Rogue 1038—Man Against Man 1039—The Demons of the Night 1040—The Brotherhood of Death 1041—At the Knife’s Point 1042—A Cry for Help 1043—A Stroke of Policy 1044—Hounded to Death 1045—A Bargain in Crime 1046—The Fatal Prescription 1047—The Man of Iron 1048—An Amazing Scoundrel 1049—The Chain of Evidence 1050—Paid with Death 1051—A Fight for a Throne
  • 51. 1052—The Woman of Steel 1053—The Seal of Death 1054—The Human Fiend 1055—A Desperate Chance 1056—A Chase in the Dark 1057—The Snare and the Game 1058—The Murray Hill Mystery 1059—Nick Carter’s Close Call 1060—The Missing Cotton King 1061—A Game of Plots 1062—The Prince of Liars 1063—The Man at the Window 1064—The Red League 1065—The Price of a Secret 1066—The Worst Case on Record 1067—From Peril to Peril 1068—The Seal of Silence 1069—Nick Carter’s Chinese Puzzle 1070—A Blackmailer’s Bluff 1071—Heard in the Dark 1072—A Checkmated Scoundrel 1073—The Cashier’s Secret 1074—Behind a Mask 1075—The Cloak of Guilt 1076—Two Villains in One
  • 52. 1077—The Hot Air Clew 1078—Run to Earth 1079—The Certified Check 1080—Weaving the Web 1081—Beyond Pursuit 1082—The Claws of the Tiger 1083—Driven from Cover 1084—A Deal in Diamonds 1085—The Wizard of the Cue 1086—A Race for Ten Thousand 1087—The Criminal Link 1088—The Red Signal 1089—The Secret Panel 1090—A Bonded Villain 1091—A Move in the Dark 1092—Against Desperate Odds 1093—The Telltale Photographs 1094—The Ruby Pin 1095—The Queen of Diamonds 1096—A Broken Trail 1097—An Ingenious Stratagem 1098—A Sharper’s Downfall 1099—A Race Track Gamble 1100—Without a Clew 1101—The Council of Death
  • 53. 1102—The Hole in the Vault 1103—In Death’s Grip 1104—A Great Conspiracy 1105—The Guilty Governor 1106—A Ring of Rascals 1107—A Masterpiece of Crime 1108—A Blow for Vengeance 1109—Tangled Threads 1110—The Crime of the Camera 1111—The Sign of the Dagger 1112—Nick Carter’s Promise 1113—Marked for Death 1114—The Limited Holdup 1115—When the Trap Was Sprung 1116—Through the Cellar Wall 1117—Under the Tiger’s Claws 1118—The Girl in the Case 1119—Behind a Throne 1120—The Lure of Gold 1121—Hand to Hand 1122—From a Prison Cell 1123—Dr. Quartz, Magician 1124—Into Nick Carter’s Web 1125—The Mystic Diagram 1126—The Hand that Won
  • 54. 1127—Playing a Lone Hand 1128—The Master Villain 1129—The False Claimant 1130—The Living Mask 1131—The Crime and the Motive 1132—A Mysterious Foe 1133—A Missing Man 1134—A Game Well Played 1135—A Cigarette Clew 1136—The Diamond Trail 1137—The Silent Guardian 1138—The Dead Stranger 1140—The Doctor’s Stratagem 1141—Following a Chance Clew 1142—The Bank Draft Puzzle 1143—The Price of Treachery 1144—The Silent Partner 1145—Ahead of the Game 1146—A Trap of Tangled Wire 1147—In the Gloom of Night 1148—The Unaccountable Crook 1149—A Bundle of Clews 1150—The Great Diamond Syndicate 1151—The Death Circle
  • 55. 1152—The Toss of a Penny 1153—One Step Too Far 1154—The Terrible Thirteen 1155—A Detective’s Theory 1156—Nick Carter’s Auto Trail 1157—A Triple Identity 1158—A Mysterious Graft 1159—A Carnival of Crime 1160—The Bloodstone Terror 1161—Trapped in His Own Net 1162—The Last Move in the Game 1163—A Victim of Deceit 1164—With Links of Steel 1165—A Plaything of Fate 1166—The Key Ring Clew 1167—Playing for a Fortune 1168—At Mystery’s Threshold 1169—Trapped by a Woman 1170—The Four Fingered Glove 1171—Nabob and Knave 1172—The Broadway Cross 1173—The Man Without a Conscience 1174—A Master of Deviltry 1175—Nick Carter’s Double Catch
  • 56. 1176—Doctor Quartz’s Quick Move 1177—The Vial of Death 1178—Nick Carter’s Star Pupils 1179—Nick Carter’s Girl Detective 1180—A Baffled Oath 1181—A Royal Thief 1182—Down and Out 1183—A Syndicate of Rascals 1184—Played to a Finish 1185—A Tangled Case 1186—In Letters of Fire 1187—Crossed Wires 1188—A Plot Uncovered 1189—The Cab Driver’s Secret 1190—Nick Carter’s Death Warrant 1191—The Plot that Failed 1192—Nick Carter’s Masterpiece 1193—A Prince of Rogues 1194—In the Lap of Danger 1195—The Man from London 1196—Circumstantial Evidence 1197—The Pretty Stenographer Mystery 1198—A Villainous Scheme 1199—A Plot Within a Plot
  • 57. 1200—The Elevated Railroad Mystery 1201—The Blow of a Hammer 1202—The Twin Mystery 1203—The Bottle With the Black Label 1204—Under False Colors 1205—A Ring of Dust 1206—The Crown Diamond 1207—The Blood-red Badge 1208—The Barrel Mystery 1209—The Photographer’s Evidence 1210—Millions at Stake 1211—The Man and His Price 1212—A Double-Handed Game 1213—A Strike for Freedom 1214—A Disciple of Satan 1215—The Marked Hand 1216—A Fight with a Fiend 1217—When the Wicked Prosper 1218—A Plunge into Crime 1219—An Artful Schemer 1220—Reaping the Whirlwind 1221—Out of Crime’s Depths 1222—A Woman at Bay 1223—The Temple of Vice
  • 58. 1224—Death at the Feast 1225—A Double Plot 1226—In Search of Himself 1227—A Hunter of Men 1228—The Boulevard Mutes 1229—Captain Sparkle, Pirate 1230—Nick Carter’s Fall 1231—Out of Death’s Shadow 1232—A Voice from the Past 1233—Accident or Murder? 1234—The Man Who Was Cursed 1235—Baffled, But Not Beaten 1236—A Case Without a Clew 1237—The Demon’s Eye 1238—A Blindfold Mystery 1239—Nick Carter’s Swim to Victory 1240—A Man to Be Feared 1241—Saved by a Ruse 1242—Nick Carter’s Wildest Chase 1243—A Nation’s Peril 1244—The Rajah’s Ruby 1245—The Trail of a Human Tiger 1246—The Disappearing Princess 1247—The Lost Chittendens 1248—The Crystal Mystery
  • 59. 1249—The King’s Prisoner 1250—Talika, the Geisha Girl 1251—The Doom of the Reds 1252—The Lady of Shadows 1253—The Mysterious Castle 1254—The Senator’s Plot 1255—A Submarine Trail 1256—A War of Brains 1257—Pauline—A Mystery 1258—The Confidence King 1259—A Chase for Millions 1260—Shown on the Screen 1261—The Streaked Peril 1262—The Room of Mirrors 1263—A Plot for an Empire 1264—A Call on the Phone In order that there may be no confusion, we desire to say that the books listed below will be issued during the respective months to New York City and vicinity. They may not reach the readers at a distance promptly, on account of delays in transportation. To be published in July, 1929. 1265—Nick Carter’s Convict Client 1266—The House of the Yellow Door 1267—Nick Carter’s Round-up
  • 60. To be published in August, 1929. 1268—A Masterly Trick 1269—For a Madman’s Millions To be published in September, 1929. 1270—The Four Hoodoo Charms 1271—The Man in the Auto To be published in October, 1929. 1272—The Jeweled Mummy 1273—The Vanishing Emerald To be published in November, 1929. 1274—A Live Wire Clue 1275—The Vampire’s Trail To be published in December, 1929. 1276—The Crimson Flash 1277—The Vanishing Heiress
  • 61. BOOKS THAT NEVER GROW OLD Alger Series Clean Adventure Stories for Boys The Most Complete List Published The following list does not contain all the books that Horatio Alger wrote, but it contains most of them, and certainly the best. Horatio Alger is to boys what Charles Dickens is to grown-ups. His work is just as popular to-day as it was years ago. The books have a quality, the value of which is beyond computation. There are legions of boys of foreign parents who are being helped along the road to true Americanism by reading these books which are so peculiarly American in tone that the reader cannot fail to absorb some of the spirit of fair play and clean living which is so characteristically American. In this list will be included certain books by Edward Stratemeyer, Oliver Optic, and other authors who wrote the Alger type of stories, which are equal in interest and wholesomeness with those written by the famous author after whom this great line of books for boys is named. ALL TITLES ALWAYS IN PRINT By HORATIO ALGER, Jr. 1—Driven from Home 2—A Cousin’s Conspiracy 3—Ned Newton 4—Andy Gordon 5—Tony, the Tramp
  • 62. 6—The Five Hundred Dollar Check 7—Helping Himself 8—Making His Way 9—Try and Trust 10—Only an Irish Boy 11—Jed, the Poorhouse Boy 12—Chester Rand 13—Grit, the Young Boatman of Pine Point 14—Joe’s Luck 15—From Farm Boy to Senator 16—The Young Outlaw 17—Jack’s Ward 18—Dean Dunham 19—In a New World 20—Both Sides of the Continent 21—The Store Boy 22—Brave and Bold 23—A New York Boy 24—Bob Burton 25—The Young Adventurer 26—Julius, the Street Boy 27—Adrift in New York 28—Tom Brace 29—Struggling Upward
  • 63. 30—The Adventures of a New York Telegraph Boy 31—Tom Tracy 32—The Young Acrobat 33—Bound to Rise 34—Hector’s Inheritance 35—Do and Dare 36—The Tin Box In order that there may be no confusion, we desire to say that the books listed below will be issued during the respective months in New York City and vicinity. They may not reach the readers at a distance promptly, on account of delays in transportation. To be published in July, 1929. 37—Tom, the Bootblack 38—Risen from the Ranks To be published in August, 1929. 39—Shifting for Himself 40—Wait and Hope To be published in September, 1929. 41—Sam’s Chance 42—Striving for Fortune To be published in October, 1929. 43—Phil, the Fiddler 44—Slow and Sure
  • 64. To be published in November, 1929. 45—Walter Sherwood’s Probation 46—The Trials and Triumphs of Mark Mason 47—The Young Salesman To be published in December, 1929. 48—Andy Grant’s Pluck 49—Facing the World
  • 65. NOW IN PRINT By EDWARD STRATEMEYER 98—The Last Cruise of The Spitfire 99—Reuben Stone’s Discovery 100—True to Himself 101—Richard Dare’s Venture 102—Oliver Bright’s Search 103—To Alaska for Gold 104—The Young Auctioneer 105—Bound to Be an Electrician 106—Shorthand Tom 108—Joe, the Surveyor 109—Larry, the Wanderer 110—The Young Ranchman 111—The Young Lumberman 112—The Young Explorers 113—Boys of the Wilderness 114—Boys of the Great Northwest 115—Boys of the Gold Field 116—For His Country 117—Comrades in Peril 118—The Young Pearl Hunters 119—The Young Bandmaster 121—On Fortune’s Trail
  • 66. 122—Lost in the Land of Ice 123—Bob, the Photographer
  • 67. By OLIVER OPTIC 124—Among the Missing 125—His Own Helper 126—Honest Kit Dunstable 127—Every Inch a Boy 128—The Young Pilot 129—Always in Luck 130—Rich and Humble 131—In School and Out 133—Work and Win 135—Haste and Waste 136—Royal Tarr’s Pluck 137—The Prisoners of the Cave 138—Louis Chiswick’s Mission 139—The Professor’s Son 140—The Young Hermit 141—The Cruise of The Dandy 142—Building Himself Up 143—Lyon Hart’s Heroism 144—Three Young Silver Kings 145—Making a Man of Himself 146—Striving for His Own 147—Through by Daylight 148—Lightning Express
  • 68. 149—On Time 150—Switch Off 151—Brake Up 152—Bear and Forbear 153—The “Starry Flag” 154—Breaking Away 155—Seek and Find 156—Freaks of Fortune 157—Make or Break 158—Down the River 159—The Boat Club 160—All Aboard 161—Now or Never 162—Try Again 163—Poor and Proud 164—Little by Little 165—The Sailor Boy 166—The Yankee Middy 167—Brave Old Salt
  • 69. 175—Fighting for Fortune By Roy Franklin 176—The Young Steel Worker By Frank H. MacDougal 177—The Go-ahead Boys By Gale Richards 178—For the Right By Roy Franklin 179—The Motor Cycle Boys By Donald Grayson 180—The Wall Street Boy By Allan Montgomery 181—Stemming the Tide By Roy Franklin 182—On High Gear By Donald Grayson 183—A Wall Street Fortune By Allan Montgomery 184—Winning by Courage By Roy Franklin 185—From Auto to Airship By Donald Grayson 186—Camp and Canoe By Remson Douglas 187—Winning Against Odds By Roy Franklin 188—The Luck of Vance Sevier By Frederick Gibson 189—The Island Castaway By Roy Franklin 190—The Boy Marvel By Frank H. MacDougal 191—A Boy With a Purpose By Roy Franklin 192—The River Fugitives By Remson Douglas
  • 70. READ When you want real recreation in your leisure hours, read! Read the Street & Smith Novels! They are the cheapest and the most interesting reading matter published in America to-day. No jazz—no sex—just big, clean, interesting books. There are hundreds of different titles, among which you will find a lot of exactly the sort of reading you want. So, when you get tired of rolling around in your Lady Lizzie or listening to the blah-blah of your radio, hie yourself to the nearest news dealer, grab off a copy of a good detective, adventure or love story, and then READ! Read the Street & Smith Novels. Catalog sent upon request. Street & Smith Corporation 79 Seventh Avenue New York City
  • 71. Welcome to Our Bookstore - The Ultimate Destination for Book Lovers Are you passionate about books and eager to explore new worlds of knowledge? At our website, we offer a vast collection of books that cater to every interest and age group. From classic literature to specialized publications, self-help books, and children’s stories, we have it all! Each book is a gateway to new adventures, helping you expand your knowledge and nourish your soul Experience Convenient and Enjoyable Book Shopping Our website is more than just an online bookstore—it’s a bridge connecting readers to the timeless values of culture and wisdom. With a sleek and user-friendly interface and a smart search system, you can find your favorite books quickly and easily. Enjoy special promotions, fast home delivery, and a seamless shopping experience that saves you time and enhances your love for reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookgate.com