0% found this document useful (0 votes)
6 views

Developing Java Servlets 2nd Edition James Goodwill - The complete ebook version is now available for download

The document promotes various Java-related ebooks available for download on ebookgate.com, including titles like 'Developing Java Servlets' and 'Murach's Java Servlets and JSP'. It provides links to each book and highlights the availability of instant digital formats such as PDF, ePub, and MOBI. Additionally, it outlines the contents and structure of the 'Developing Java Servlets' book, detailing its focus on servlet fundamentals and JSP applications.

Uploaded by

badergardojm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Developing Java Servlets 2nd Edition James Goodwill - The complete ebook version is now available for download

The document promotes various Java-related ebooks available for download on ebookgate.com, including titles like 'Developing Java Servlets' and 'Murach's Java Servlets and JSP'. It provides links to each book and highlights the availability of instant digital formats such as PDF, ePub, and MOBI. Additionally, it outlines the contents and structure of the 'Developing Java Servlets' book, detailing its focus on servlet fundamentals and JSP applications.

Uploaded by

badergardojm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Get the full ebook with Bonus Features for a Better Reading Experience on ebookgate.

com

Developing Java Servlets 2nd Edition James


Goodwill

https://ebookgate.com/product/developing-java-servlets-2nd-
edition-james-goodwill/

OR CLICK HERE

DOWLOAD NOW

Download more ebook instantly today at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Apache Jakarta Tomcat 1st Edition James Goodwill

https://ebookgate.com/product/apache-jakarta-tomcat-1st-edition-james-
goodwill/

ebookgate.com

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/

ebookgate.com

Java 2 micro edition Java in small things James White

https://ebookgate.com/product/java-2-micro-edition-java-in-small-
things-james-white/

ebookgate.com

Developing a Dream Destination James Mak

https://ebookgate.com/product/developing-a-dream-destination-james-
mak/

ebookgate.com
The Java Language Specification Third Edition James
Gosling

https://ebookgate.com/product/the-java-language-specification-third-
edition-james-gosling/

ebookgate.com

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/

ebookgate.com

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/

ebookgate.com

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/

ebookgate.com

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/
ebookgate.com

Developing Java
Servlets
James Goodwill

800 East 96th St., Indianapolis, Indiana, 46240 USA


PUBLISHER
Developing Java™ Servlets, Paul Boger
Second Edition EXECUTIVE EDITOR
Copyright © 2001 by Sams Publishing Michael Stephens

All rights reserved. No part of this book shall be reproduced, stored in a ACQUISITIONS EDITOR
retrieval system, or transmitted by any means, electronic, mechanical, photo- Carol Ackerman
copying, recording, or otherwise, without written permission from the pub-
DEVELOPMENT EDITOR
lisher. No patent liability is assumed with respect to the use of the information
Tiffany Taylor
contained herein. Although every precaution has been taken in the preparation
of this book, the publisher and author assume no responsibility for errors or MANAGING EDITOR
omissions. Nor is any liability assumed for damages resulting from the use of Matt Purcell
the information contained herein.
PROJECT EDITOR
International Standard Book Number: 0-672-32107-6 Christina Smith
Library of Congress Catalog Card Number: 00-111799
COPY EDITOR
Printed in the United States of America Cynthia Fields
First Printing: June 2001 INDEXER
04 03 02 01 4 3 2 1 Erika Millen

PROOFREADER
Trademarks Benjamin Berg
All terms mentioned in this book that are known to be trademarks or service
marks have been appropriately capitalized. Sams Publishing cannot attest to TECHNICAL EDITOR
the accuracy of this information. Use of a term in this book should not be Rob Tiffany
regarded as affecting the validity of any trademark or service mark.
TEAM COORDINATOR
Warning and Disclaimer Lynne Williams
Every effort has been made to make this book as complete and as accurate as INTERIOR DESIGNER
possible, but no warranty or fitness is implied. The information provided is on Anne Jones
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- COVER DESIGNER
ing from the information contained in this book. 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
vi
DEVELOPING JAVA SERVLETS, SECOND EDITION

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
vii
CONTENTS

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
viii
DEVELOPING JAVA SERVLETS, SECOND EDITION

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
ix
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
x
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
xi
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
xii
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
xiii
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
xiv
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
xv
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
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.
2
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.
3
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.
4
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.
5
INTRODUCTION

