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

Developing Java Servlets 2nd Edition James Goodwill download

Ebook

Uploaded by

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

Developing Java Servlets 2nd Edition James Goodwill download

Ebook

Uploaded by

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

Developing Java Servlets 2nd Edition James

Goodwill pdf download

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

Get Instant Ebook Downloads – Browse 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;
Another Random Document on
Scribd Without Any Related Topics
him from it, but without effect. He sold it, and with the money bought such
goods as were suitable to the trade he designed. He joined a caravan, and
took a journey. He returned, at the end of the year, in the same condition as
my other brother; and I, having gained another thousand sequins, gave him
them, with which he furnished his shop, and continued to follow his trade.

Some time after, one of my brothers came to me to propose a trading


voyage with them. I immediately rejected their proposal. You have
travelled, says I, and what have you gained by it? Who can assure me that I
shall be more successful than you have been. They represented to me, in
vain, all that they thought fit, to prevail upon me to engage in that design
with them, for I constantly refused: but they importuned me so much, that
after having resisted their solicitations five whole years, they overcame me
at last. But, when we were to make preparations for our voyage, and to buy
goods necessary to the undertaking, I found they had spent all, and that they
had not one farthing left of the thousand sequins I had given each of them. I
did not, however, upbraid them in the least. On the contrary, my stock being
six thousand sequins, I shared the half of it with them, telling them, My
brothers, we must venture these three thousand sequins, and hide the rest in
some sure place; that, in case our voyage be no more successful than your’s
was formerly, we may have wherewith to assist us, and to follow our
ancient way of living. I gave each of them a thousand sequins, and, keeping
as much for myself, I buried the other three thousand in a corner of my
house. We bought our goods, and, after having embarked them on board of
a vessel, which we freighted betwixt us three, we put to sea, with a
favourable wind. After a month’s sail —But I see day, says Scheherazade; I
must stop here.

Sister, says Dinarzade, this story promises a great deal; I fancy the rest of
it must be very extraordinary. You are not mistaken, says the sultaness; and,
if the sultan will allow me to tell it you, I am persuaded, it will very much
divert you. Schahriar got up, as he did the day before, without explaining
his mind, but gave no order to the grand vizier to kill his daughter.

SEVENTH NIGHT.
When the seventh night drew near a close, Dinarzade awaked the
sultaness, and prayed her to continue the story of the second old man. I will,
answered Scheherazade, provided the sultan, my lord and master, does not
oppose it. Not at all, says Schahriar; I am so far from opposing it, that I
desire you earnestly to go on with it.

To resume the thread of the story, says Scheherazade, you must know, that
the old man who led the two dogs, continued his story to the genie, the
other two old men, and the merchant, thus: In short, says he, after two
months’ sail, we arrived happily at port, where we landed and had a very
great vent for our goods. I, especially, sold mine so well, that I gamed ten to
one, and we bought commodities of that country, to transport and sell in our
own.

When we were ready to embark, in order to return, I met upon the bank of
the sea a lady, handsome enough, but poorly clad. She came up to me
presently, kissed my hand, prayed me, with the greatest earnestness
imaginable, to marry her, and take her along with me. I made some
difficulty to agree to it; but she said so many things to persuade me that I
ought to make no objection to her poverty, and that I should have all the
reason in the world to be satisfied with her conduct, that I yielded. I ordered
proper apparel to be made for her; and after having married her, according
to form, I took her on board, and we set sail. During the navigation, I found
the wife I had taken had so many good qualities, that I loved her every day
more and more. In the mean time, my two brothers, who had not managed
their affairs so well as I did mine, envied my prosperity; and their fury
carried them so far as to conspire against my life; so that, one night, when
my wife and I were asleep, they threw us both into the sea.

My wife was a fairy, and, by consequence, a genie, you know well she
could not be drowned; but for me, it is certain I had been lost without her
help. I had scarce fallen into the water when she took me up, and carried me
to an island. When it was day, the fairy said to me, You see, husband, that,
by saving your life, I have not rewarded you ill for your kindness to me.
You must know, that I am a fairy, and that, being upon the bank of the sea
when you were going to embark, I found I had a strong inclination for you:
I had a mind to try your goodness, and presented myself before you in that
disguise wherein you saw me. You have dealt very generously with me, and
I am very glad to have found an opportunity of testifying my
acknowledgment to you. But I am incensed against your brothers, and
nothing will satisfy me but their lives.

I listened to this discourse of the fairy with admiration; I thanked her, as


well as I could, for the great kindness she had done me: but, madam, says I,
as for my brothers, I beg you to pardon them; whatever cause they have
given me, I am not cruel enough to desire their death. I told her the
particulars of what I had done for them, which increased her indignation so
that she cried out, I must immediately pursue those ungrateful traitors, and
take speedy vengeance on them: I will drown their vessel, and throw them
into the bottom of the sea. No, my good lady, replied I, for Heaven’s sake,
do not so; moderate your anger; consider that they are my brothers, and that
we must do good for evil.

I pacified the fairy by those words; and, as soon as I had spoken them, she
transported me, in a moment, from the island where we were to the roof of
my own house, which was terrassed, and disappeared in a moment. I went
down, opened the doors, and dug up the three thousand sequins I had hid. I
went afterwards to the place where my shop was, which I also opened; and
was complimented by the merchants, my neighbours, upon my return.
When I went to my house, I perceived two black dogs, which came to me in
a very submissive manner: I knew not what it meant, but was much
astonished at it. But the fairy, who appeared immediately, says to me,
husband, be not surprised to see these two black dogs by you; they are your
two brothers. I was troubled at these words, and asked her by what power
they were so transformed. It was I who did it, says she; at least, I gave
commission to one of my sisters to do it, who at the same time sunk their
ship. You have lost the goods you had on board, but I will make it up to you
another way. As to your two brothers, I have condemned them to remain
five years in that shape: their perfidiousness too well deserves such a
penance. And, in short, after having told me where I might hear of her, she
disappeared.

Now, the five years being out, I am travelling in quest of her; and, as I
passed this way, I met this merchant and the good old man that led the hind,
and sat down by them. This is my history, O prince of genii! do not you
think it very extraordinary? I own it, says the genie; and, upon that account,
I remit the merchant the second third of the crime which he committed
against me.

