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

Developing Java Servlets 2nd Edition James Goodwill - Read the ebook online or download it to own the full content

The document provides information about various Java-related ebooks available for instant download at ebookgate.com, including titles like 'Developing Java Servlets' and 'Murach's Java Servlets and JSP.' It outlines the content structure of the 'Developing Java Servlets' book, detailing its chapters and topics related to servlet fundamentals, JSP fundamentals, and web applications. The document emphasizes the ease of access to digital formats such as PDF, ePub, and MOBI for readers interested in Java programming.

Uploaded by

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

Developing Java Servlets 2nd Edition James Goodwill - Read the ebook online or download it to own the full content

The document provides information about various Java-related ebooks available for instant download at ebookgate.com, including titles like 'Developing Java Servlets' and 'Murach's Java Servlets and JSP.' It outlines the content structure of the 'Developing Java Servlets' book, detailing its chapters and topics related to servlet fundamentals, JSP fundamentals, and web applications. The document emphasizes the ease of access to digital formats such as PDF, ePub, and MOBI for readers interested in Java programming.

Uploaded by

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

Instant Ebook Access, One Click Away – Begin at ebookgate.

com

Developing Java Servlets 2nd Edition James


Goodwill

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

OR CLICK BUTTON

DOWLOAD EBOOK

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Click here to visit ebookgate.com and download ebook now
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;
Exploring the Variety of Random
Documents with Different Content
The scout laughed again.
“I reckon we’ll have excitement enough to please you before we’re
done with the Brazos,” said he, “but it’s only going to be incidental to
the main question of peace.”
The trapper chuckled, fancying he was catching Buffalo Bill’s drift.
“We’ll make peace, Buffler,” he declared, “ef we hev ter shoot
holes in every bloomin’ statute of ther State o’ Texas!”
“Not so bad as that. We’re backing up the law, Nick. Bloom hasn’t
been looking after the law as he was sworn to do.”
“Nary, he hasn’t. Ef he don’t do his duty, we’ll climb his neck an’
choke him till he sees et right an’ promises ter be good. Oh, I
dunno. I reckon bein’ peacemaker kerries plenty o’ blue-fire
trimmin’s. I knowed er feller, up in the Niobrara kentry, called Piegan
Charlie. Charlie went an’ took an’ got married. I was lopin’ past his
wickiup one day, an’ I found him an’ Mrs. Charlie engaged in er
argyment. Charlie was pushin’ Mrs. Charlie agin’ the side o’ the
house, an’ argyin’ with a broomstick. I got all worked up with er fool
desire ter be one o’ these hyar peacemakers. Thet’s what I did. So,
like er ijut, I drapped off’n my hoss, caught Charlie by the scruff o’
the neck, an’ throwed him inter a rainwater bar’l. While I was
prancin’ eround an’ yellin’ fer peace an’ domestic quiet, Mrs. Charlie
come up behind me an’ rapped me over the head with er
washboard. She screeched out thet I hadn’t no bizness meddlin’ with
her husband er distarbin’ ther fambly. When Charlie got out o’ the
bar’l, he begun shootin’ at me. So I loped on, sadder an’ a heap
wiser.”
By the time the scout had finished enjoying his pard’s
reminiscence, they were in Hackamore.
There was quite a crowd collected around the front of the
Delmonico, peering curiously through the open door of the office
and the office windows.
“Somethin’ goin’ on, an’ I’ll bet er blue stack,” muttered Nomad.
“Looks like it,” the scout answered.
“What’s up, Pinkey?” queried the trapper, as the man in charge of
the corral came to look after their riding gear.
“Dunno,” answered Pinkey. “Thar’s so much goin’ on in this man’s
town et’s hard ter keep track o’ all the doin’s. Mebby a dog fight, er
a man fight—thar ain’t much diff’rence when it comes ter rowdyin’.”
At this point a lanky individual, who had seen the pards ride up to
the corral, hurried toward the group by the corral gate.
“Buffler Bill! Buffler Bill!” the man cried.
“Et’s Sim Pierce, thet’s who et is,” said Nomad, recognizing the
approaching man. “What’s agitatin’ ye, Sim?”
“Row on in the orfice o’ the Delmonico,” panted Sim Pierce. “Jake
Phelps, Hank’s cousin er somethin’, is rowin’ it with Nate Dunbar. I
reckon ye kin stop it, muy pronto, Buffler Bill. Hustle in an’ stop ’em
afore they git ter drorin’ hardware an’ throwin’ lead.”
The scout started for the office at a run.
C H A P T E R X X I V.
THE QUARREL.