Appendix G, “WMLScript”
Appendix G describes the libraries and functions used in WMLScript.
Web Applications and the CHAPTER

1
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


8
DEVELOPING JAVA SERVLETS

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.
Web Applications and the Model View Controller (MVC) Design Pattern
9
CHAPTER 1

Application Server 1

WEB APPLICATIONS
DESIGN PATTERN
AND THE MVC
3. EJB/
2. Servlet BEAN
(Controller)
EJB/
1. BEAN
Web Client Web 4.
Server DBMS
6.
EJB/
JSP BEAN
5.
(View)
EJB/
BEAN

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.
10
DEVELOPING JAVA SERVLETS

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.
Web Applications and the Model View Controller (MVC) Design Pattern
11
CHAPTER 1

In the rest of this text we will study servlets and JSPs in the context of this model. We will 1
examine how servlets and JSPs work separately and then we will complete the text by combin-

WEB APPLICATIONS
DESIGN PATTERN
AND THE MVC
ing what we have learned into Web application case studies that implement the MVC.
PART
Servlet Fundamentals
I
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 Overview and CHAPTER

2
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


Servlet Fundamentals
16
PART I

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.

Request
Servlet
Response

Web Browser
Web Server

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:
Servlet Overview and Architecture
17
CHAPTER 2

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

OVERVIEW AND
vide inexpensive Web interfaces into them. Because you have the entire JDK at your

ARCHITECTURE
disposal and security provided by the Web server, you can use servlets to interface into

SERVLET
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 Fundamentals
18
PART I

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.

Request CGI1
Client New CGI1 Process
Request CGI1
Client New CGI1 Process
Request CGI1
Client New CGI1 Process
Web Server

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
Servlet Overview and Architecture
19
CHAPTER 2

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 2
CGI, and they prove to have a clear advantage over many of the other alternatives. The follow-

OVERVIEW AND
ARCHITECTURE
ing sections discuss some of the advantages offered by servlets.

SERVLET
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 Fundamentals
20
PART I

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 Overview and Architecture
21
CHAPTER 2

<<Interface>> <<Interface>> <<Interface>>


javax.servlet.Servlet javax.servlet.ServletConfig java.io.Serializable

init() getInitParameter()
getServletConfig() getServletContext()
service() getInitParameterNames()
getServletInfo() getServletName()
destroy()

javax.servlet.GenericServlet

getServletContext() 2
getInitParameter()
getInitParameterNames()

OVERVIEW AND
ARCHITECTURE
log()

SERVLET
getServletInfo()
init()
getServletConfig()
service()
destroy()
getServletName()

javax.servlet.http.HttpServlet

doDelete()
doGet()
doOptions()
doPost()
doPut()
doTrace()
getLastModified()
service()

BasicServlet

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 Fundamentals
22
PART I

Request GenericServlet
Client
Response service()*

Web Server

* abstract method

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.

HttpServlet
doDelete()
Request doGet()
Client doOptions()
service()
Response doPost()
doPut()
Web Server
doTrace()

FIGURE 2.5
A HttpServlet Request.
Servlet Overview and Architecture
23
CHAPTER 2

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

OVERVIEW AND
ARCHITECTURE

SERVLET
Servlet Basics CHAPTER

3
IN THIS CHAPTER
• The Life Cycle of a Servlet 26

• A Basic Servlet 27

• Dissecting the BasicServlet 29


Servlet Fundamentals
26
PART I

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 Basics
27
CHAPTER 3

The service() method implements a request and response paradigm. The ServletRequest
object contains information about the service request, encapsulating information provided by
the client. The ServletResponse object contains the information returned to the client.

The destroy() Method


This method signifies the end of a servlet’s life. When a service is being shut down it calls the
servlet’s destroy() method. This is where any resources that were created in the init()
method should be cleaned up. If you have an open database connection, you should close it
here. This is also a good place to save any persistent information that will be used the next
time the servlet is loaded. The signature of destroy() is very simple, but I have displayed it
here just to complete the picture:
public void destroy();

A Basic Servlet
In this section, we are going to look at building a very basic servlet. Its purpose will be to ser-
vice a request and respond with the request method used by the client. We will take a quick
look at the servlet’s source code, the steps involved in compiling and installing the servlet, and 3
the HTML necessary to invoke the servlet. After you have the servlet compiled, you will need

SERVLET BASICS
to refer to Appendix A, “Web Applications and Configuring the Servlet Engine,” for instruc-
tions on how to configure the servlet engine, which actually runs your servlets.