As soon as the second old man had finished his story, the third began, and
made the like request of the genie with the two first; that is to say, to pardon
the merchant the other third of his crime, provided the story he had to tell
him exceeded the two he had already heard for singular events. The genie
made him the same promise as he had done the other two. Hearken, then,
says the old man to him —but day appears, says Scheherazade; I must stop
here.

I cannot enough admire, sister, says Dinarzade, the adventures you have
told me. I know abundance more, says the sultaness, that are still more
wonderful. Schahriar, willing to know if the story of the third old man
would be as agreeable as that of the second, put off the execution of
Scheherazade till the next day.

EIGHTH NIGHT.
As soon as Dinarzade perceived it was time to call the sultaness, she says,
sister, I have been awake a long time, and had a great mind to awake you, I
am so impatient to hear the story of the third old man. The sultan answered,
I can hardly think that the third story will surpass the two former ones.

Sir, replies the sultaness, the third old man told his story to the genie: I
cannot tell it to you, because it is not come to my knowledge; but I know
that it did so much exceed the two former stories, in the variety of
wonderful adventures, that the genie was astonished at it, and no sooner
heard the end of it, but he said to the third old man, I remit the other third
part of the merchant’s crime upon the account of your story. He is very
much obliged to all three of you for having delivered him out of this danger,
by your stories, without which he had not now been in the world. And,
having spoke thus, he disappeared to the great contentment of the company.

The merchant failed not to give his three deliverers the thanks he owed
them. They rejoiced to see him out of danger; after which they bade him
adieu, and each of them went on his way. The merchant returned to his wife
and children, and passed the rest of his days with them in peace. But, sir,
added Scheherazade, now pleasant soever these stories may be, that I have
told your majesty hitherto, they do not come near that of the fisherman.
Dinarzade, perceiving that the sultaness demurred, says to her, sister, since
there is still some time remaining, pray tell us the story of the fisherman, if
the sultan is willing. Schahriar agreed to it; and Scheherazade, resuming her
discourse, pursued it in this manner:

The Story of the Fisherman.


Sir —There was a very ancient fisherman, so poor, that he could scarce
earn enough to maintain himself, his wife, and three children. He went
every day to fish betimes in a morning; and imposed it as a law upon
himself, not to cast his nets above four times a day. He went one morning
by moonlight, and coming to the sea-side, undressed himself, and cast in his
nets. As he drew them towards the shore, he found them very heavy, and
thought he had a good draught of fish, at which he rejoiced within himself;
but in a moment after perceiving, that, instead of fish, there was nothing in
his nets but the carcass of an ass, he was much vexed. Scheherazade
stopped here, because she saw it was day.

Sister, says Dinarzade, I must confess, that the beginning of the story
charms me, and I foresee that the result of it will be very agreeable. There is
nothing more surprising than the story of this fisherman, replied the
sultaness; and you will be convinced of it next night, if the sultan will be so
gracious as to let me live. —Schahriar being curious to hear the success of
such an extraordinary fishing, would not order Scheherazade to be put to
death that day.

NINTH NIGHT.
My dear sister, cried Dinarzade, next morning, at the usual hour, if you be
not asleep, I pray you go on with the story of the fisherman; I am ready to
die till I hear it. I am willing to give you that satisfaction, says the sultaness:
but, at the same time she demanded leave of the sultan, and having obtained
it, began the story again as follows:
Sir, when the fisherman, vexed to have made such a sorry draught, had
mended his nets, which the carcass of the ass had broken in several places,
he threw them in a second time; and when he drew them, found a great deal
of resistance, which made him think he had taken abundance of fish; but he
found nothing except a basket full of gravel and slime, which grieved him
extremely. O, fortune! cries he, with a lamentable tone, be not angry with
me, nor persecute a wretch who prays thee to spare him. I came hither from
my house to seek for my livelihood, and thou pronouncest death against me.
I have no other trade but this to subsist by; and, notwithstanding all the
pains I take, I can scarcely provide what is absolutely necessary for my
family. But I am to blame to complain of thee; thou takest pleasure to
persecute honest people, and to leave great men in obscurity, while thou
showest favour to the wicked, and advancest those who have no virtue to
recommend them.

Having finished this complaint, he threw away the basket in a fret, and
washing his nets from the slime, cast them the third time; but brought up
nothing, except stone, shells, and mud. Nobody can express his disorder; he
was almost beside himself. However, when day began to appear, he did not
forget to say his prayers, like a good Mussulman, and afterwards added this
petition: “Lord, thou knowest that I cast my nets only four times a day; I
have already drawn them three times, without the least reward for my
labour: I am only to cast them once more; I pray thee to render the sea
favourable to me, as thou didst to Moses.”

The fisherman having finished this prayer, cast his nets the fourth time;
and when he thought it was time, he drew them as formerly, with great
difficulty; but instead of fish, found nothing in them but a vessel of yellow
copper, which, by its weight, seemed to be full of something; and he
observed that it was shut up and sealed with lead, having the impression of
a seal upon it. This rejoiced him: I will sell it, says he, to the founder, and
with the money arising from the produce, buy a measure of corn. He
examined the vessel on all sides, and shook it, to see if what was within
made any noise, but heard nothing. This circumstance, with the impression
of the seal upon the leaden cover, made him think there was something
precious in it. To try this he took a knife, and opened it with very little
labour. He presently turned the mouth downward, but nothing came out;
which surprised him extremely. He set it before him, and while he looked
upon it attentively, there came out a very thick smoke, which obliged him to
retire two or three paces from it.

The smoke ascended to the clouds, and extending itself along the sea and
upon the shore, formed a great mist, which, we may well imagine, did
mightily astonish the fisherman. When the smoke was all out of the vessel,
it re-united itself, and became a solid body, of which there was formed a
genie twice as high as the greatest of giants. At the sight of a monster of
such an unsizeable bulk, the fisherman would fain have fled, but was so
frightened that he could not go one step.

Solomon, cried the genie immediately, Solomon, the great prophet,


pardon, pardon; I will never more oppose your will, I will obey all your
commands.—

Scheherazade, perceiving day, broke off her story.