The scout reached the door of the office, only to be grabbed by


one of the men who had been standing there and looking in, but
who had now retired with others to a safer position.
“Keep away!” breathed the man. “They’ve got their shooters out,
an’ there’ll be fireworks in a brace o’ shakes. If you go in there you’ll
be right in the middle of the celebration.”
“That’s where I want to be,” answered the scout, shaking the
hand from his arm, “and I want to get in there before the
celebration begins.”
He stepped to the door and looked in.
Nate Dunbar and Jake Phelps were standing no more than a
dozen feet apart, Phelps with his back to the counter and Dunbar
across the room.
Furious anger burned in the face of Jake Phelps. In Dunbar’s face
there was only determination—but it was deadly.
Each man held a revolver in his right hand, and each watched like
a cat for the first move of the other to lift his weapon. Only a hair’s
breadth separated these men from rash and ugly work.
Without a moment’s hesitation, Buffalo Bill sprang into the room
and placed himself squarely between Dunbar and Jake Phelps.
“I reckon this has gone far enough,” said he curtly.
“Buffalo Bill!” exclaimed Dunbar. “Get away, amigo, and give me
my chance at that hound!”
Dunbar’s voice, husky with pent-up passion, rang surprisingly in
the scout’s ears. He had not much time to remark upon the depth of
the young rancher’s feeling, however, before his keen eye caught a
hostile move of Jake Phelps’ right hand.
In the wizardry of six-shooter practice, Buffalo Bill was second to
none. Jake Phelps was perhaps a fraction of a second in lifting his
revolver, yet, in that brief period of time, the scout had drawn—not
only his own revolver, but also a very effectual “bead.”
“Down with that hand!” he ordered. “Don’t you dare say no to
me!”
The compelling voice of the scout, no less than the bewildering
magic that loaded his right hand with a six-shooter, caused Jack
Phelps to gasp. From sheer amazement he suffered the hand to
drop.
“That’s right,” said the scout, “but see that you keep that hand
where it is. Just remember, Jake Phelps, that what I miss in the
original deal I always make up in the draw. You’re a friend of mine,
Nate?”
He kept his back to Dunbar and his eyes on Phelps as he asked
the question.
“Great guns,” cried the young rancher, “don’t I owe you about
everything I’ve got in the world?”
“I wouldn’t put it so strong as that, Nate,” said the scout, with a
quiet laugh. “If you’re my friend, though, you’ll put up your gun. I’ll
guarantee that Jake Phelps doesn’t take any advantage of you.”
“But you don’t understand——”
“I’m going to understand all about this before I get through. In
the meantime, you’ll please understand that I have requested you to
put up your revolver.”
“She’s up,” said Dunbar promptly.
“Buenos! Now, Nate, kindly talk at the back of my head and tell
me the cause of this flare-up.”
Old Nomad was standing in the door, leaning negligently against
the door casing and fanning himself with his hat. Pard Buffler was
“on the job,” and the trapper realized that there wasn’t any cause for
any one to worry. But that peacemaker racket, while all right in its
way, wasn’t making much of a hit with Nomad.
“I was sitting here minding my own business,” said Dunbar, “when
Jake Phelps came in. He began saying things to r’ile me. His palaver
wasn’t thrown at me, but was fired at the clerk. I allowed him to talk
about me as much as he pleased, but when he turned his dirty
tongue loose on Dick Perry, then on you, and, at the last, dragged in
the name of my wife, my patience had reached the limit. He’s a low-
down whelp!”
“What did he say about me?” inquired the scout.
“He said you were a meddler in other men’s affairs and——”
“Which was the truth, in a way.”
“It wasn’t so much what he said about you as the way he said it.”
In the West there are some things a man has to say with a smile—
if he would avoid gun play.
“Anything else, Nate?” asked the scout.
“Well, he remarked that Dick Perry was a blackguard an——”
“Waugh!” came from the door. “Did he refer ter me with any o’ his
fool talk, Nate?”
“No.”
“I’m relieved a hull lot,” grinned the trapper. “Ef he’d er called me
a goat, er somethin’ like thet, I mout hev shot him up.”
“Got anything to tell us, Jake?” asked the scout.
“Well, yes,” answered Jake; “you fellers over at the Star-A ranch
are a lot of measley tin horns. You can put up a good front, but your
work is all rhinecaboo. I rode into town after the H-P pay-roll, and
strolled in here to stuff the coin into my saddlebags. I saw Dunbar.
What I said, I said so as to show this town he ain’t half a man.” Jake
Phelps laughed, and looked around in a cheap attempt at bravado.
“He dassen’t fight. Everybody can see that.”
“Anybody can see with half an eye that Nate Dunbar has you beat
a mile in everything that makes a man a man. You’re nine-tenths
pure guff, Jake, and the other tenth is just plain dog.”
The scout put up his revolver. Phelps was still armed, but the
scout looked him squarely in the eye and he made no attempt to use
his weapon.
“You’ve got your pay-roll money, have you?” went on Buffalo Bill.
“What business is that of——”
“That’s going far enough. I’ll give you five minutes to get out of
town.”
“Ho!” glowered Jake. “You the boss of this town? You got more ter
say about things in Hackamore than the sheriff?”
“Never mind that. If you’re not out of town in five minutes, I’ll go
gunning for you myself.”
“I’ll take a shot at that meachin’ whelp behind you yet!” gritted
Jake. “He can’t make any dead-set at me without getting all that’s
coming. I’ll have his scalp, that’s what I’ll have. I’m going to make a
widder of Mrs. Dunbar, and then Lige Benner——”
The scout jumped at Phelps, grabbed him by the shoulders, and
flung him bodily toward the door. Old Nomad stepped aside and
helped him out of the room with a kick. The clerk, who had been on
hands and knees behind the counter, carried out Phelps’ saddlebags
and threw them after him.
From the hitching pole, where his horse was tied, Jake Phelps
swore and howled his threats.
“I’ll square up with you for all this, my buck!” shouted Nate
Dunbar, from a window.
“You’ll have to get Buffalo Bill’s permission to call your soul your
own before you do,” taunted Jake, tying the bags to the saddle,
mounting, and spurring away.
Dunbar turned to the scout with a gloomy face.
“Amigo,” said he, “it would have been better if you’d let me had it
out with that skunk.”
“There was nothing to the row, Nate,” the scout answered.
“Phelps has had too much red eye, and you lost your temper too
easily. Have you finished your work here?”
“Yes.”
“Then you’d better ride for the Star-A ranch, Nate. And don’t
forget yourself and take the trail to the Phelps outfit.”
“You know me too well for that,” answered the young rancher.
“When I say I’ll do a thing don’t I generally do it?”
“You do,” returned the scout gravely, “and that’s what makes Nate
Dunbar stack up so high with me. You’ll leave Jake Phelps alone?”
“Yes.”
“Thet’s ther tork, pard,” approved old Nomad. “Even a measley,
no-’count yaller pup like Jake Phelps kin shoot. It would be tough on
that Hattie girl if you was wiped out. Go home, Nate, an’ tell ’em out
thar ter the ranch thet Buffler an’ Pard Nomad hev struck town and
aire already at their peacemakin’.”
Nate pricked up his ears.
“I was wondering why you were here,” said he.
“We’ve come to see Bloom, the sheriff.”
“Bloom’s travelin’ this-a-way as fast as his legs kin kerry him,”
spoke up Nomad, taking a squint through the door and up the
street.
“Then here’s where I pull out,” said Nate. “There’s no love lost
between Bloom and me, and if I met him now and he gave me any
of his back talk, the fur would fly. Be back to the ranch soon, Buffalo
Bill?”
“To-morrow, I hope.”
Dunbar left the hotel by a rear door. Old Nomad, with a queer grin
on his weather-beaten face, pushed into the office and dropped on a
chair.
“Now fer more peacemakin’,” he remarked, “an’ from ther looks o’
ther sher’ff, I reckon et’ll be real saloobrious. I’m fixin’ ter enjoy
what’s comin’, I am so.”
“There’ll be no trouble,” said the scout, himself taking a seat.
“Waal, ef thar is, I shore reckon they’ll hev ter git another sher’ff
ter bloom in this man’s berg.”
A moment later the sheriff rushed into the room. He was at white
heat, and the looks he threw at the scout and the trapper were
anything but reassuring.
The crowd outside once more clustered about the open door and
the windows. There was to be something more doing, and each
spectator held his breath and watched and listened.
“Somebody said there was a row here,” growled Bloom. “I heard
up the street that Jake Phelps an’ that pesky trouble maker, Nate
Dunbar, was roughin’ it with each other.”
The sheriff was addressing himself to the hotel clerk, but Buffalo
Bill took it upon himself to answer.
“They didn’t get so far as an exchange of shots, sheriff. I
happened in, just as the affair began to look serious, and ordered
Jake Phelps out of town.”
Bloom had whirled away on his heel as soon as the scout began to
speak; then, suddenly changing his mind, he whirled back when he
had finished.
“You ordered him out o’ town?” he scowled.
“Oh, yes,” answered the scout passively. “If they had both stayed
in town there would have been trouble.”
“Tell me this, you who make yourself so high and mighty wherever
you happen to plant yourself: What business you got orderin’
anybody out o’ Hackamore?”
A glimmer arose in the scout’s eyes.
“Well,” said he, “if you come to simmer it down to a fine point, I
was doing business that you ought to have been around here to
attend to.”
“You my deperty?” flared Bloom; “have I ever asked you to help
me?”
“No, Bloom; I sort of asked myself.”
“You take my advice, Cody, and keep hands off my work. You and
I have come together once, and if that ever happens again, sparks
are sure goin’ to fly.”
There was only the clerk in the office, apart from the scout, the
trapper, and the sheriff. The spectators kept outside, confining their
view of what was going on to the open door and the windows.
“Right here, then,” said Buffalo Bill, “is where the sparks begin to
fly.” He turned to the trapper. “As it may get rather hot for some of
the people outside, Nick,” he added, “you’d better close the door.”
“On ther jump, pard,” carolled Nomad.
The trend of affairs was vastly to his liking.
“Leave that door open!” snarled the sheriff.
Nomad’s answer was to slam the door, turn around, and put his
back to it.
“How does thet hit ye?” he asked truculently.
“There’s more’n one door,” grunted the sheriff, moving toward the
dining-room entrance.
The scout got up and barred the way in that direction. For an
instant the sheriff glared, one hand half starting toward his hip.
“I have only the most peaceable intentions, Bloom,” said the
scout, as pleasantly as possible. “There’s a little matter I want to talk
over with you.”
“There ain’t any matter, little or big, that I want to talk over with
you,” snapped Bloom.
“This has to do with your business. From what you’ve just been
saying, you’re mighty particular to attend to your own business,
seems to me.”
The sheriff grunted and swept his eyes toward the two windows.
In each opening were framed as many excited faces as could crowd
into it. Bloom felt that the eyes of the town were upon him, that his
prestige would suffer if he did not in some way stir himself.
“Sit down,” proceeded the scout; “have a cigar and we’ll smoke a
talk.”
There was a friendly smile on Buffalo Bill’s face as he held out a
weed.
With a muttered oath the sheriff grabbed the cigar, crushed it in
his thick fingers, and flung it in the scout’s face. A gasp came from
the faces in the windows.
“Snarlin’ catermounts!” fumed the trapper. “Ef ye don’t make him
eat thet cigyar ye ain’t no friend o’ mine.”
The scout was still smiling.
“Sit down, Bloom.”
The voice was as soft as velvet, but it cut like steel.
The sheriff invited the scout to go to a warmer region than the
Brazos, and started to brush by in the direction of the rear door.
Then something happened. It happened with a suddenness that
deceived the eye.
One moment Bloom was pushing for the rear door, and the next
he was sprawled in a chair, and the scout had the revolver that had
been dangling from his belt.
A titter came from the windows, and a whoop from old Nomad.
“Et ain’t well ter fool with We, Us an’ Comp’ny when we’re loaded,”
exulted the trapper, “er when we’re out spreadin’ harmony an’ good
will up an’ down ther Brazos.”
The sheriff’s face was as black as a thundercloud. He realized fully
the ignominy of his position—and, quite as fully, his own
helplessness.
“More of your high-handed proceedings,” he ground out. “Some
day you’ll get jumped on good and proper for your meddlin’, and
after that you’ll ’tend to your own business an’ let other folks’
business alone.”
“Some day,” said the scout, “but not to-day. Try and be a
gentleman, Bloom. I reckon it’ll be hard for you, but, anyhow, make
the effort.”
The sheriff was beside himself with anger; in fact, he was so
wrought up that words failed him. He gurgled and glared. Old
Nomad stood at the door surveying the sheriff with great
satisfaction.
“Ther further we go on this hyar peacemakin’ tour, Buffler,” he
remarked, “ther better I like et.”
“Bloom,” pursued the scout, “a little history has been made during
the last few days, and one detail of it I am going to offer for your
attention. A man by the name of Ace Hawkins was shot and killed by
a fellow calling himself Red Steve.”
“You can’t tell me a thing I don’t know,” snorted the sheriff. “Ace
Hawkins was a desperado—he deserved all he got, no matter who
gave it to him.”
“Wrong, in two ways. Hawkins was not a desperado. He was a
man who was doing his best to further the cause of right and
justice. Error number one for you. Whether or not he deserved the
fate that overtook him, however, need command little of our
attention. It was not Red Steve’s place to hand out his destiny with
the point of a six-shooter. What have you done to apprehend Red
Steve?”
“Nothin’, and I won’t do anythin’.”
“Why not? Aren’t you sworn to look after the law in this county?”
“It ain’t part o’ my duty to take advice from you.”
“I’m going to tell you a few things, Bloom. Red Steve works for
Lige Benner, and you’ve a notion that Lige Benner wanted Ace
Hawkins sponged off the slate. You’re a friend of Benner’s. You think
it will please Benner if you don’t take any action against Red Steve.
Probably you’re right in your surmise, but you’re ’way wrong in
letting yourself be swayed by your likes and dislikes in a matter that
touches upon your duty as sheriff. You’d better take my advice and
help me and my pards lay Red Steve by the heels.”
This was straight talk, and as logical as it was straight. Bloom
knew the scout had the right end of the argument, and he hated to
have the men outside hear him lectured in just that way. The scout
had purposely raised his voice and spoken deliberately and clearly, in
order that his words might carry, and his full meaning reach the ears
of the townspeople.
“Confound you and your advice!” barked Bloom. “I know what my
duty is a heap better’n you, and I’m here to stand by it.”
“Will you stand by your duty, in this case,” fenced the scout, “or
will you stand by Lige Benner and Red Steve?”
“I ain’t goin’ to tell you what I’ll do. What’s more, I’ve got enough
o’ this talk.”
“Then you’re going to get more than enough, Bloom, because I’m
not more than half done. In shielding Red Steve you’re trying to
shield Lige Benner. You’re afraid that if you press matters against
Red Steve that it will be shown that Lige Benner had at least a guilty
knowledge of Red Steve’s murderous intentions against Hawkins.
Isn’t that it?”
Steadily, relentlessly, the sheriff was being forced into a tight
corner. It was like a trial. Bloom, accused of dereliction of duty, was
being catechised by the scout, and the townspeople outside were
the jury. Between duty and private desire the unfortunate sheriff
writhed and sputtered.
“I’m not going to take any more talk from you,” he shouted.
“There’s a hull lot to this Red Steve matter you don’t know anything
about.”
“I know all about it,” declared the scout, “much more, in fact, than
you do.”
“How do you know Red Steve did that shooting?”
“Ace Hawkins said so.”
“That’s what you say,” sneered the sheriff.
“There are others who heard Hawkins make his statement, and
they will bear me out. Wild Bill Hickok, for one——”
“He’s your pard. I wouldn’t believe him any quicker’n I’d believe
you.”
Old Nomad’s gorge was rising. The sheriff was a coyote, and
Buffalo Bill was putting up with too much from him. He made an
attempt to slip in a few words, but the scout looked toward him and
waved him to silence.
“There’s the sky pilot, Jordan,” went on the scout. “He’ll back up
my statement. I reckon there’s not a man on the Brazos who would
refuse to believe the sky pilot.”
This statement rather floored the sheriff.
“When the sky pilot talks to me,” said he, “then I’ll know what to
think, but——”
Just here the door opened at old Nomad’s back. He turned quickly
to deny the newcomer entrance, but recoiled when he saw who was
coming into the office.
“Benner!” exclaimed old Nomad, wondering what this new move
was to signify.
“Benner!” cried Bloom, jumping to his feet.
Benner pushed on into the room and came to a halt within a short
distance of the scout.
“Yes, Benner,” said the cattle baron. “I’ve come here to say that
Buffalo Bill is right. Red Steve was the man who did the trick for Ace
Hawkins. Is that enough for you, Bloom?”
The scout was surprised by this totally unexpected coming of Lige
Benner—surprised, perhaps, far more by his appearance and his
words than by the mere fact of his presence.
There was a haggard, careworn look in Benner’s face—an
earnestness in his manner that contrasted strongly with his
spectacular attire.
If the scout was surprised by Benner’s words, the sheriff seemed
even more so. He stared.
“Come again with that, Benner,” said he.
“I’ve been standing outside listening to what was going on in
here,” continued Benner. “The time came when I thought I ought to
take part in the talk. Red Steve is guilty of shooting Ace Hawkins. I
had nothing to do with the crime, and knew nothing about it until it
was accomplished. Both men worked for me. Red Steve himself told
me he was guilty, and tried to find excuse for what he had done by
saying that Ace Hawkins was a traitor, that he was working for me
and trying to help Perry and Dunbar. That, of course, was no excuse
at all. I told him he would have to come to Hackamore and stand
trial. It was my intention to bring him myself, but he escaped on foot
from the ranch and, at the present moment, is somewhere on the
Brazos, a fugitive. I rode to town to get you to take up the pursuit of
Red Steve. It’s up to you, Bloom.”
Lige Benner dropped wearily into a chair and drew one hand
across his forehead. Bloom continued to stare at him, Nomad
regarded him with suspicion, and only the scout—adept at reading
motives in a man’s face—gave him approval.
“That’s the talk, Benner!” the scout exclaimed.
“Don’t ye bank too much on his tork, Buffler,” put in the old
trapper. “Lige Benner is tricky; he’s showed himself ter be a snake in
the grass right along; an’ how d’ye know he ain’t got somethin’ up
his sleeve right now? Don’t give him a chance ter trap ye.”
Benner flung himself around in his chair, but the fierce protest
faded from his face as he looked at Nomad.
“I’ve made mistakes, I reckon,” said Benner slowly, “a lot of ’em,
but I’m not making any mistake now, old Nomad, and don’t you
make any. I’m tired of this squabbling in the cattle country. I’ll admit
I never liked Perry or Dunbar. They blew in here and spoiled one of
the objects I had set my heart on achieving. I did everything I could
to carry out that object, but the scout and his pards made that
impossible; then, listening to advisers, I set out to secure revenge.
There I failed again. My hands are in the air. Now I want Red Steve
captured, so it can be proved that I had nothing to do with what
happened to Ace Hawkins.”
“If he’s captured,” returned the scout, “are you willing to cry quits
in this fight on Perry and Dunbar? Will you be for peace in the cattle
country, Benner?”
“I’m for peace now,” was the reply; “if I hadn’t been I shouldn’t
have come here as I did to-day.”
“I believe you,” said the scout quietly. “Have you any idea where
Red Steve can be found, or what he intends to do?”
“If he is hunted for at once, he’ll be found somewhere on the
Brazos. He got away, as I said, on foot. Since he has no horse, about
the first move he makes will be to get a mount somewhere. After he
does that it will be hard to capture him. He knows this country like a
book, and he’ll hole himself away where he’ll never be found.”
“My pards are looking for Red Steve on the river,” proceeded the
scout. “If he’s there, you can gamble that they’ll find him.”
“I’ve sent out some of my cowboys to prosecute the search.
Between them and your pards, Buffalo Bill, the chances seem pretty
fair for taking the scoundrel. You understand my attitude? There
may be a suspicion that I was back of Red Steve in the shooting of
Ace Hawkins. I want that suspicion brushed aside and my entire
innocence made clear. Red Steve is the one to do this. Whatever else
I have done, I’ve never tried to get any man’s blood on my hands.
I’ve gone far in this war with Perry and Dunbar, but never so far as
that.”
A sneer curled Bloom’s lip as he gazed at Benner.
“Lost your nerve, have you?” he rasped.
Benner lifted his eyes to Bloom’s.
“You’ll find,” said he, “that I have plenty of nerve to avenge any
insult you heave at me. Walk softly, Bloom, when you’re going over
my feet. That’s my advice to you. So far as Dunbar and Perry are
concerned. I’ve buried the hatchet; but, so far as you are concerned,
I’ll dig it up if you give me half a chance. Spread your blankets and
go to sleep on that.”
Benner’s spirit was not broken. There was plenty of snap and
ginger in his words. It was clear to the scout that the cattle baron
was swerved by only one motive, and that was to have Red Steve
captured, so that the owner of the Circle-B ranch would be cleared
of the taking off of Ace Hawkins.
The capture of Red Steve, therefore, had become a factor in the
business Buffalo Bill was so anxious to accomplish—the peace of the
Brazos country.
“I’m mighty glad,” scowled Bloom, in no wise relishing the manner
of the cattle baron, “that Hank Phelps is still got the nerve to hold
his grudge against Perry and Dunbar.”
“Don’t be too sure of that,” said Benner. “Phelps is a friend of
mine, and I’m going to see him to-morrow. I think he’ll promise to
coöperate with me in establishing peace on the Brazos. He’s about
as tired of these foolish squabbles as I am.”
He got up and moved toward the door.
“We’re on good terms now, Buffalo Bill?” he asked, halting at the
threshold.
“Yes,” answered the scout.
“Well, I’ve gone on record. All these men”—he waved his hand
toward the faces in the windows—“are witnesses. From now on,
Perry and Dunbar will receive from me the same treatment other
ranchers on the river give each other. That shot goes as it lays.”
He left the hotel, and could be seen making his way through the
crowd in front.
“Gi’me that gun!” snapped Bloom, stretching out his hand to the
scout.
The weapon was handed over without comment. Then Bloom
himself started for the door.
“Has he got the right ter leave, Buffler?” asked Nomad.
The scout nodded. The trapper stepped aside, and Bloom flung
out of the office. Nomad came over and dropped down in a chair
beside the scout.
“Waugh!” he muttered. “Blamed ef we didn’t git out o’ thet
without er fight. I never thort we would, one spell. But I ain’t takin’
none too much stock in this hyar flop o’ Benner’s. Et’s too suddent.”
“Benner’s all right, Nick,” averred Buffalo Bill, with confidence.
“Shore he ain’t figgerin’ on somethin’?”
“I’m sure he is figuring on something. The shooting of Ace
Hawkins might have far-reaching results for him; so he wants Red
Steve captured, so he can be forced to tell the truth.”
“Sufferin’ twisters! Why, Benner hired Red Steve in the fust place
bekase he was a desperado, an’ willin’ ter do any leetle job a honest
cowpuncher might shy around. Now thet Red Steve’s done jest what
Benner mout hev knowed he’d do, Benner gits what looks like an
attack o’ narves. I kain’t b’leeve in et, not complete.”
“I never thought Benner was so desperate as some folks tried to
make out,” Buffalo Bill answered. “He has his good points, Nick.”
“Up ter now,” said Nomad dryly, “he’s been purty successful
keepin’ his good p’ints buried out o’ sight. But I’m s’prised at one
thing.”
“What’s that?”
“Why, Bloom an’ Benner ain’t the team I thort they was. They ain’t
pullin’ tergether like they was well matched.”
“It looks as though we’d been a little wide of our trail, old pard,”
said the scout. “We’ve been thinking, all along, that Bloom, by his
ugly actions, was trying to keep on the right side of Lige Benner. I
think, come to sift the reasons close to bed rock, that Bloom is in the
game against Perry and Dunbar just because he hates the Star-A
ranchers. He’s taken a dislike to them—to Nate in particular—and
that’s why he acts as he does.”
“Mebbyso. He’s ’er whelp. He’d do a heap ter land on Nate
somehow. I’m bettin’——”
A pounding of hoofs out in front, suddenly brought to a stop, a
concerted rush of the men around the hotel toward the hitching
pole, and a wild voice suddenly lifted, caused the old trapper to
break off his remarks. The voice, husky with excitement, floated into
the office through the open front door.
“Where’s a doctor? I want a doctor on the jump!”
Buffalo Bill and old Nomad, at this startling summons, left their
chairs and went to the door.
A cowboy, his horse lathered and panting painfully, was at a halt
before the hotel. A crowd of curious men surrounded him.
“I’ll go fer a doctor,” said Sim Pierce, and hustled off without
waiting for further news.
“What’s the matter?” asked the scout.
“I was lopin’ inter town with a pard,” replied the cowboy, “when
we found Jake Phelps’ hoss, without no saddle, runnin’ to’rds ther
ranch. A mile farder we found Jake hisself, layin’ face down in the
trail. He come in arter the pay-rool money, an’ the money was gone.
Jake was about gone, too, an’ he may be clean gone by now. I left
Jeems with him, while I hit the breeze fer a sawbones. We gotter
have the doc in er hurry, an’ mebby it won’t do no good at that.”
This news hit the scout between the eyes. Already the bystanders
were exchanging significant glances.
The scout grabbed Nomad’s arm and pulled him back into the
office.
“This looks bad, pard,” he whispered.
“Ye don’t think Nate had anythin’ ter do with what happened ter
Jake Phelps?” gasped the old trapper.
“Certainly not, but there are others who’ll think so—after what
happened between Nate and Jake Phelps here in Hackamore. Take
my word for it, Bloom will be the first one to voice the suspicion.”
C H A P T E R X X V.
SIM PIERCE BRINGS NEWS.