The BasicServlet Source


Listing 3.1 contains the source code for this example. You can find the following source listing
on this book’s Web site. If you have the time, it is probably best to type the first few examples
yourself. This will help you become familiar with the basic parts of servlets. As you type or
browse over this listing, feel free to look up the referenced classes in Appendices A and B.

LISTING 3.1 BasicServlet.java Displays the REQUEST_METHOD used by the Client

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class BasicServlet extends HttpServlet {

public void init(ServletConfig config)


throws ServletException {
Servlet Fundamentals
28
PART I

LISTING 3.1 Continued


// Always pass the ServletConfig object to the super class
super.init(config);
}

//Process the HTTP Get request


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType(“text/html”);
PrintWriter out = response.getWriter();

out.println(“<html>”);
out.println(“<head><title>BasicServlet</title></head>”);
out.println(“<body>”);

// Prints the REQUEST_METHOD sent by the client


out.println(“Your request method was “ + request.getMethod()
+ “\n”);

out.println(“</body></html>”);
out.close();
}

//Process the HTTP Post request


public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType(“text/html”);
PrintWriter out = response.getWriter();

out.println(“<html>”);
out.println(“<head><title>BasicServlet</title></head>”);
out.println(“<body>”);

// Prints the REQUEST_METHOD sent by the client


out.println(“Your request method was “ + request.getMethod()
+ “\n”);

out.println(“</body></html>”);
out.close();
}
Servlet Basics
29
CHAPTER 3

LISTING 3.1 Continued


//Get Servlet information
public String getServletInfo() {

return “BasicServlet Information”;


}
}

Dissecting the BasicServlet


Now that you have had a chance to look over the source of the BasicServlet, let’s take a
closer look at each of its integral parts. We will examine where the servlet fits into the JSDK
framework, the methods that the servlet implements, and the objects being used by the servlet.

Where Does the BasicServlet Fit into the Servlet


Framework?
The first thing we are going to look at is where the BasicServlet fits into the servlet frame-
work. This servlet extends the HttpServlet class. The HttpServlet class is an abstract class
3

SERVLET BASICS
that simplifies writing HTTP servlets. It extends the GenericServlet class and provides the
functionality for handling the HTTP protocol-specific requests. The BasicServlet overrides
four of its inherited methods. Figure 3.1 shows where the BasicServlet fits into this hierarchy.

<<Interface>>
<<Interface>>
javax.servlet.ServletConfig
javax.servlet.Servlet <<Interface>>
java.io.Serializable

javax.servlet.GenericServlet

javax.servlet.http.HttpServlet

BasicServlet

FIGURE 3.1
The BasicServlet depicted in the Servlet Framework.
Servlet Fundamentals
30
PART I

The Methods Overridden by the BasicServlet


The following four methods are overridden by the BasicServlet:
• init()

• doGet()

• doPost()

• getServletInfo()

Let’s take a look at each of these methods in more detail.

The init() Method


The BasicServlet defines a very simple implementation of the init() method. It takes the
ServletConfig object that is passed to it and passes it to its parent’s init() method, which
stores the object for later use. The parent that actually holds on to the ServletConfig object is
the GenericServlet. The GenericServlet provides your servlet, through inheritance, with
methods to access the ServletConfig object. The code that performs this action follows:
super.init(config);

This is a very important step. If you do not do this, you must hold the ServletConfig object
yourself. We will discuss the significance of the ServletConfig object in later chapters.
You will also notice this implementation of the init() method does not create any resources.
This is why the BasicServlet does not implement a destroy() method.

The doGet() and doPost() Methods


The BasicServlet’s doGet() and doPost() methods are identical. The only difference is the
requests they service. The doGet() method handles GET requests and the doPost() method
handles POST requests.
Both of these methods receive HttpServletRequest and HttpServletResponse objects. These
objects encapsulate the request/response paradigm. The HttpServletRequest contains infor-
mation sent from the client, and the HttpServletResponse contains information that will be
sent back to the client. The first executed line of these methods follows:
response.setContentType(“text/html”);

This method sets the content type for the response. You can set this response property only
once. You must set this property before you can begin writing to a Writer or an OutputStream.
In our example, we are using a PrintWriter and setting the response type to text/html.
The next thing to do is get the PrintWriter. This is accomplished by calling the
ServletResponses’s getWriter() method. This is done in the following line of code:

PrintWriter out = response.getWriter();


Servlet Basics
31
CHAPTER 3

Now you have a reference to an object that will allow you to write HTML text that will be sent
back to the client in the HttpServletResponse object. The next few lines of code show how
this is done:
out.println(“<html>”);
out.println(“<head><title>BasicServlet</title></head>”);
out.println(“<body>”);

// Prints the REMOTE_ADDR sent by the client in the request


out.println(“Your request method was “ + request.getMethod()
+ “\n”);

out.println(“</body></html>”);
out.close();

This is a very straightforward method of sending HTML text back to the client. You simply
pass to the PrintWriter’s println() method the HTML text you want included in the
response and close the stream. The only thing that you might have a question about is the fol-
lowing few lines:
// Prints the REMOTE_ADDR sent by the client in the request
out.println(“Your request method was “ + request.getMethod()
3
+ “\n”);

SERVLET BASICS
This code takes advantage of the information sent from the client. It calls the
HttpServletRequest’s getMethod() method, which returns the HTTP method with which the
request was made. The HttpServletRequest object holds HTTP-protocol specific header
information.

The getServletInfo() Method


The getServletInfo() method is like the applet’s getAppletInfo() method. It can be used to
provide version, copyright, author, and any other information about itself.

Summary
In this chapter, we were finally able to start examining some servlet code. We looked at the life
cycle of a servlet. We also dissected a basic servlet, which gave us a view of each integral part
of a servlet.
You should now be able to create your own servlets. You should also have a basic understand-
ing of the servlet life cycle and where your servlets will fit into the Java servlet framework.
In the next chapter we will take a look at Web applications and how to leverage them to deploy
servlet applications.
Exploring the Variety of Random
Documents with Different Content
14 lb 7 lb 4 lb 2 lb 1 lb 8 oz 4 oz
No. I R S 169. Best Quality Domestic Scale, with Tray
and Weights, brass caps over bearings, government
stamped.
To weigh 7 lbs. 14 lbs. 28 lbs.
With weights 4 lbs. to ¼ oz. 7 lbs. to ¼ oz. 14 lbs. to ¼ oz.
21/6 24/9 29/6
No. I R S 170. Cheap quality, unstamped, with ring weights.
7 lbs. 14 lbs. 28 lbs.
With weights 4 lbs. to ¼ oz. 7 lbs. to ¼ oz. 14 lbs. to ¼ oz.
12/6 15/0 20/9

No. I R 178 S. French Pattern Scales with


two Brass Pans as shown, hardened steel
centres and bearings and stamped.
To Weigh 1 lb. 2 lbs. 4 lbs.
With Brass 1 lb. to ¼ oz. 2 lbs. to ¼ oz. 4 lbs. to ¼ oz.
Weights 16/2 20/6 27/3
W. & T Avery Ltd.
No. I R 367. Letter Balance. Very Accurate
and Sensitive Brass Scale, mounted on
Mahogany Base. No loose weights. Postal
rates marked on the beam. To weigh 8
ozs., 21/6; 16 ozs. 26/3
No. 2
SALTER’S
IMPROVED
SPRING BALANCE
PATENT
No. I R 2.
Spring Balance,
with hook.
To weigh Price.
20 × ¼ lb. 3/3
25 × ½ lb. 1/4
50 × ½ lb. 5/9
50 × 1 lb. 2/11

HUGHES
BABY WEIGHER
No. I R 222. New Pattern Baby Balance
with close wicker Scale. Enamelled Dial,
Glass Front, and Nickel Rim. Price 19/6.
No. I R 14.
Pocket Parcel Post
Balance. To weigh
11 lbs. × 1 lb. Price
2/8 each.
CLASS III
SALTER’S
SPRING BALANCE
No. I R 20.
Circular Balance.
56 lbs. × ¼ lb., 13/6
100 lbs. × ½ lb., 11/6
200 lbs. × 1 lb., 11/9
250 lbs. × 1 lb., 15/3
300 lbs. × 1 lb., 18/9
No. I R 20T.
Circular Balance,
stamped for trade use.
100 lbs. × ½ lb., 17/0
200 lbs. × 1 lb., 18/6
250 lbs. × 1 lb., 26/9
SALTER’S
FAMILY SCALE
POSTAL PARCEL BALANCE Salter’s Family Balance, with
SALTER’S
Tin pan.
11 LBS BY 1 Oz.
No. I R 35. Parcel Post To weigh Price
Balance, Brass Scale Plate. 7 lbs. × ½ oz. 7/4
Enamelled Dial. To weigh— 14 lbs. × 1 oz. 7/9
11 lbs. × 1 oz. 6/9 28 lbs. × 2 oz. 8/9
11 lbs. × ½ oz. 9/6 25 lbs. × 1 oz. 12/9
No. I R 45T. Counter
Balance, stamped for trade
use.
To weigh 20 lbs. × 1 oz.
Price 19/6
SALTER’S
FAMILY SCALE
No. I R 221. Spring Balance
for Weighing Infants. With
wicker scale. To weigh—
28 lbs. × 2 oz. 13/6
25 lbs. × 1 oz. 17/3