Upon which Dinarzade said, Dear sister, nobody can keep their promise
better than you have done yours. This story is certainly more surprising than
all the former. Sister, replies the sultaness, there are more wonderful things
yet to come, if my lord the sultan will allow me to tell them to you.
Schahriar had too great a desire to hear out the story of the fisherman, to
deprive himself of that pleasure; and therefore put off the sultaness’s death
another day.

TENTH NIGHT.
Dinarzade called her sister next night, when she thought it was time, and
prayed her to continue the story of the fisherman; and the sultan being also
impatient to know what concern the genie had with Solomon, Scheherazade
continued her story thus:

Sir, the fisherman, when he heard these words of the genie, recovered his
courage, and said to him, Proud spirit, what is it that you say? It is above
eighteen hundred years since the prophet Solomon died, and we are now at
the end of time. Tell me your history, and how you came to be shut up in
this vessel.

The genie, turning to the fisherman, with a fierce look, says, you must
speak to me with more civility; thou art very bold to call me a proud spirit.
Very well, replies the fisherman, shall I speak to you with more civility, and
call you the owl of good luck? I say, answers the genie, speak to me more
civilly before I kill thee. Ah! replies the fisherman, why would you kill me?
Did not I just now set you at liberty, and have you already forgotten it? Yes,
I remember it, says the genie, but that shall not hinder me from killing thee:
I have only one favour to grant thee. And what is that? says the fisherman.
It is, answers the genie, to give thee thy choice, in what manner thou
wouldst have me take thy life. But wherein have I offended you? replies the
fisherman. Is that your reward for the good services I have done you? I
cannot treat you otherwise, says the genie; and that you may be convinced
of it, hearken to my story.

I am one of those rebellious spirits that opposed the will of Heaven; all
the other genii owned Solomon, the great prophet, and submitted to him.
Sacar and I were the only genii that would never be guilty of a mean thing:
and, to avenge himself, that great monarch sent Asaph, the son of Barakhia,
his chief minister, to apprehend me. That was accordingly done. Asaph
seized my person, and brought me by force before his master’s throne.

Solomon, the son of David, commanded me to quit my way of living, to


acknowledge his power, and to submit myself to his command; I bravely
refused to obey, and told him, I would rather expose myself to his
resentment, than swear fealty, and submit to him, as he required. To punish
me, he shut me up in this copper vessel; and to make sure of me, that I
should not break prison, he himself stamped upon this leaden cover his seal,
with the great name of God engraved upon it. Then he gave the vessel to
one of the genii who submitted to him, with orders to throw me into the sea,
which was executed to my sorrow.

During the first hundred years imprisonment, I swore that if any one
would deliver me before the hundred years expired, I would make him rich,
even after his death: but that century ran out, and nobody did me that good
office. During the second, I made an oath, that I would open all the
treasures of the earth to any one that should set me at liberty; but with no
better success. In the third, I promised to make my deliverer a potent
monarch, to be always near him in spirit, and to grant him every day three
requests, of what nature soever they might be: but this century ran out as
well as the two former, and I continued in prison. At last, being angry, or
rather mad, to find myself a prisoner so long, I swore, that if afterwards any
one should deliver me, I would kill him without mercy, and grant him no
other favour but to choose what kind of death he would die; and, therefore,
since you have delivered me to-day, I give you that choice.

This discourse afflicted the poor fisherman extremely; I am very


unfortunate, cries he, to come hither to do such a piece of good service to
one that is so ungrateful. I beg you to consider your injustice, and revoke
such an unreasonable oath: pardon me, and heaven will pardon you; if you
grant me my life, heaven will protect you from all attempts against yours.
No, thy death is resolved on, says the genie, only choose how you will die.
The fisherman, perceiving the genie to be resolute, was extremely grieved,
not so much for himself, as for his three children; and bewailed the misery
they must be reduced to by his death. He endeavoured still to appease the
genie, and says, Alas! be pleased to take pity on me, in consideration of the
good service I have done you. I have told thee already, replies the genie, it
is for that very reason I must kill thee. That is very strange, says the
fisherman, are you resolved to reward good with evil? The proverb says,
“That he who does good to one who deserves it not, is always ill rewarded.”
I must confess, I thought it was false; for in effect there can be nothing
more contrary to reason, or the laws of society. Nevertheless, I find now by
cruel experience, that it is but too true. Do not lose time, replies the genie;
all thy reasoning shall not divert me from my purpose: make haste and tell
me which way you choose to die.
Necessity is the mother of invention. The fisherman bethought himself of
a stratagem. Since I must die, then, says he to the genie, I submit to the will
of heaven; but before I choose the manner of death, I conjure you by the
great name which was engraven upon the seal of the prophet Solomon, the
son of David, to answer me truly the question I am going to ask you.

The genie finding himself obliged to a positive answer by this abjuration,


trembled; and replied to the fisherman, Ask what thou wilt, but make haste.
Day appearing, Scheherazade held her peace.

Sister, says Dinarzade, it must be owned that the more you speak, the
more you surprise and satisfy. I hope our lord, the sultan, will not order you
to be put to death, till he hears out the fine story of the fisherman. The
sultan is absolute, replies Scheherazade, we must submit to his will in every
thing. But Schahriar being as willing as Dinarzade to hear an end of the
story, did again put off the execution of the sultaness.

ELEVENTH NIGHT.
Schahriar, and the princess his spouse, passed this night in the same
manner as they had done the former; and before break of day, Dinarzade
awaked them with these words, addressed to the sultaness: I pray you,
sister, to resume the story of the fisherman. With all my heart, said
Scheherazade, I am willing to satisfy you, with the sultan’s permission.

The genie, continued she, having promised to speak the truth, the
fisherman says to him, —I would know if you were actually in this vessel:
dare you swear it by the name of the great God? Yes, replied the genie, I do
swear by that great name that I was, and it is a certain truth. In good faith,
answered the fisherman, I cannot believe you; the vessel is not capable of
holding one of your feet, and how should it be possible that your whole
body could lie in it? I swear to thee, notwithstanding, replied the genie, that
I was there just as you see me here: Is it possible, that thou dost not believe
me after this great oath that I have taken? Truly, not I, said the fisherman;
nor will I believe you, unless you show it me.