The cowboy jumped from his weary horse, loosened the cinches
to give the animal’s lungs greater freedom, and came into the office
to wait for the doctor.
The cowboy was excited, and tramped up and down, rolling a
cigarette.
“You’re from Hank Phelps’ ranch?” asked the scout.
“That’s me,” was the answer. “My name’s Quiller, an’ I’ve worked
fer Hank for two years. He’s all right, Hank is.”
“How was Jake Phelps hurt?”
“Looks like he’d been hit on the head with a club er somethin’.”
“Then he wasn’t shot?”
“Not as Jeems an’ me could see. But I didn’t tarry long arter we
found Jake; I jest hustled right in arter the doc. There was some
queer things about Jake’s fix. The feller that swiped the pay-roll
money took Jake’s saddle along. What’s this I hear about Jake’s
havin’ a row with Nate Dunbar afore leavin’ fer home?”
“They had some words, Quiller,” answered the scout.
“I’m wonderin’—I’m wonderin’——”
Quiller was leaning against the counter, holding a lighted match to
his cigarette.
“You’re wondering,” spoke up the scout, “whether Nate Dunbar
had anything to do with what happened to Jake Phelps. Well, stop
your wondering. He didn’t.”
“But the’ was bad blood between ’em, wasn’t they?” went on the
cowboy, wrinkling his brows. “When they separated didn’t they both
say they’d git even with each other? An’ didn’t Dunbar hit the trail
right arter Jake did?”
“All that happened, yes. But that doesn’t prove anything against
Nate. I’m rather thinking that it makes the future dark for Red
Steve.”
Old Nomad jumped at that; and Quiller, the match going out
without lighting his cigarette, flung away the burnt firestick and
groped in his pocket for another.
“What about Red Steve?” demanded Quiller.
“He’s loose in the Brazos country,” answered the scout. “Benner
was going to bring him to Hackamore for the shooting of Ace
Hawkins, but Red Steve slipped away from the Circle-B ranch on
foot.”
“On foot, hey? Then why didn’t Red Steve, if he done this, take
Jake’s hoss? Red Steve wouldn’t never hev let the hoss git away
from him arter he had nabbed the money.”
“Perhaps Red Steve had a horse already,” suggested the scout.
“It’s possible he picked up a horse without any gear, and that he
took the saddle to ride in.”
“It’s possible, I reckon.”
But it was plain that Quiller’s mind was running on Nate Dunbar.
Circumstances seemed to point more decisively in the direction of
the Star-A rancher than toward Red Steve.
“The man who took the money,” pursued the scout, noting the
trend of the cowboy’s thoughts, “was the man who look the saddle.
Nate Dunbar’s not a thief.”
“It’s hard ter tell what a man is when he makes a play o’ this
kind.”
“And certainly Nate wouldn’t take the saddle. Why should he? He
had a good saddle of his own.”
This fact seemed to make some impression on Quiller. Before he
could express himself, however, the doctor came riding up in front.
With the doctor was Bloom and Sim Pierce, both ready for the trail.
“Come on, you there!” roared Bloom.
Quiller ran out, tightened his cinches, swung into the saddle, and
the four riders fared out of town at a gallop.
“See how it is, Nick?” queried the scout. “Already suspicion is
leveled at Nate Dunbar. You can gamble that Bloom will do
everything possible to make it bad for the boy. I reckon we had also
better be getting saddle leather between our knees.”
“Ter go whar, Buffler?”
“Why, to the H-P ranch. I want to watch this thing and find out
just what develops. We must keep in touch with every detail. It’s
liable to mean a whole lot for Nate.”
“Waugh! Ye’re shore right thar. But et’s Red Steve as turned ther
trick, ye kin take et from me. When’ll we ride?”
“Now.”
“Whoop! When ye tune up like thet, ye shore ketch me plumb
whar I live. Spurs an’ quirts an’ a call on Hank Phelps. This hyar
peace bizness is gittin’ some excitin’.”
Pinkney brought out their saddles and bridles. Bear Paw and old
Hide-rack seemed surprised at the sudden getaway. Probably, in
their brute minds, they had been expecting an all-night stay in the
comfortable corral.
“It beats the nation,” remarked the scout, when he and his old
pard were galloping along the trail, “what beastly luck comes Nate
Dunbar’s way.”
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