No. I R 649. The Avery Baby Scales, with Strong


Basket or Cradle. Very sensitive, with hardened
steel knife edges and bearings. Complete with
weights, 14 lbs. to ½ oz. Capacity 20 lbs. Price
52/0
No. I R 3119. Standard Personal Weighing
Machine, for Bathroom. Weighs up to 24
stone. Size of Platform, 10½ in. ×
13½ in. Packed in Case, with Instructions
for putting together. 22/6
No. 1047. Similar to above, best quality
with hardened Steel Bearings and
superior finish. 43/9
Stained Wood Stand for ditto, 17/3
Height Measuring Standard, to fit on
Stand, 13/0
HUGHES’
FAMILY SCALE
No. 48
TO WEIGHT 20 LBS BY 1 OZ
No. I R 48. Hughes’ Family
Balance. Oblong Scale Pan,
To weigh 20 lbs. × 1 oz. 4/11
,, 28 lbs. × 2 oz. 5/6
[1086]

WEIGHING MACHINES (PERSONAL), FOR


BATHROOMS, ETC.
W & T. AVERY Ld.
No. I R 1065.
Personal Weighing Machine, suitable for
Private Houses, Bathrooms, Schools and
Consulting-Rooms. Japanned Green. Price,
66/6
Fitted with Boxwood Measuring Standard.
77/9
Fitted with Nickel-plated Measuring Standard
and Nickel-plated Steelyard. 90/9
If Japanned White, 8/6 extra to order.
Weighs up to 24 stone × 1 oz.
No. I R S 137.
Improved Personal Weighing
Machine, specially suited for
Physicians’ Consulting-Rooms.
Nickel-plated Brass Steelyard,
Carpeted Platform.
Size of Platform, 14 in. × 14 in.
Capacity, 24 stone.
Price 52/6
The New Jaraso Personal Weighing
Machine. Your weight instantly recorded
by merely standing on the platform, when
it can easily be seen reflected in the
mirror. Capacity, 20 stone. Size, 10½ × 7
× 8 in. high. Can be used for other
purposes equally well. Its weight and size
render it suitable for travelling or for use
in very limited spaces, and it can be kept
under the bed “if desired.” 22/6
The Jaraso de Luxe Personal Weighing
Machine, beautifully encased in polished
Mahogany or Oak, with covered Platform.
Price 55/6
The Jaraso de Luxe, inlaid Mahogany.
Price 59/6
Cork Platform Mats, for use with ordinary
Jaraso, 2/6 each. Fibre Travelling Case,
4/9 each. Willesden Canvas Travelling
Case, with spring lock, 12/6 Leather
Travelling Case, with spring lock, 25/6
No. I R 138.
Superior Personal Weighing Machine,
Polished Oak Case, with Carpeted
Platform and Nickel-plated Mounts and
Steelyard. Best quality Steel Bearing. Very
accurate, weighs up to 32 stone × 1 oz.
Price, with 7 ft Sliding Boxwood Height
Standard, £9 15. Sent direct, carriage
paid to nearest Railway Station in
England.
SALTERS
WEIGHING MACHINE
TO WEIGH
20 STONE BY 1LB
The Compact Improved Personal
Weighing Machine, with sloping
white Enamelled Dial with glass
cover. Machine Japanned White
and Gold with Cork-covered
Platform. To weigh 20 stone × 1
lb. Price 65/0
No. 1054
Chippendale Mahogany Arm-chair
Weighing Machine. Upholstered in best
dark Morocco Leather, with patent Ticket
Registering Steelyard. £25 17 6 (including
500 tickets). Sent direct, carriage paid to
nearest Railway Station in England.
W & T AVERY Ld
No. 1073. The Maison Personal
Weighing Machine (no loose
Weights), weighs up to 24 stone ×
1 oz. Japanned Green finish, and
Gunmetal Beam. Price, 90/9
No. 1056.
The Carlton Personal Weighing Machine.
Chippendale Mahogany Frame and Stand,
Morocco Leather Seat. No loose Weights.
To Weigh up to 24 stone × 2 oz. £10 17 6
Sent direct, carriage paid to nearest
Railway Station in England.
SALTERS
WEIGHING MACHINE
TO WEIGH
20 STONE BY 1LB
The Albion Personal Weighing
Machine. Japanned White and
Gold, with Glass-covered White
Enamelled Dial, Cork-covered
Platform. To weigh 20 stone × 1
lb. Price 67/6
[1087]