Upon which the body of the genic was dissolved, and changed itself into
smoke, extending itself as formerly upon the sea and shore: and then at last
being gathered together, it began to re-enter the vessel, which it continued
to do successively by a slow and equal motion, after a smooth and exact
way, till nothing was left out; and immediately, a voice came forth, which
said to the fisherman, Well, now, incredulous fellow, I am all in the vessel,
do not you believe me now.

The fisherman, instead of answering the genie, took the cover of lead, and
having speedily shut the vessel, Genie, cries he, now it is your turn to beg
my favour, and to choose which way I shall put you to death; but not so, it
is better that I should throw you into the sea, whence I took you: and then I
will build a house upon the bank, where I will dwell, to give notice to all
fishermen who come to throw in their nets, to beware of such a wicked
genie as thou art, who hast made an oath to kill him that shall set thee at
liberty.

The genie, enraged at those expressions, did all he could to get out of the
vessel again; but it was not possible for him to do it; for the impression of
Solomon’s seal prevented him. So perceiving that the fisherman had got the
advantage of him, he thought fit to dissemble his anger; Fisherman, said he,
in a pleasant tone, take heed you do not do what you say, for what I spoke
to you before was only by way of jest, and you are to take it no otherwise.
O, genie! replies the fisherman, thou who wast but a moment ago the
greatest of all genie, and now art the least of them, thy crafty discourse will
signify nothing to thee, but to the sea thou shalt return. If thou hast staid
there already so long as thou hast told me, thou mayst very well stay there
till the day of judgment. I begged of thee in God’s name, not to take away
my life, and thou didst reject my prayers; I am obliged to treat thee in the
same manner.

The genie omitted nothing that could prevail upon the fisherman; Open
the vessel, says he, give me my liberty, I pray thee, and I promise to satisfy
thee to thy own content. Thou art a mere traitor, replies the fisherman; I
should deserve to lose my life, if I were such a fool as to trust thee; thou
wilt not fail to treat me in the same manner as a certain Grecian king treated
the physician Douban. It is a story I have a mind to tell thee, therefore listen
to it.
The Story of the Grecian King and the Physician Douban.
There was in the country of Zouman, in Persia, a king, whose subjects
were originally Greeks. This king was all over leprous, and his physicians
in vain endeavoured his cure; and when they were at their wits end what to
prescribe to him, a very able physician, called Douban, arrived at his court.

This physician had learned his science in Greek, Persian, Turkish,


Arabian, Latin, Syriac, and Hebrew books; and besides that, he was an
expert philosopher, and fully understood the good and bad qualities of all
sorts of plants and drugs. As soon as he was informed of the king’s
distemper, and understood that his physicians had given him over, he clad
himself in the best habits he could procure, and found means to present
himself to the king. Sir, says he, I know that all your majesty’s physicians
have not been able to cure you the leprosy; but if you will do me the honour
to accept my service, I will engage myself to cure you without potions, or
external applications.

The king listened to what he said, and answered, If you be able to perform
what you do promise, I will enrich you and your posterity; and besides the
presents I shall make you, you shall be my chief favourite. Do you assure
me, then, that you will cure me of my leprosy, without making me take any
potion, or applying any external medicine? Yes, sir, replies the physician; I
promise myself success, through God’s assistance, and to-morrow I will
make trial of it.

The physician returned to his quarters, and made a mallet, hollow within,
and at the handle he put in his drugs: he made also a ball in such a manner
as suited his purpose, with which, next morning, he went to present himself
before the king, and falling down at his feet, kissed the ground. Here
Scheherazade, perceiving day, acquainted the sultan with it, and held her
peace.

I wonder, sister, says Dinarzade, where you learn so many fine things.
You shall hear a great many others to-morrow, replies Scheherazade, if the
sultan, my master, will be pleased to prolong my life farther. Schahriar, who
longed as much as Dinarzade, to hear the sequel of the story of Douban, the
physician, did not order the sultaness to be put to death that day.

TWELFTH NIGHT.
The twelfth night was far advanced, when Dinarzade called, and says,
sister, you owe us the continuation of the agreeable history of the Grecian
king and the physician Douban. I am very willing to pay my debt, replied
Scheherazade, and resumed the story as follows:

Sir, the fisherman, speaking always to the genie, whom he kept shut up in
the vessel, went on thus. The physician Douban rose up, and after a
profound reverence, says to the king, he judged it meet that his majesty
should take horse, and go to the place where he used to play at mall. [1] The
king did so, and when he arrived there, the physician came to him with the
mall, and says to him, Sir, exercise yourself with this mall, and strike the
ball with it until you find your hands and your body in a sweat. When the
medicine I have put up in the handle of the mall, is heated with your hand,
it will penetrate your whole body; and as soon as you shall sweat, you may
leave off the exercise, for then the medicine will have had its effect. As
soon as you are returned to your palace, go into the bath, and cause yourself
to be well washed and rubbed; then go to bed, and when you rise to-morrow
you will find yourself cured.

The king took the mall, and struck the ball, which was returned by his
officers that played with him; he struck it again, and played so long, that his
hand and his whole body were in a sweat, and then the medicine shut up in
the handle of the mall had its operation, as the physician said. Upon this the
king left off play, returned to his palace, entered the bath, and observed very
exactly what his physician had prescribed him.

He was very well after it, and next morning, when he arose, he perceived,
with equal wonder and joy, that his leprosy was cured, and his body as
clean as if he had never been attacked with that distemper. As soon as he
was dressed, he came into the hall of audience, where he ascended his
throne, and showed himself to his courtiers, who, eager to know the success
of the new medicine, came thither betimes; and, when they saw the king
perfectly cured, did all express great joy. The physician Douban entered the
hall, and bowed himself before the throne, with his face to the ground. The
king, perceiving him, called him, made him sit down by his side, showed
him to the assembly, and gave him all the commendation he deserved. His
majesty did not stop here; but, as he treated all his court that day, he made
him eat at his table alone with him. At these words, Scheherazade,
perceiving day, broke off her story. Sister, says Dinarzade, I know not what
the conclusion of this story will be, but I find the beginning admirable. That
which is to come is yet better, answered the sultaness; and I am certain you
will not deny it, if the sultan gives me leave to make an end of it to-morrow
night. Schahriar consented, and rose very well satisfied with what he had
heard.

THIRTEENTH NIGHT.
Dinarzade, willing to keep the sultan in ignorance of her design, cried out
as if she had started out of her sleep: O, dear sister, I have had a
troublesome dream, and nothing will sooner make me forget it than the
remainder of the story of the Grecian king and doctor Douban. I conjure
you by the love you always bore me, not to defer it a moment longer. I shall
not fail, good sister, to ease your mind; and if my sovereign will permit me,
I will go on. Schahriar, being charmed with the agreeable manner of
Scheherazade’s telling her stories, says to her, You will oblige me no less
than Dinarzade, therefore continue. [2]

The Grecian king, says the fisherman to the genie, was not satisfied with
having admitted the physician Douban to his table, but towards night, when
he was about dismissing the company, he caused him to be clad in a long
rich robe, like those which his favourites usually wore in his presence; and
besides that he ordered him two thousand sequins. The next day and the day
following, he continued his favour to him; in short, the prince, thinking that
he could never enough acknowledge the obligations he lay under to that
able physician, bestowed every day new favours upon him. But this king
had a grand vizier, who was avaricious, envious, and naturally capable of all
sort of mischief. He could not see, without envy, the presents that were
given to the physician, whose other merits had already began to make him
jealous, and therefore he resolved to lessen him in the king’s esteem. To
effect this, he went to the king, and told him in private, that he had some
advice to give him, which was of the greatest concern. The king having
asked what it was, Sir, said he, it is very dangerous for a monarch to put
confidence in a man whose fidelity he never tried. Though you heap favours
upon the physician Douban, and show him all the familiarity that may be,
your majesty does not know but he may be a traitor, and come on purpose
to this court to kill you. From whom have you this, answered the king, that
you dare to tell it me? Consider to whom you speak, and that you advance a
thing which I shall not easily believe. Sir, replied the vizier, I am very well
informed of what I have had the honour to represent to your majesty;
therefore do not let your dangerous confidence grow to a farther height: if
your majesty be asleep, be pleased to awake; for I once more repeat it, that
the physician Douban did not leave the heart of Greece, his native country,
nor come here to settle himself at your court, but to execute that horrible
design which I have just now hinted to you.

No, no, vizier, replies the king; I am certain that this man, whom you treat
as a villain, and a traitor, is one of the best and most virtuous men in the
world, and there is no man I love so much. You know by what medicine, or
rather by what miracle, he cured me of my leprosy; if he had a design upon
my life, why did he save me? He needed only have left me to my disease; I
could not have escaped it; my life was already half gone. Forbear, then, to
fill me with unjust suspicions: instead of listening to you, I tell you, that
from this day forward I will give that great man a pension of a thousand
sequins per month for his life; nay, though I were to share with him all my
riches and dominions, I should never pay him enough for what he has done
for me: I perceive it to be his virtue which raises your envy; but do not
think that I will be unjustly possessed with prejudice against him. I
remember too well what a vizier said to king Sinbad, his master, to prevent
his putting to death the prince, his son. But, sir, says Scheherazade, day
light appears, which forbids me to go any further.

I am very well pleased that the Grecian king, says Dinarzade, had so
much firmness of spirit, to reject the false accusation of the vizier. If you
commend the firmness of that prince to-day, says Scheherazade, you will as
much condemn his weakness to-morrow, if the sultan be pleased to allow
me time to finish this story. The sultan, being curious to hear wherein the
Grecian king discovered his weakness, did further delay the death of the
sultaness.

FOURTEENTH NIGHT.
An hour before day, Dinarzade awaked her sister, and says to her, You
will certainly be as good as your word, madam, and finish the story of the
fisherman; to assist your memory, I will tell you where you left off: it was
where the Grecian king maintained the innocence of his physician Douban
against his vizier. I remember it, says Scheherazade, and am ready to give
you satisfaction.

Sir, continues she, addressing herself to Schahriar, what the Grecian king
said about king Sinbad raised the vizier’s curiosity, who says to him, sir, I
pray your majesty to pardon me, if I have the boldness to ask what the
vizier of king Sinbad said to his master to divert him from cutting off the
prince, his son. The Grecian king had the complaisance to satisfy him: That
vizier, says he, after having represented to king Sinbad, that he ought to
beware, lest on the accusation of a mother-in-law, he should commit an
action which he might afterwards repent of, told him this story.

The Story of the Husband and the Parrot.


A certain man had a beautiful wife, whom he loved so dearly, that he
could scarce allow her to be out of his sight. One day being obliged to go
abroad, about urgent affairs, he came to a place where all sorts of birds were
sold, and there bought a parrot which not only spoke very well, but could
also give an account of every thing that was done before it. He brought it in
a cage to his house, desired his wife to put it in his chamber, and to take
care of it during a journey he was obliged to undertake; and then went out.

At his return, he took care to ask the parrot concerning what had passed in
his absence, and the bird told him things that gave him occasion to upbraid
his wife. She thought some of her slaves had betrayed her, but all of them
swore they had been faithful to her; and they all agreed that it must have
been the parrot that had told tales.

Upon this, the wife bethought herself of a way how she might remove her
husband’s jealousy, and at the same time revenge herself on the parrot,
which she effected thus: her husband being gone another journey, she
commanded a slave in the night-time to turn a hand-mill under the parrot’s
cage; she ordered another to throw water, in form of rain, over the cage; and
a third to take a looking-glass, and turn it to the right and to the left before
the parrot by candle-light. The slaves spent great part of the night in doing
what their mistress commanded them, and acquitted themselves very
dexterously.

Next night the husband returned, and examined the parrot again about
what had passed during his absence. The bird answered, Good master, the
lightning, thunder, and rain, did so much disturb me all night, that I cannot
tell how much I suffered by it. The husband, who knew that there had been
neither thunder, lightning, nor rain, that night, fancied that the parrot, not
having told him the truth in this, might also have lied to him in the other;
upon which he took it out of the cage, and threw it with so much force to
the ground that he killed it. Yet, afterwards, he understood by his
neighbours, that the poor parrot had not lied to him, when it gave him an
account of his wife’s base conduct, which made him repent he had killed it.
Scheherazade stopped here, because she saw it was day.