WEIGHING MACHINES, DINNER WAGGONS,


ETC.
No. I R 1. Dinner Waggon.
Very strongly made of Solid Fumed Oak
throughout, with easy running Rubber-Tyred
Castors. Height, 36 in. Size of Trays (inside),
29 in. × 19 in.
Price £4 5 9
Ditto, with Leather-Tyred Castors, £4 9 6
Solid Mahogany with Rubber-Tyred Castors,
£4 10 9
Ditto, with Leather-Tyred Castors, £4 14 6
No. I R 10.
The “Sterling” Vegetable Slice for all
kinds of Vegetables and Fruits, will cut
any thickness and is easily cleaned.
Price 5/11

WAFER IRON.
For Making Wafer Cakes.
7½ in. 3/6
No. I R 1717. Vegetable or
Cucumber Slice, with adjusting
screw, 2/3
No. I R 1716. Cheaper pattern, not
adjustable, 0/10½ and 1/1 each.

No. I R 2673. Vegetable and Fruit


Slicer. Strong Cast-Iron body,
Tinned all over and fitted with
Steel Cutters to cut various
thicknesses. 5/3 each.
Bottle Carrier. Made of
strong Tinned Iron, strongly
riveted. Will fold up flat. To
take 4 bottles, 2/3; 6, 3/4;
8, 4/6

H&S
L
Vegetable Scoops. Plain Round,
0/8½; do. Oval, 0/10½; Fancy
Oval, 1/1. Vegetable Pressers,
0/7½; Peeler, 0/4½ and 1/1; Knife
(French pattern), 0/7½; ditto
(English pattern), 1/0
No. I R 5072. Sack or Luggage Truck.
Nos. 1 2 3 4
ft. in. ft. in. ft. in. ft. in.
Length over all 34 37 41 46
Width at Handles 1 2½ 1 4½ 1 6 1 7½
Width at Wheels 1 4½ 1 5½ 1 7½ 1 10½
Diameter of Wheels 0 7 08 09 09
Projection of Shoe 0 3½ 0 4½ 0 6 07
Prices 10/3 12/0 13/3 15/6
Rubber Tyres Extra. Prices on application.
No. I R 132.
W. & T AVERY Ltd
BIRMINGHAM
The Colonial Light Platform Weigher.
Light, Portable Platform Weighing Machine, made
entirely of Iron, excepting the Steelyard, which is
Gun-metal. With Knife-edges and Bearings of
hardened Steel. Fitted with Backrail for Sacks,
etc., and mounted on four Wheels, with Frame
constructed so as to give a strong double bearing
to the Axles.
To Weigh 4 cwt. 7 cwt.
Platform-Length 20 26 in.
,, Width 17 19 in.
98/3 130/0
Sent direct, carriage paid to nearest station in England.
Made with four
separate Bins,
which enables the
various kinds of
vegetables to be
kept apart, and
prevents them from
being crowded
together and
becoming stale.

THE HYGIENIC VEGETABLE RACK.


Sizes. High. Wide. Deep. Price.
No. 0 24 in. 18 in. 8 in. 5/0
No. 1 30 in. 18 in. 8½ in. 6/8
No. 2 36 in. 24 in. 12 in. 10/6
Household Folding Wash Bench.
Any Wringer up to 16 in. can be
placed on the Standard.

The Bench is made of hard wood,


and so constructed that when it is
not in use it can be folded up and
put away in a very small space.
Fitted with stand on both sides to
take two tubs. Price 9/6
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

You might also like