All that you tell us, sister, says Dinarzade, is so curious, that nothing can
be more agreeable. I shall be willing to divert you, answers Scheherazade, if
the sultan, my master, will allow me time to do it. Schahriar, who took as
much pleasure to hear the sultaness, as Dinarzade, rose and went about his
affairs, without ordering the vizier to cut her off.
FIFTEENTH NIGHT.
Dinarzade was punctual this night, as she had been the former, to awaken
her sister, and begged of her, as usual, to tell her a story. I am going to do it,
sister, says Scheherazade: but the sultan interrupted her, for fear she should
begin a new story, and bid her finish the discourse between the Grecian
king and his vizier about his physician Douban. Sir, says Scheherazade, I
will obey you; and went on with the story, as follows:

When the Grecian king, says the fisherman to the genie, had finished the
story of the parrot; and you, vizier, adds he, because of the hatred you bear
to the physician Douban, who never did you any hurt, you would have me
cut him off; but I will take care of that, for fear I should repent it, as the
husband did the killing of his parrot.

The mischievous vizier was too much concerned to effect the ruin of the
physician Douban to stop here. Sir, says he, the death of the parrot was but
a trifle, and, I believe, his master did not mourn for him long; but why
should your fear of wronging an innocent man, hinder your putting this
physician to death? Is it not enough to authorize you to take away his life,
that he is accused of a design against your life? When the business in
question is to secure the life of a king, bare suspicion ought to pass for
certainty; and it is better to sacrifice the innocent than to spare the guilty.
But, sir, this is not an uncertainty; the physician Douban has certainly a
mind to assassinate you. It is not envy which makes me his enemy; it is
only my zeal, and the concern I have for preserving your majesty’s life, that
makes me give you my advice in a matter of this importance. If it be false, I
deserve to be punished in the same manner as a vizier was formerly
punished. What had the vizier done, says the Grecian king, to deserve
punishment? I will inform your majesty of that, says the vizier, if you will
be pleased to hear me.

The Story of the Vizier that was punished.


There was a king, says the vizier, who had a son that loved hunting. He
allowed him to divert himself that way very often; but gave orders to his
grand vizier to attend him constantly, and never to lose sight of him.
One hunting-day, the huntsman having roused a deer, the prince, who
thought the vizier followed him, pursued the game so far, and with so much
earnestness, that he was left quite alone. He stopped, and finding he had lost
his way, endeavoured to return the same way he came, to find out the vizier,
who had not been careful enough to follow him, and so wandered farther.

Whilst he rode up and down, without keeping any road, he met by the
way-side a handsome lady, who wept bitterly. He stopped his horse, asked
who she was, how she came to be alone in that place, and what she wanted.
I am, says she, daughter to an Indian king. As I was taking the air on
horseback, in the country, I grew sleepy, fell from my horse, who is run
away, and I know not what is become of him. The young prince taking
compassion on her, asked her to get up behind him, which she willingly
accepted.

As they passed by the ruins of a house, the lady signified a desire to alight
on some occasion. The prince, stopped, and suffered her to alight; then he
alighted himself, and went near the ruins with his horse in his hand. But you
may judge how much he was surprised, when he heard the lady within say
these words: “Be glad, my children, I bring you a handsome young man,
and very fat;” and other voices, which answered immediately, “Mamma,
where is he, that we may eat him presently, for we are very hungry!”

The prince heard enough to convince him of his danger, and then he
perceived that the lady who called herself daughter to an Indian king, was
an Ogress, wife to one of those savage demons, called Ogres, who live in
remote places, and make use of a thousand wiles to surprise and devour
passengers; so that the prince being frightened, mounted his horse as soon
as he could.

The pretended princess appeared that very moment, and perceiving she
had missed her prey, she cries, Fear nothing, prince: who are you? whom do
you seek? I have lost my way, replies he, and am seeking it. If you have lost
your way, says she, recommend yourself to God, he will deliver you out of
your perplexity. Then the prince lifted up his eyes towards heaven. But, sir,
says Scheherazade, I am obliged to break off, for day appears.
I long, says Dinarzade, to know what became of that young prince: I
tremble for him. I will deliver you from your uneasiness to-morrow,
answers the sultaness, if the sultan will allow me to live till then. Schahriar,
willing to hear an end of this adventure, prolonged Scheherazade’s life for
another day.

SIXTEENTH NIGHT.
Dinarzade had such a desire to hear out the story of the young prince, that
she awaked that night sooner than ordinary, and said, Sister, pray go on with
the story you began yesterday: I am much concerned for the young prince,
and ready to die for fear that he was eaten up by the Ogress and her
children. Schahriar having signified that he had the same fear, the sultaness
replies, Well, sir, I will satisfy you immediately.

After the counterfeit Indian princess had bid the young prince recommend
himself to God, he could not believe she spoke sincerely, but thought she
was sure of him: and therefore, lifting up his hands to heaven, said,
“Almighty Lord, cast thine eyes upon me, and deliver me from this enemy.”
After this prayer, the Ogress entered the ruins again, and the prince rode off
with all possible haste. He happily found his way again, and arrived safe
and sound at his father’s court, to whom he gave a particular account of the
danger he had been in through the vizier’s neglect: upon which the king,
being incensed against the minister, ordered him to be immediately
strangled.

Sir, continued the Grecian king’s vizier, to return to the physician


Douban, if you do not take care, the confidence you put in him will be fatal
to you: I am very well assured, that he is a spy sent by your enemies to
attempt your majesty’s life. He has cured you, he will say: but alas! who
can assure you of that? He has, perhaps, cured you only in appearance, and
not radically; who knows but the medicine he has given you may, in time,
have pernicious effects?

The Grecian king, who had naturally very little sense, was not able to
discover the wicked design of his vizier, nor had he firmness enough to
persist in his first opinion. This discourse staggered him. Vizier, says he,
thou art in the right; he may be come on purpose to take away my life,
which he may easily do by the very smell of some of his drugs. We must
consider what is fit for us to do in this case.

When the vizier found the king in such a temper as he wished, Sir, said
he, the surest and speediest method you can take to secure your life, is to
send immediately for the physician Douban, and order his head to be cut off
as soon as he comes. In truth, says the king, I believe that is the way we
must take to prevent his design. When he had spoken thus, he called for one
of his officers, and ordered him to go for the physician; who, knowing
nothing of the king’s design, came to the palace in haste.

Know ye, says the king, when he saw him, why I sent for you; No, sir,
answers he; I wait till your majesty be pleased to inform me. I sent for you,
replied the king, to rid myself of you by taking your life.

No man can express the surprise of the physician, when he heard the
sentence of death pronounced against him. Sir, said he, why would your
majesty take my life? What crime have I committed? I am informed by
good hands, replies the king, that you come to my court only to attempt my
life; but to prevent you, I will be sure of yours. Give the blow, says he to the
executioner, who was present, and deliver me from a perfidious wretch,
who came hither on purpose to assassinate me.

When the physician heard this cruel order, he readily judged that the
honours and presents he had received from the king had procured him
enemies, and that the weak prince was imposed on. He repented that he had
cured him of his leprosy; but it was now too late. Is it thus, replied the
physician, that you reward me for curing you? The king would not hearken
to him, but a second time ordered the executioner to strike the fatal blow.
The physician then had recourse to his prayers: Alas! sir, cries he, prolong
my days, and God will prolong yours; do not put me to death lest God treat
you in the same manner. The fisherman broke off his discourse here, to
apply it to the genie. Well, genie, says he, you see what passed then betwixt
the Grecian king and his physician Douban, is acted just now betwixt us.

The Grecian king, continues he, instead of having regard to the prayers of
the physician, who begged him for God’s sake to spare him, cruelly replied
to him, No, no; I must of necessity cut you off, otherwise you may take my
life away with as much art as you cured me. The physician melted into
tears, and bewailing himself for being so ill rewarded by the king, prepared
for death. The executioner bound up his eyes, tied his hands, and was going
to draw his scimitar.

Then the courtiers, who were present, being moved with compassion,
begged the king to pardon him, assuring his majesty that he was not guilty
of the crime laid to his charge, and that they would answer for his
innocence: but the king was inflexible, and answered them so as they dared
not to say any more of the matter.

The physician, being on his knees, his eyes tied up, and ready to receive
the fatal blow, addressed himself once more to the king: Sir, says he, since
your majesty will not revoke the sentence of death, I beg at least, that you
would give me leave to return to my house, to give order about my burial,
to bid farewell to my family, to give alms, and to bequeath my books to
those who are capable of making good use of them. I have one particularly I
would present to your majesty: it is a very precious book, and worthy to be
laid up very carefully in your treasury. Well, replies the king, why is that
book so precious as you talk of? —Sir, says the physician, because it
contains an infinite number of curious things; of which the chief is, that
when you have cut off my head, if your majesty will give yourself the
trouble to open the book at the sixth leaf, and read the third line of the left
page, my head will answer all the questions you ask it. The king being
curious to see such a wonderful thing, deferred his death till next day, and
sent him home under a strong guard.

The physician, during that time, put his affairs in order: and the report
being spread that an unheard-of prodigy was to happen after his death, the
viziers, emirs, officers of the guard, and, in a word, the whole court,
repaired next day to the hall of audience, that they might be witnesses of it.

The physician Douban was soon brought in, and advanced to the foot of
the throne, with a great book in his hand: there he called for a basin, upon
which he laid the cover that the book was wrapped in, and presented the
book to the king. Sir, says he, take that book, if you please, and as soon as
my head is cut off, order that it be put into the basin upon the cover of the
book; as soon as it is put there, the blood will stop: then open the book, and
my head will answer your questions. But, sir, says he, permit me once more
to implore your majesty’s clemency; for God’s sake grant my request; I
protest to you that I am innocent. Your prayers, answers the king, are in
vain; and, were it for nothing but to hear your head speak after your death,
it is my will you should die. As he said this, he took the book out of the
physician’s hand, and ordered the executioner to do his duty.

The head was so dexterously cut off, that it fell into the basin, and was no
sooner laid upon the cover of the book, but the blood stopped; then, to the
great surprise of the king, and all the spectators, it opened its eyes, and said,
Sir, will your majesty be pleased to open the book? The king opened it, and
finding that one leaf was as it were glued to another, that he might turn it
with the more ease, he put his finger to his mouth, and wet it with spittle.
He did so till he came to the 6th leaf, and finding no writing on the place
where he was bid to look for it, Physician, says he to the head, there is
nothing written. Turn over some more leaves, replies the head. The king
continued to turn over, putting always his finger to his mouth, until the
poison, with which each leaf was imbued, coming to have its effect, the
prince finding himself all of a sudden taken with an extraordinary fit, his
eye-sight failed, and he fell down at the foot of the throne, in violent
convulsions. At these words, Scheherazade, perceiving day, gave the sultan
notice of it, and forbore speaking. Ah, dear sister, says Dinarzade, how
grieved am I that you have not time to finish the story: I should be
inconsolable if you lose your life to-day. Sister, replies the sultaness, that
must be as the sultan pleases; but I hope he will be so good as to suspend
my death till to-morrow. And accordingly, Schahriar, far from ordering her
death that day, expected the next night with much impatience; so earnest
was he to hear out the story of the Grecian king, and the sequel of the
fisherman and the genie.

SEVENTEENTH NIGHT.
Though Dinarzade was very curious to hear the rest of the story of the
Grecian king, she did not awake that night so soon as usual, so that it was
almost day before she called upon the sultaness; and then she said, I pray
you, sister, to continue the wonderful story of the Grecian king; but make
haste, I beseech you, for it will speedily be day.

Scheherazade resumed the story where she left off the day before: Sir,
said she to the sultan, when the physician Douban, or rather his head, saw
that the poison had taken effect, and that the king had but a few moments to
live; Tyrant, it cried, now you see how princes are treated, who, abusing
their authority, cut off innocent men: God punishes soon or late their
injustice and cruelty. Scarcely had the head spoken these words, when the
king fell down dead, and the head itself lost what life it had.

Sir, continued Scheherazade, such was the end of the Grecian king and of
the physician Douban. I must return now to the story of the fisherman and
the genie; but it is day. The sultan, who always observed his hours regularly,
got up; and wishing to hear the sequel of the story of the genie and the
fisherman, bid the sultaness prepare to relate it to him the next night.

EIGHTEENTH NIGHT.
Dinarzade made amends for the last night’s neglect; she awoke long
before day, and calling upon Scheherazade, sister, said she, if you be not
asleep, pray give us the rest of the story of the fisherman and the genie; you
know the sultan desires to hear it as well as I.

I shall soon satisfy his curiosity and yours, answered the sultaness, and
then addressing herself to Schahriar, Sir, continued she, as soon as the
fisherman had concluded the history of the Greek king and his physician
Douban, he made the application to the genie, whom he still kept shut up in
the vessel. If the Grecian king, said he, had suffered the physician to live,
God would have continued his life also: but he rejected his most humble
prayers, and the case is the same with thee, O, genie! Could I have
prevailed with thee to grant me the favour I supplicated, I should now take
pity on thee; but since, notwithstanding the extreme obligation thou wast
under to me, for having set thee at liberty, thou didst persist in thy design to
kill me, I am obliged, in my turn, to be equally hard-hearted to thee.

My good friend fisherman, replied the genie, I conjure thee once more,
not to be guilty of such cruelty; consider, that it is not good to avenge one’s
self, and that on the other hand, it is commendable to do good for evil; do
not treat me as Imama formerly treated Ateca. And what did Imama to
Ateca? inquired the fisherman. Ho! says the genie, if you have a mind to be
informed, open the vessel: do you think that I can be in a humour to relate
stories in so strait a prison? I will tell you as many as you please, when you
have let me out. No, said the fisherman, I will not let thee out; it is in vain
to talk of it: I am just going to throw thee into the bottom of the sea. Hear
me one word more, cried the genie: I promise to do thee no hurt; nay, far
from that, I will shew thee a way to become exceedingly rich.
The hope of delivering himself from poverty, prevailed with the
fisherman. I could listen to thee, said he, were there any credit to be given
to thy word; swear to me by the great name of God, that you will faithfully
perform what you promise, and I will open the vessel; I do not believe you
will dare to break such an oath.

The genie swore to him, upon which the fisherman immediately took off
the covering of the vessel. At that instant, the smoke ascended, and the
genie having resumed his form, the first thing he did was to kick the vessel
into the sea. This action alarmed the fisherman. Genie, said he, will not you
keep the oath you just now made? And must I say to you, as the physician
Douban said to the Grecian king, suffer me to live, and God will prolong
your days.

The genie laughed at the fisherman’s fear, and answered, No, fisherman,
be not afraid, I only did it to divert myself, and to see if thou wouldst be
alarmed at it: but to convince thee that I am in earnest, take thy nets and
follow me. As he spoke these words, he walked before the fisherman, who
having taken up his nets, followed him, but with some distrust. They passed
by the town, and came to the top of a mountain, from whence they
descended into a vast plain, which brought them to a lake, that lay betwixt
four hills.

When they reached the side of the lake, the genie said to the fisherman,
Cast in thy nets, and catch fish; the fisherman did not doubt of taking some,
because he saw a great number in the water; but he was extremely
surprised, when he found they were of four colours, that is to say, white,
red, blue, and yellow. He threw in his nets, and brought out one of each
colour. Having never seen the like before, he could not but admire them,
and judging that he might get a considerable sum for them, he was very
joyful. Carry those fish, said the genie to him, and present them to thy
sultan; he will give thee more money for them. Thou mayest come every
day to fish in this lake; but I give thee warning not to throw in thy nets
above once a day, otherwise thou wilt repent. Having spoken thus, he struck
his foot upon the ground, which opened, and after it had swallowed him up,
closed again.

The fisherman being resolved to follow the genie’s advice, forbore


casting in his nets a second time; and returned to the town very well
satisfied; and making a thousand reflections upon his adventure. He went
immediately to the sultan’s palace, to offer his fish. But, sir, said
Scheherazade, I perceive day, and must stop here.

Dear sister, said Dinarzade, how surprising are the last events you have
told us? I can hardly believe that any thing you have to say can be more
surprising. Sister, replied the sultaness, if the sultan, my master, will let me
live till tomorrow, I am persuaded you will find the sequel of the history of
the fisherman more wonderful than the beginning of it, and incomparably
more diverting. Schahriar, being curious to know if the remainder of this
story would be such as the sultaness said, put off once more the execution
of his cruel sentence.

NINETEENTH NIGHT.
Towards morning, Dinarzade called the sultaness, and said, Dear sister, it
will be day speedily, therefore pray continue the history of the fisherman; I
am extremely impatient to know what the issue of it was. Scheherazade
having demanded permission, resumed her discourse as follows: I leave it
to your majesty to think how much the sultan was surprised, when he saw
the four fish which the fisherman presented. He took them up one after
another, and viewed them with attention; and after having admired them a
long time, Take those fish, said he to his vizier, and carry them to the cook,
whom the emperor of the Greeks has sent me. I cannot imagine but that
they must be as good as they are beautiful.

The vizier carried them as he was directed, and delivering them to the
cook, said, Here are four fish just brought to the sultan; he orders you to
dress them: he then returned to the sultan his master, who ordered him to
give the fisherman four hundred pieces of gold of the coin of that country,
which he did accordingly.

The fisherman, who had never seen so much money, could scarcely
believe his good fortune, but thought the whole must be a dream, until he
found it otherwise, by being able to provide necessaries for his family with
the produce of his fish.

But, sir, said Scheherazade, having told you what happened to the
fisherman, I must acquaint you next with what befel the sultan’s cook,
whom we shall find in great perplexity. As soon as she had gutted the fish,
she put them upon the fire in a frying pan, with oil, and when she thought
them fried enough on one side, she turned them upon the other; but, O,
monstrous prodigy! scarcely were they turned, when the wall of the kitchen
divided, and a young lady of wonderful beauty entered from the opening.
She was clad in flowered satin, after the Egyptian manner, with pendants in
her ears, a necklace of large pearls, and bracelets of gold set with rubies,
with a rod in her hand. She moved towards the frying-pan, to the great
amazement of the cook, who continued fixed by the sight, and striking one
of the fish with the end of the rod, said, “Fish, fish, are you in duty?” The
fish having answered nothing, she repeated these words, and then the four
fish lifted up their heads, and replied, “Yes, yes: if you reckon, we reckon;
if you pay your debts, we pay ours; if you fly, we overcome, and are
content.” As soon as they had finished these words, the lady overturned the
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