developing java servlets
TRANSCRIPT
![Page 1: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/1.jpg)
![Page 2: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/2.jpg)
James Goodwill
800 East 96th St., Indianapolis, Indiana, 46240 USA
Developing Java™
Servlets
![Page 3: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/3.jpg)
Developing Java™ Servlets,Second EditionCopyright © 2001 by Sams Publishing
All rights reserved. No part of this book shall be reproduced, stored in aretrieval system, or transmitted by any means, electronic, mechanical, photo-copying, recording, or otherwise, without written permission from the pub-lisher. No patent liability is assumed with respect to the use of the informationcontained herein. Although every precaution has been taken in the preparationof this book, the publisher and author assume no responsibility for errors oromissions. Nor is any liability assumed for damages resulting from the use ofthe information contained herein.
International Standard Book Number: 0-672-32107-6
Library of Congress Catalog Card Number: 00-111799
Printed in the United States of America
First Printing: June 2001
04 03 02 01 4 3 2 1
TrademarksAll terms mentioned in this book that are known to be trademarks or servicemarks have been appropriately capitalized. Sams Publishing cannot attest tothe accuracy of this information. Use of a term in this book should not beregarded as affecting the validity of any trademark or service mark.
Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate aspossible, but no warranty or fitness is implied. The information provided is onan “as is” basis. The author and the publisher shall have neither liability norresponsibility to any person or entity with respect to any loss or damages aris-ing from the information contained in this book.
PUBLISHER
Paul Boger
EXECUTIVE EDITOR
Michael Stephens
ACQUISITIONS EDITOR
Carol Ackerman
DEVELOPMENT EDITOR
Tiffany Taylor
MANAGING EDITOR
Matt Purcell
PROJECT EDITOR
Christina Smith
COPY EDITOR
Cynthia Fields
INDEXER
Erika Millen
PROOFREADER
Benjamin Berg
TECHNICAL EDITOR
Rob Tiffany
TEAM COORDINATOR
Lynne Williams
INTERIOR DESIGNER
Anne Jones
COVER DESIGNER
Aren Howell
PAGE LAYOUT
Ayanna LaceyHeather Hiatt MillerStacey Richwine-DeRome
![Page 4: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/4.jpg)
OverviewContents 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
![Page 5: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/5.jpg)
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
![Page 6: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/6.jpg)
ContentsIntroduction 1
1 Web Applications and the Model View Controller (MVC) Design Pattern 7
The Model View Controller (MVC) Design Pattern ..............................8A Server-Side Implementation of the MVC............................................8
Servlets as MVC Controllers..............................................................9JSPs as MVC Views ........................................................................10
Summary ................................................................................................10
PART I Servlet Fundamentals
2 Servlet Overview and Architecture 15Movement to Server-Side Java ..............................................................16Definition of a Java Servlet ..................................................................16Practical Applications for Java Servlets ................................................16Java Servlet Alternatives........................................................................17
Common Gateway Interface ............................................................17Proprietary APIs ..............................................................................18Server-Side JavaScript......................................................................18Microsoft’s Active Server Pages ......................................................18
Reasons to Use Java Servlets ................................................................19Efficiency..........................................................................................19Persistency ........................................................................................19Portability ........................................................................................19Robustness ........................................................................................19Extensibility......................................................................................20Security ............................................................................................20
The Java Servlet Architecture ................................................................20GenericServlet and HttpServlet........................................................20
Summary ................................................................................................23
3 Servlet Basics 25The Life Cycle of a Servlet ..................................................................26
The init() Method ............................................................................26The service() Method ......................................................................26The destroy() Method ......................................................................27
A Basic Servlet ......................................................................................27The BasicServlet Source ..................................................................27
Dissecting the BasicServlet ..................................................................29Where Does the BasicServlet Fit into the Servlet Framework? ......29The Methods Overridden by the BasicServlet ................................30
Summary ................................................................................................31
![Page 7: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/7.jpg)
DEVELOPING JAVA SERVLETS, SECOND EDITIONvi
4 Servlets and HTML 33Retrieving Form Data in a Servlet ........................................................34
Servicing the GET and POST Requests ..........................................34How the FormServlet Works ............................................................38
Summary ................................................................................................39
5 Servlet Sessions 41What Is Session Tracking? ....................................................................42Using Hidden Form Fields ....................................................................42Working with Cookies ..........................................................................46URL Rewriting ......................................................................................50Session Tracking with the Servlet API ..................................................51Summary ................................................................................................58
6 HTTP Tunneling 59What Is HTTP Tunneling? ....................................................................60Object Serialization................................................................................60Creating an HTTP Tunneling Client......................................................66Creating an HTTP Tunneling Servlet ....................................................71A Practical HTTP Tunneling Example..................................................73
The OrderStatusApplet ....................................................................74The OrderStatusServlet ....................................................................80
Pros and Cons of Applet-to-Servlet Communication ............................83Summary ................................................................................................84
7 Servlets, JDBC, and Inter-Servlet Communications 85What is the JDBC? ................................................................................86Two- and Three-Tier Database Access Models ....................................86JDBC Driver Types................................................................................87
Type 1: JDBC-ODBC Bridge, Plus ODBC Driver ..........................88Type 2: Native-API, Partly Java Driver............................................88Type 3: JDBC-Net, Pure Java Driver ..............................................89Type 4: Native-Protocol, Pure Java Driver ......................................90
JDBC Basics ........................................................................................92Installing and Setting Up a Type 1 Driver ......................................92Establishing a Database Connection ................................................93Performing the Basic SQL Commands ............................................94
A Basic JDBC Servlet ........................................................................107A JDBC Connection Pool....................................................................112Inter-Servlet Communications ............................................................123Summary ..............................................................................................130
![Page 8: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/8.jpg)
CONTENTSvii
8 Servlets and JavaMail 131JavaMail and Internet E-mail ..............................................................132
JavaMail Services ..........................................................................132Preparing to Use JavaMail ..................................................................133A JavaMail Example............................................................................133Using JavaMail in a Servlet ................................................................137Summary ..............................................................................................141
9 Servlet Security 143Introduction to Security ......................................................................144Roll Your Own ....................................................................................144Basic Authentication ............................................................................148Digest Authentication ..........................................................................148Secure Sockets Layer (SSL) ................................................................149Summary ..............................................................................................150
10 Servlets and XML 151XML and Java......................................................................................153
Using the SAX API ........................................................................153Using XML in a Servlet ......................................................................159Summary ..............................................................................................162
11 Servlets and LDAP 163A Brief Discussion of Directories ......................................................164
Attributes ........................................................................................165Distinguished Names......................................................................165
LDAP ..................................................................................................165JNDI ....................................................................................................166Using JNDI to Access LDAP ..............................................................166
Installing Netscape Directory Server ............................................167Connecting......................................................................................168Searching the LDAP Server ..........................................................170Adding an Object to an LDAP Server............................................174Removing an Object ......................................................................176Modifying Information Stored in LDAP........................................177
Accessing LDAP from a Servlet..........................................................184Summary ..............................................................................................188
12 Servlets and Enterprise JavaBeans 189What Are Enterprise JavaBeans? ........................................................190EJB Terminology ................................................................................191Installing JRun ....................................................................................191The Enterprise JavaBean......................................................................192
Interfaces and Classes ....................................................................192Naming Conventions ......................................................................193
![Page 9: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/9.jpg)
DEVELOPING JAVA SERVLETS, SECOND EDITIONviii
Session Beans ......................................................................................194Stateless Versus Stateful ................................................................194Session Bean Interfaces and Classes..............................................195Deployment Descriptor ..................................................................200Client View of a Session Bean ......................................................204Session Bean Lifecycle ..................................................................205
Entity Beans ........................................................................................206Who Handles the Persistence? ......................................................206Entity Bean Interfaces and Classes ................................................207Deployment Descriptor ..................................................................215Client View of an Entity Bean........................................................217Entity Bean Life Cycle ..................................................................217
Deploying Your EJB to Your Application Server ................................218Packaging the jar File ....................................................................218Deploying the jar File ....................................................................220Viewing Deployed Beans ..............................................................220
Servlets as EJB Clients ........................................................................220Summary ..............................................................................................224
13 A Servlet Controller 225What Is a Controller? ..........................................................................226A Servlet Controller ............................................................................226The Service Interface ..........................................................................229A Sample Service ................................................................................230Summary ..............................................................................................232
PART II JSP Fundamentals
14 JSP Overview and Architecture 235What are JavaServer Pages? ................................................................236The Components of a JavaServer Page ..............................................237
Directives........................................................................................238Standard Actions ............................................................................240Implicit Objects ..............................................................................241JSP Scripting ..................................................................................242
Summary ..............................................................................................246
15 JSP Implicit Objects 247What are Implicit Objects? ..................................................................248The request Object ..............................................................................249The response Object ............................................................................250The pageContext Object ......................................................................251The session Object ..............................................................................252
![Page 10: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/10.jpg)
CONTENTS
The application Object ........................................................................254Testing the JSPs..............................................................................256
The out Object ....................................................................................257The config Object ................................................................................258The page Object ..................................................................................260The exception Object ..........................................................................260Summary ..............................................................................................260
16 JSP Standard Actions 261What Are Standard Actions?................................................................262JavaBean Standard Actions..................................................................262
The <jsp:useBean> Standard Action..............................................262The <jsp:setProperty> Standard Action ........................................263The <jsp:getProperty> Standard Action ........................................264A JSP Example Using JavaBeans ..................................................264
Other Standard Actions........................................................................268The <jsp:param> Standard Action ................................................268The <jsp:include> Standard Action................................................269The <jsp:forward> Standard Action ..............................................274The <jsp:plugin> Standard Action ................................................278
Summary ..............................................................................................279
17 Using JavaBeans and JSP Scopes 281The Counter JavaBean ........................................................................282page Scope ..........................................................................................283request Scope ......................................................................................284session Scope ......................................................................................286application Scope ................................................................................289Summary ..............................................................................................291
18 Handling JSP Errors 293JSP Translation-Time Errors................................................................294JSP Request-Time Errors ....................................................................294
Creating a JSP Error Page ..............................................................294Using a JSP Error Page ..................................................................297
Summary ..............................................................................................300
19 Custom JSP Tag Libraries 301JSP Customs Tags ................................................................................302Deploying Tag Libraries ......................................................................302
Creating a Taglib Descriptor ..........................................................302Deploying the Tag Handlers to Your Web Application ..................304Adding a taglib Entry to Your Web Application ............................304Adding the taglib Directive to Your JSP ........................................305
ix
![Page 11: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/11.jpg)
DEVELOPING JAVA SERVLETS, SECOND EDITION
Developing Custom JSP Tags Handlers ..............................................306Tags Without Bodies ......................................................................306Tags with Bodies ............................................................................311Tags with Attributes........................................................................314
Summary ..............................................................................................317
PART III Servlet and JSP Web Applications
20 Catalog Case Study 321Catalog Requirements..........................................................................322Models..................................................................................................322
Shopping Cart ................................................................................325Views....................................................................................................328
Catalog Layout ..............................................................................328Index View......................................................................................332Movie List View ............................................................................334Shopping Cart View........................................................................335Check Out View..............................................................................336
Controllers............................................................................................338The ListMovies Service..................................................................338The AddToCart Service ..................................................................341The EmptyCart Service ..................................................................343The CheckOut Service....................................................................343
Using the Online Catalog ....................................................................344Summary ..............................................................................................345
21 An LDAP Web Client 347Directory Requirements ......................................................................348Models..................................................................................................348Views....................................................................................................349
The Directory Layout ....................................................................349Index View......................................................................................351Directory View................................................................................352Add View ........................................................................................354
Controllers............................................................................................356The LDAPDirectory Service ..........................................................356The LDAPInsert Service ................................................................358The LDAPDelete Service ..............................................................359
Using the LDAP Application ..............................................................360Summary ..............................................................................................361
22 A Stock Trader 363Trader Requirements............................................................................364Models..................................................................................................364
x
![Page 12: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/12.jpg)
CONTENTS
Views....................................................................................................367Trader Layout ................................................................................367Index View......................................................................................370Get Quote View ..............................................................................371Buy/Sell View ................................................................................372
Controllers............................................................................................375The GetQuote Service ....................................................................375The Buy Service ............................................................................377The Sell Service..............................................................................380
Using the Trader Application ..............................................................382Summary ..............................................................................................383
23 Wireless Application Development Using WAP 385WAP History: Past, Present, and Future..............................................386
The Past: Handheld Device Markup Language (HDML) ..............386Present: WAP Hits the Street..........................................................387The Future: WAP 1.2 and Beyond ................................................387
Why WAP? ..........................................................................................389Screen Size Considerations ............................................................389Network Considerations ................................................................390Bandwidth Considerations..............................................................390
WAP Architecture ................................................................................391Emulators, Browsers, and Developer Tools ........................................392
Online Emulators............................................................................392WinWAP Browser ..........................................................................392Emulators and Developer Tools ....................................................394PDA WAP Browsers ......................................................................394Application Servers ........................................................................395
Suggested Resources............................................................................395Summary ..............................................................................................396
24 WML/WMLScript Development 397The Wireless Markup Language (WML) ............................................398
WML Language Basics ..................................................................398A WML Example ................................................................................401WMLScript ..........................................................................................405
Calling WMLScript from WML ....................................................406Language Basics ............................................................................406Operators ........................................................................................407Statements ......................................................................................407The Standard Libraries ..................................................................408WMLScript Example......................................................................409
xi
![Page 13: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/13.jpg)
DEVELOPING JAVA SERVLETS, SECOND EDITION
Wireless Application Developing Using Servlets................................412Configuring Server MIME Types ..................................................412A Quick “Hello World!” WML Servlet ........................................413Multiple Device Support ................................................................414Maintaining a Site in XML ............................................................414
Summary ..............................................................................................415
PART IV Appendixes
A Web Applications and Configuring the Servlet Engine 419Web Applications ................................................................................420
The ServletContext in Relation to the Web Application................420The Directory Structure..................................................................420Web Application Deployment Descriptors ....................................421
Web Archive (WAR) Files ..................................................................422Servlet Requirements ..........................................................................422Apache Tomcat ....................................................................................422
Installing the Tomcat Server ..........................................................422Adding the DJS Web Application ..................................................424Building and Installing the BasicServlet........................................426
Summary ..............................................................................................427
B The javax.servlet Package 429The javax.servlet Interfaces ................................................................430
The RequestDispatcher Interface ..................................................431The Servlet Interface ......................................................................432The ServletConfig Interface ..........................................................433The ServletContext Interface..........................................................434The ServletRequest Interface ........................................................440The ServletResponse Interface ......................................................445The SingleThreadModel Interface..................................................448
Classes..................................................................................................448The GenericServlet Class ..............................................................449The ServletInputStream Class ........................................................452The ServletOutputStream Class ....................................................452
Exceptions............................................................................................456The ServletException ....................................................................456The UnavailableException ............................................................458
C The javax.servlet.http Package 461Interfaces..............................................................................................462
The HttpServletRequest Interface ..................................................462The HttpServletResponse Interface................................................468The HttpSession Interface ..............................................................476The HttpSessionBindingListener Interface ....................................479
xii
![Page 14: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/14.jpg)
CONTENTS
Classes..................................................................................................479The Cookie Class............................................................................479The HttpServlet Class ....................................................................483The HttpSessionBindingEvent Class..............................................486The HttpUtils Class ........................................................................487
D The javax.servlet.jsp Package 489Interfaces..............................................................................................490
The HttpJspPage Interface..............................................................490The JspPage Interface ....................................................................491
Classes..................................................................................................492The JspEngineInfo Class ................................................................492The JspFactory Class......................................................................492The JspWriter Class........................................................................494The PageContext Class ..................................................................502
Exceptions............................................................................................511The JspError Exception ..................................................................511The JspException Exception ..........................................................512
E The javax.servlet.jsp.tagext Package 513Interfaces..............................................................................................514
The Tag Interface............................................................................514The BodyTag Interface ..................................................................520
Classes..................................................................................................522The BodyContent Class..................................................................522The BodyTagSupport Class............................................................523The TagSupport Class ....................................................................525The TagAttributeInfo Class ............................................................528The TagData Class..........................................................................530The TagExtraInfo Class ..................................................................532The TagInfo Class ..........................................................................533The TagLibraryInfo Class ..............................................................537The VariableInfo Class ..................................................................539
F WML (The Wireless Markup Language) 543WML Elements....................................................................................544
G WMLScript 547Lang Library ........................................................................................548
abort()—The abort Function ..........................................................548abs()—The abs Function ................................................................548characterSet()—The characterSet Function ..................................548exit()—The exit Function ..............................................................548float()—The float Function ............................................................548
xiii
![Page 15: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/15.jpg)
DEVELOPING JAVA SERVLETS, SECOND EDITION
isFloat()—The isFloat Function ....................................................549isInt()—The isInt Function ............................................................549max()—The max Function ............................................................549maxInt()—The maxInt Function ....................................................549min()—The min Function ..............................................................549minInt()—The minInt Function......................................................549parseFloat()—The parseFloat Function..........................................549parseInt()—The parseInt Function ................................................549random()—The random Function ..................................................550seed()—The seed Function ............................................................550
Float Library ........................................................................................550ceil()—The ceil Function ..............................................................550floor()—The floor Function ..........................................................550int()—The int Function ..................................................................550maxFloat()—The maxFloat Function ............................................550minFloat()—The minFloat Function ..............................................551pow()—The pow Function ............................................................551round()—The round function ........................................................551sqrt()—The sqrt Function ..............................................................551
String Library ......................................................................................551charAt()—The charAt Function ....................................................551compare()—The compare Function ..............................................551elementAt()—The elementAt Function..........................................551elements()—The elements Function ..............................................552find()—The find Function ..............................................................552format()—The format Function......................................................552insertAt()—The insertAt Function ................................................552isEmpty()—The isEmpty Function ................................................552length()—The length Function ......................................................552removeAt()—The removeAt Function ..........................................552replace()—The replace Function....................................................553replaceAt()—The replaceAt Function............................................553squeeze()—The squeeze Function..................................................553subString()—The subString Function ............................................553toString()—The toString Function ................................................553trim()—The trim Function..............................................................553
URL Library ........................................................................................553escapeString()—The escapeString Function ..................................554getBase()—The getBase Function..................................................554getFragment()—The getFragment Function ..................................554getHost()—The getHost Function ..................................................554getParameters()—The getParameters Function..............................554
xiv
![Page 16: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/16.jpg)
CONTENTS
getPath()—The getPath Function ..................................................554getPort()—The getPort Function....................................................555getQuery()—The getQuery Function ............................................555getReferer()—The getReferer Function ........................................555getScheme()—The getScheme Function........................................555isValid()—The isValid Function ....................................................555loadString()—The loadString Function..........................................555resolve()—The resolve Function....................................................555unescapeString()—The unescapeString Function ..........................555
WMLBrowser Library ........................................................................556getCurrentCard()—The getCurrentCard Function ........................556getVar()—The getVar Function ......................................................556go()—The go Function ..................................................................556newContext()—The newContext Function ....................................556prev()—The prev Function ............................................................556refresh()—The refresh Function ....................................................556setVar()—The setVar Function ......................................................556
Dialogs Library ....................................................................................557alert()—The alert Function ............................................................557confirm()—The confirm Function..................................................557prompt()—The prompt Function....................................................557
Index 559
xv
![Page 17: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/17.jpg)
About the AuthorsLead AuthorJames Goodwill is the co-founder and chief architect at Virtuas Solutions, LLC., located inDenver, 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 indeveloping 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 AuthorBryan Morgan is an experienced writer and software developer and founder of the WirelessDeveloper Network (http://www.wirelessdevnet.com) in 1999. He is a respected voice in thewireless industry, is a regular contributor to industry publications, and has been a featuredspeaker at numerous events. He holds a B.S. in electrical engineering from Clemson Universityand lives in Pensacola, FL with his wife Becky and beautiful daughter Emma.
![Page 18: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/18.jpg)
DedicationTo my girls Christy, Abby, and Emma.
AcknowledgmentsBefore I start thanking those close to home, I need to thank the people who made this bookwhat 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 tothank Carol Ackerman, my acquisitions editor, who answered all my questions and resolvedany 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 wouldlike to thank Christina Smith for managing the entire project. Each and every person made thisbook 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 upmy 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 daughtersAbby 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.
![Page 19: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/19.jpg)
Tell Us What You Think!As the reader of this book, you are our most important critic and commentator. We value youropinion and want to know what we’re doing right, what we could do better, what areas you’dlike 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, orwrite me directly to let me know what you did or didn’t like about this book—as well as whatwe 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 yourname and phone or fax number. I will carefully review your comments and share them with theauthor and editors who worked on the book.
Fax: 317-581-4770
E-mail: [email protected]
Mail: Michael StephensExecutive EditorSams Publishing201 West 103rd StreetIndianapolis, IN 46290 USA
![Page 20: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/20.jpg)
IntroductionStructure of This BookBefore you begin reading this book, you might want to take a look at its basic structure. Thiswill help you outline your reading plan, if you choose not to read it from cover to cover. Thisintroduction gives you an overview of what each chapter covers.
Chapter 1, “Web Applications and the Model ViewController (MVC) Design Pattern”Chapter 1 lays the foundation for the entire text. It introduces your to the Model ViewController design pattern. It also introduces you to a server-side implementation of the MVCand 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 toserver-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 ofa 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 retrieveform data in a servlet.
Chapter 5, “Servlet Sessions”Chapter 5 discusses several ways that you can maintain state while using servlets. The methodsthat it discusses include hidden form fields, cookies, URL rewriting, and session tracking withthe Servlet API.
Chapter 6, “HTTP Tunneling”Chapter 6 covers HTTP tunneling. It provides a definition of HTTP tunneling, describes objectserialization (which is required in tunneling), it describes the creation of a tunneling client andserver, and it gives a practical tunneling example. It also covers some of the pros and cons ofapplet to servlet communications.
![Page 21: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/21.jpg)
DEVELOPING JAVA SERVLETS
Chapter 7, “Servlets, JDBC, and Inter-ServletCommunications”Chapter 7 discusses how servlets can use the JDBC to interact with relational databases. Itgives a basic introduction to the JDBC and then combines the technology with servlets. It alsodiscusses 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 prosand cons.
Chapter 10, “Servlets and XML”Chapter 10 covers the basics of Extensible Markup Language, or XML. It discusses how to useSun’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 toaccess 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 froman 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 ModelView 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 tocreate a JSP document and understand what is happening behind the scenes at request time. Italso discusses the process a JSP file goes through when it is first requested.
2
![Page 22: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/22.jpg)
INTRODUCTION
Chapter 15, “JSP Implicit Objects”Chapter 15 discusses the JSP implicit objects and how they are commonly used. It also talksabout 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 youcan 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. Italso 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 andrespond 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 exampleincluding requirements, MVC components, and how to use the finished application.
3
![Page 23: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/23.jpg)
DEVELOPING JAVA SERVLETS
Chapter 23, “Wireless Application Development UsingWAP”Chapter 23 introduces you to wireless application development using Java servlets and theWireless Application Protocol (WAP), including the wide variety of client and server toolsavailable to the WAP developer. It includes an example in which you create a dynamic wirelessapplication 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 theServlet 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.tagextPackage”Appendix E covers the classes, interfaces, and exceptions of the javax.servlet.jsp.tagextpackage.
Appendix F, “WML (The Wireless Markup Language)”Appendix F provides a tag references for WML.
4
![Page 24: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/24.jpg)
INTRODUCTION
Appendix G, “WMLScript”Appendix G describes the libraries and functions used in WMLScript.
5
![Page 25: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/25.jpg)
![Page 26: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/26.jpg)
CHAPTER
1Web Applications and theModel View Controller (MVC)Design Pattern
IN THIS CHAPTER• The Model View Controller (MVC) Design
Pattern 8
• A Server-Side Implementation of the MVC 8
![Page 27: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/27.jpg)
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 andreusable Web applications: the Model View Controller (MVC). In this study we will also lookat exactly where and why both servlets and JSPs fit in this pattern. Because you have not yetcovered servlet and JSP technologies, you will have to accept some of the statements made inthis chapter. My goal for the remainder of this text is to show how and why this pattern andthese technologies work so well when developing server-side Java Web applications.
The Model View Controller (MVC) Design PatternThe 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 ofthese 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 isbeing manipulated and presented to the user.
View The View is the screen representation of the Model. It is the objectthat presents the current state of the Model.
Controller The Controller defines the way the user interface reacts to the user’sinput. The Controller is the object that manipulates the Model.
The major advantage of using the MVC design pattern is that it separates the Views andModels. As a result, you can separate presentation from business logic, and, in turn, create orchange Views without having to change the Models or the Controller logic that manipulates theModels. The MVC also allows Models to be represented by multiple Views.
A Server-Side Implementation of the MVCTo implement the MVC server-side pattern in Java we must combine JSPs and servlets. In thissection, we define a high-level server-side implementation of the MVC, where the Model is aJavaBean that represents the data being transmitted or received. The Controller is a servlet thatmanipulates or transmits data, and the View is a JSP that presents the results of the performedtransaction. Figure 1.1 models the steps involved in a sever-side implementation of the MVC.
DEVELOPING JAVA SERVLETS8
![Page 28: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/28.jpg)
FIGURE 1.1The 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 theWeb 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 abilityto 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 ontransactions, whereas the View programmers can focus primarily on presentation.
Servlets as MVC ControllersWe have chosen to use servlets as MVC Controllers after examining some of their strengthsand weaknesses.
Web Applications and the Model View Controller (MVC) Design Pattern
CHAPTER 1
1 WEB
APPLICA
TION
SA
ND
THE
MV
CD
ESIGN
PA
TTERN
9
Web Client WebServer
Servlet(Controller)
JSP(View)
DBMS
EJB/BEAN
EJB/BEAN
EJB/BEAN
EJB/BEAN
1.
6.
2.
5.
4.
3.
Application Server
![Page 29: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/29.jpg)
Strengths of servlets as Controllers are as follows:
• Servlets have very robust server-side processing capabilities because they have access toalmost the entire Java SDK.
• The servlet architecture lends itself well to a transactional style of programming, whichis 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 forMVC Controllers, where there will be fewer changes because the presentation logic has beenabstracted.
JSPs as MVC ViewsJavaServer Pages were chosen as MVC Views after a similar examination of their strengths andweaknesses.
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 inconfusing and difficult-to-maintain JSPs.
• If you plan to allow your HTML programmers to maintain your JSPs, which is verycommon, they will require a good understanding of Java.
After examining the previous lists, we can determine that JSPs make great candidates for MVCViews. This is because we can leverage a JSP’s access to Java objects, while conquering one oftheir major weaknesses by limiting scriptlet code to presentation only.
SummaryIn this chapter, we laid the foundation for the rest of this text. We looked at the MVC designpattern and saw how we could combine servlets and JSPs to implement a server-side solutionfor Web applications.
DEVELOPING JAVA SERVLETS10
![Page 30: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/30.jpg)
In the rest of this text we will study servlets and JSPs in the context of this model. We willexamine how servlets and JSPs work separately and then we will complete the text by combin-ing what we have learned into Web application case studies that implement the MVC.
Web Applications and the Model View Controller (MVC) Design Pattern
CHAPTER 1
1 WEB
APPLICA
TION
SA
ND
THE
MV
CD
ESIGN
PA
TTERN
11
![Page 31: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/31.jpg)
![Page 32: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/32.jpg)
IN THIS PART2 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 FundamentalsPART
I
![Page 33: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/33.jpg)
![Page 34: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/34.jpg)
CHAPTER
2Servlet Overview andArchitecture
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
![Page 35: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/35.jpg)
Movement to Server-Side JavaWhen the Java language was first introduced by Sun Microsystems Inc., its purpose was toembed greater interactivity into Web pages. Java has accomplished this through the use ofapplets. Applets add functionality to Web pages, but because of compatibility and bandwidthissues, businesses have started moving to server-side Java.
Java applets are programs that are embedded directly into Web pages. When a browser loads aWeb page, which contains a reference to an applet, the applet byte-code is downloaded to theclient computer and executed by the browser. This is fine for very thin clients, but as appletsgrow 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 acompatible browser, applets will not be presented with the proper content. These issues haveforced 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 theserver 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 ServletServlets are generic extensions to Java-enabled servers. Their most common use is to extendWeb servers, providing a very secure, portable, and easy-to-use replacement for CGI. A servletis a dynamically loaded module that services requests from a Web server. It runs entirely insidethe Java Virtual Machine. Because the servlet is running on the server side, it does not dependon browser compatibility. Figure 2.1 graphically depicts the execution of a Java servlet.
Servlet Fundamentals
PART I16
Web BrowserWeb Server
Servlet
Request
Response
FIGURE 2.1Execution of a Java Servlet.
Practical Applications for Java ServletsServlets 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 Ibelieve are some of the most important:
![Page 36: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/36.jpg)
• Developing e-commerce “store fronts” will become one of the most common uses forJava servlets. A servlet can build an online catalog based on the contents of a database. Itcan then present this catalog to the customer using dynamic HTML. The customer willchoose 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 theorders and place them in the database for fulfillment. Every one of these processes caneasily be implemented using Java servlets.
• Servlets can be used to deploy Web sites that open up large legacy systems on theInternet. Many companies have massive amounts of data stored on large mainframe sys-tems. These businesses do not want to re-architect their systems, so they choose to pro-vide inexpensive Web interfaces into them. Because you have the entire JDK at yourdisposal and security provided by the Web server, you can use servlets to interface intothese 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 arevery viable options for most Web applications.
Java Servlet AlternativesSome alternatives to using Java servlets are CGI, proprietary server APIs, server-sideJavaScript, or even Microsoft’s Active Server Pages. All these are viable solutions, but theyeach have their own set of problems. The following sections examine some of these issues.
Common Gateway InterfaceThe Common Gateway Interface (CGI) is one of the most common server-side solutions used todevelop Web applications. A CGI application is an independent module that receives requestsfrom 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 standardthat is used by most of today’s Web servers. Figure 2.2 shows the interaction between thebrowser, 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 ina slower response time, because the server must create and initialize a new address spacefor every process. You can also face the problem of running out of processes. Most
Servlet Overview and Architecture
CHAPTER 2
2
SER
VLET
OV
ERV
IEWA
ND
AR
CH
ITECTU
RE
17
![Page 37: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/37.jpg)
servers are configured to run a limited number of processes. If the server runs out, it willnot 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 itrequires the server to start a new interpreter for every request. This takes longer thanstarting 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 arequest to a CGI program that terminates before responding to the Web server, thebrowser has no way of knowing what happened. It just sits there waiting for a responseuntil it times out.
Servlet Fundamentals
PART I18
Web Server
New CGI1 ProcessClientRequest CGI1
New CGI1 ProcessClientRequest CGI1
New CGI1 ProcessClientRequest CGI1
FIGURE 2.2The interaction of a CGI solution.
Proprietary APIsMany Web servers include APIs that extend their functionality. The most common examplesinclude 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 changeservers without porting your code. These APIs are also developed using languages such as C orC++ that can contain memory leaks or core dumps that can crash the Web server.
Server-Side JavaScriptServer-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 pagesyou improve performance, but the only servers that implement server-side JavaScript areNetscape’s Enterprise, FastTrack Servers, and Microsoft’s IIS. This again ties you to a particu-lar vendor.
Microsoft’s Active Server PagesMicrosoft has developed its own solution to the problem of dynamic Web content: ActiveServer Pages (ASP). Like Server-side JavaScript, ASP is embedded into HTML pages, but it is
![Page 38: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/38.jpg)
also similar to server-side JavaScript in that it is tied to a particular Web server: Microsoft’sInternet Information Server. Some third-party products implement ASP, but you must purchasethem separately at additional costs.
Reasons to Use Java ServletsJava servlets are one of the most exciting new technologies I have had the opportunity to workwith. 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 yourselfa lot of time and headache. Servlets solve many common problems you run into when usingCGI, and they prove to have a clear advantage over many of the other alternatives. The follow-ing sections discuss some of the advantages offered by servlets.
EfficiencyA servlet’s initialization code is executed only the first time the Web server loads it. Once theservlet is loaded, it is only a matter of calling a service method to handle new requests. This isa much more efficient technique than loading a completely new executable with every request.
PersistencyServlets can maintain state between requests. Once a servlet is loaded, it stays resident inmemory while serving incoming requests. A simple example of this is a Vector that holds a listof categories used in an online catalog. When the servlet is initialized, it queries the databasefor a list of categories and stores these categories in a Vector. As it services requests, theservlet 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’sperformance drastically.
PortabilityServlets are developed using Java; therefore, they are portable. This portability enables servletsto be moved to a new operating system without changing the source. You can take code thatwas compiled on a Windows NT platform and move it to a Solaris box without making anychanges.
RobustnessBecause servlets are developed with access to the entire JDK, they are very powerful androbust solutions. Java provides a well-defined exception hierarchy for error handling. It has agarbage collector to prevent problems with memory leaks. In addition, it includes a very largeclass library that includes network support, file support, database access, distributed objectcomponents, security, and many other classes.
Servlet Overview and Architecture
CHAPTER 2
2
SER
VLET
OV
ERV
IEWA
ND
AR
CH
ITECTU
RE
19
![Page 39: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/39.jpg)
ExtensibilityAnother advantage servlets gain by being developed in an object-oriented language such asJava 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 searchtool at the top of every dynamic page throughout your Web site. You definitely don’t want toadd this code to every one of your servlets. So, you implement a base servlet that builds andinitializes the search tool and then extend it to display transaction-specific responses.
SecurityServlets run on the server side, inheriting the security provided by the Web server. Servlets canalso take advantage of the Java Security Manager.
The Java Servlet ArchitectureTwo packages make up the servlet architecture: javax.servlet and javax.servlet.http. Thejavax.servlet package contains the generic interfaces and classes that are implemented andextended by all servlets. The java.servlet.http package contains the classes that areextended when creating HTTP-specific servlets. An example of this is a simple servlet thatresponds 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 arethe init() method, which initializes a servlet; the service() method, which receives andresponds to client requests; and the destroy() method, which performs cleanup. All servletsmust 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 modelthat gives a high-level view of the servlet framework.
GenericServlet and HttpServletThe two main classes are the GenericServlet and HttpServlet classes. The HttpServletclass is extended from GenericServlet. When you are developing your own servlets, you willmost 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 aserver 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 youto follow this framework. The service() method prototype is defined as follows:
public abstract void service(ServletRequest req,ServletResponse res) throws ServletException, IOException;s
Servlet Fundamentals
PART I20
![Page 40: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/40.jpg)
FIGURE 2.3A high-level object model of the servlet framework.
The two objects that the service() method receives are ServletRequest andServletResponse. The ServletRequest object holds the information that is being sent to theservlet, whereas the ServletResponse object is where you place the data you want to sendback to the client. Figure 2.4 diagrams the flow of a GenericServlet request.
Servlet Overview and Architecture
CHAPTER 2
2
SER
VLET
OV
ERV
IEWA
ND
AR
CH
ITECTU
RE
21
<<Interface>>javax.servlet.Servlet
init()getServletConfig()service()getServletInfo()destroy()
<<Interface>>java.io.Serializable
<<Interface>>javax.servlet.ServletConfig
getInitParameter()getServletContext()getInitParameterNames()getServletName()
javax.servlet.GenericServlet
getServletContext()getInitParameter()getInitParameterNames()log()getServletInfo()init()getServletConfig()service()destroy()getServletName()
javax.servlet.http.HttpServlet
doDelete()doGet()doOptions()doPost()doPut()doTrace()getLastModified()service()
BasicServlet
![Page 41: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/41.jpg)
FIGURE 2.4A GenericServlet Request.
Unlike the GenericServlet, when you extend HttpServlet, you don’t usually implement theservice() method. The HttpServlet class has already implemented it for you. The followingis 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 therequest and determines which method to invoke based on this value. These are the methodsthat you will want to override. If the method type is GET, the service() method will calldoGet(). If the method type is POST, it will call doPost(). Five other method types exist; theyare discussed in Chapter 3, “Servlet Basics.” All these methods have the same parameter list asthe service() method.
You might have noticed the different request/response types in the parameter list of theHttpServlet and the GenericServlet classes. The HttpServletRequest andHttpServletResponse classes are just extensions of ServletRequest and ServletResponse
with HTTP-specific information stored in them. Figure 2.5 diagrams the flow of aHttpServlet request.
Servlet Fundamentals
PART I22
Web Server
ClientRequest
Response
GenericServlet
service()*
* abstract method
Web Server
ClientRequest
Response
doDelete()
doGet()
doOptions()
doPost()
doPut()
doTrace()
service()
HttpServlet
FIGURE 2.5A HttpServlet Request.
![Page 42: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/42.jpg)
SummaryIn this chapter, you learned about Java servlet basics, practical applications for servlets, servletalternatives, 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 andwhat objects are involved.
In the next chapter we will look at the life cycle of a servlet. We will also create and dissect abasic servlet.
Servlet Overview and Architecture
CHAPTER 2
2
SER
VLET
OV
ERV
IEWA
ND
AR
CH
ITECTU
RE
23
![Page 43: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/43.jpg)
![Page 44: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/44.jpg)
CHAPTER
3Servlet Basics
IN THIS CHAPTER• The Life Cycle of a Servlet 26
• A Basic Servlet 27
• Dissecting the BasicServlet 29
![Page 45: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/45.jpg)
The Life Cycle of a ServletThe life cycle of a Java servlet is a very simple object-oriented design. A servlet is constructedand initialized. It then services zero or more requests until the service that it extends shutsdown. At this point the servlet is destroyed and garbage is collected. This design explains whyservlets 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 definesthe life cycle methods. These methods are the init(), the service(), and the destroy()methods.
The init() MethodThe init() method is where the servlet’s life begins. It is called by the server immediatelyafter the servlet is instantiated. It is called only once. In the init() method the servlet createsand initializes the resources that it will be using while handling requests. The init() method’ssignature 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 objectso 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() methodshould throw a ServletException.
The service() MethodThe service() method handles all requests sent by a client. It cannot start servicing requestsuntil the init() method has been executed. You will not usually implement this methoddirectly, 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. Itsservice() method supports standard HTTP/1.1 requests by determining the request type andcalling the appropriate method. The signature of the service() method is shown below.
public void service(ServletRequest req, ServletResponse res)throws ServletException, IOException;
Servlet Fundamentals
PART I26
![Page 46: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/46.jpg)
The service() method implements a request and response paradigm. The ServletRequestobject contains information about the service request, encapsulating information provided bythe client. The ServletResponse object contains the information returned to the client.
The destroy() MethodThis method signifies the end of a servlet’s life. When a service is being shut down it calls theservlet’s destroy() method. This is where any resources that were created in the init()method should be cleaned up. If you have an open database connection, you should close ithere. This is also a good place to save any persistent information that will be used the nexttime the servlet is loaded. The signature of destroy() is very simple, but I have displayed ithere just to complete the picture:
public void destroy();
A Basic ServletIn this section, we are going to look at building a very basic servlet. Its purpose will be to ser-vice a request and respond with the request method used by the client. We will take a quicklook at the servlet’s source code, the steps involved in compiling and installing the servlet, andthe HTML necessary to invoke the servlet. After you have the servlet compiled, you will needto refer to Appendix A, “Web Applications and Configuring the Servlet Engine,” for instruc-tions on how to configure the servlet engine, which actually runs your servlets.
The BasicServlet SourceListing 3.1 contains the source code for this example. You can find the following source listingon this book’s Web site. If you have the time, it is probably best to type the first few examplesyourself. This will help you become familiar with the basic parts of servlets. As you type orbrowse over this listing, feel free to look up the referenced classes in Appendices A and B.
LISTING 3.1 BasicServlet.java Displays the REQUEST_METHOD used by the Client
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
public class BasicServlet extends HttpServlet {
public void init(ServletConfig config)throws ServletException {
Servlet Basics
CHAPTER 3
3
SER
VLET
BA
SICS
27
![Page 47: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/47.jpg)
// Always pass the ServletConfig object to the super classsuper.init(config);
}
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType(“text/html”);PrintWriter out = response.getWriter();
out.println(“<html>”);out.println(“<head><title>BasicServlet</title></head>”);out.println(“<body>”);
// Prints the REQUEST_METHOD sent by the clientout.println(“Your request method was “ + request.getMethod()+ “\n”);
out.println(“</body></html>”);out.close();
}
//Process the HTTP Post requestpublic void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType(“text/html”);PrintWriter out = response.getWriter();
out.println(“<html>”);out.println(“<head><title>BasicServlet</title></head>”);out.println(“<body>”);
// Prints the REQUEST_METHOD sent by the clientout.println(“Your request method was “ + request.getMethod()+ “\n”);
out.println(“</body></html>”);out.close();
}
Servlet Fundamentals
PART I28
LISTING 3.1 Continued
![Page 48: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/48.jpg)
//Get Servlet informationpublic String getServletInfo() {
return “BasicServlet Information”;}
}
Dissecting the BasicServletNow that you have had a chance to look over the source of the BasicServlet, let’s take acloser look at each of its integral parts. We will examine where the servlet fits into the JSDKframework, the methods that the servlet implements, and the objects being used by the servlet.
Where Does the BasicServlet Fit into the ServletFramework?The first thing we are going to look at is where the BasicServlet fits into the servlet frame-work. This servlet extends the HttpServlet class. The HttpServlet class is an abstract classthat simplifies writing HTTP servlets. It extends the GenericServlet class and provides thefunctionality for handling the HTTP protocol-specific requests. The BasicServlet overridesfour of its inherited methods. Figure 3.1 shows where the BasicServlet fits into this hierarchy.
Servlet Basics
CHAPTER 3
3
SER
VLET
BA
SICS
29
LISTING 3.1 Continued
<<Interface>>javax.servlet.Servlet
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
BasicServlet
<<Interface>>javax.servlet.ServletConfig
<<Interface>>java.io.Serializable
FIGURE 3.1The BasicServlet depicted in the Servlet Framework.
![Page 49: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/49.jpg)
The Methods Overridden by the BasicServletThe following four methods are overridden by the BasicServlet:
• init()
• doGet()
• doPost()
• getServletInfo()
Let’s take a look at each of these methods in more detail.
The init() MethodThe BasicServlet defines a very simple implementation of the init() method. It takes theServletConfig object that is passed to it and passes it to its parent’s init() method, whichstores the object for later use. The parent that actually holds on to the ServletConfig object isthe GenericServlet. The GenericServlet provides your servlet, through inheritance, withmethods to access the ServletConfig object. The code that performs this action follows:
super.init(config);
This is a very important step. If you do not do this, you must hold the ServletConfig objectyourself. We will discuss the significance of the ServletConfig object in later chapters.
You will also notice this implementation of the init() method does not create any resources.This is why the BasicServlet does not implement a destroy() method.
The doGet() and doPost() MethodsThe BasicServlet’s doGet() and doPost() methods are identical. The only difference is therequests they service. The doGet() method handles GET requests and the doPost() methodhandles POST requests.
Both of these methods receive HttpServletRequest and HttpServletResponse objects. Theseobjects encapsulate the request/response paradigm. The HttpServletRequest contains infor-mation sent from the client, and the HttpServletResponse contains information that will besent back to the client. The first executed line of these methods follows:
response.setContentType(“text/html”);
This method sets the content type for the response. You can set this response property onlyonce. You must set this property before you can begin writing to a Writer or an OutputStream.In our example, we are using a PrintWriter and setting the response type to text/html.
The next thing to do is get the PrintWriter. This is accomplished by calling theServletResponses’s getWriter() method. This is done in the following line of code:
PrintWriter out = response.getWriter();
Servlet Fundamentals
PART I30
![Page 50: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/50.jpg)
Now you have a reference to an object that will allow you to write HTML text that will be sentback to the client in the HttpServletResponse object. The next few lines of code show howthis is done:
out.println(“<html>”);out.println(“<head><title>BasicServlet</title></head>”);out.println(“<body>”);
// Prints the REMOTE_ADDR sent by the client in the requestout.println(“Your request method was “ + request.getMethod()
+ “\n”);
out.println(“</body></html>”);out.close();
This is a very straightforward method of sending HTML text back to the client. You simplypass to the PrintWriter’s println() method the HTML text you want included in theresponse and close the stream. The only thing that you might have a question about is the fol-lowing few lines:
// Prints the REMOTE_ADDR sent by the client in the requestout.println(“Your request method was “ + request.getMethod()
+ “\n”);
This code takes advantage of the information sent from the client. It calls theHttpServletRequest’s getMethod() method, which returns the HTTP method with which therequest was made. The HttpServletRequest object holds HTTP-protocol specific headerinformation.
The getServletInfo() MethodThe getServletInfo() method is like the applet’s getAppletInfo() method. It can be used toprovide version, copyright, author, and any other information about itself.
SummaryIn this chapter, we were finally able to start examining some servlet code. We looked at the lifecycle of a servlet. We also dissected a basic servlet, which gave us a view of each integral partof a servlet.
You should now be able to create your own servlets. You should also have a basic understand-ing of the servlet life cycle and where your servlets will fit into the Java servlet framework.
In the next chapter we will take a look at Web applications and how to leverage them to deployservlet applications.
Servlet Basics
CHAPTER 3
3
SER
VLET
BA
SICS
31
![Page 51: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/51.jpg)
![Page 52: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/52.jpg)
CHAPTER
4Servlets and HTML
IN THIS CHAPTER• Retrieving Form Data in a Servlet 34
![Page 53: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/53.jpg)
Retrieving Form Data in a ServletWe will now look at how servlets retrieve information from the client. Servlets most commonlyreceive data from both POST and GET requests. The methods used to retrieve this data are thesame in either case.
The three methods used to retrieve request parameters are the ServletRequest’sgetParameterNames(), getParameter(), and getParameterValues(). Their signatures are asfollows:
public Enumeration ServletRequest.getParameterNames();public String ServletRequest.getParameter(String name);public String[] ServletRequest.getParameterValues(String name);
getParameterNames() returns the parameter names for the request as an enumeration ofstrings, or an empty enumeration if there are no parameters. It is used as a supporting methodto getParameter(). When you have the enumerated list of parameter names, you can iterateover them calling getParameter() with each name in the list.
The getParameter() method returns a string containing the single value of the specified para-meter, or null if the parameter is not contained in the request. This method should be used onlyif you are sure the request contains only one value for the parameter. If the parameter has mul-tiple values you should use getParameterValues().
getParameterValues() returns the values of the specified parameter as an array of strings, ornull if the named parameter does not exist in the request.
Servicing the GET and POST RequestsLet’s take a look at a servlet that services a POST request. The servlet in Listing 4.1 retrievesthe parameters sent to it and returns the parameters and their values back to the client.
LISTING 4.1 FormServlet.java Displays All Parameter/Value Pairs in Request
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
public class FormServlet extends HttpServlet {
public void init(ServletConfig config)throws ServletException {
// Always pass the ServletConfig object to the super class
Servlet Fundamentals
PART I34
![Page 54: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/54.jpg)
super.init(config);}
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType(“text/html”);PrintWriter out = response.getWriter();out.println(“<html>”);out.println(“<head><title>FormServlet</title></head>”);out.println(“<body>”);
// Get all the parameter namesEnumeration parameters = request.getParameterNames();String param = null;
// Iterate over the names, getting the parameterswhile ( parameters.hasMoreElements() ) {
param = (String)parameters.nextElement();out.println(“<BOLD>” + param +
“ : “ + request.getParameter(param) +“</BOLD><BR>”);
}
out.println(“</body></html>”);out.close();
}
//Process the HTTP Post requestpublic void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType(“text/html”);PrintWriter out = response.getWriter();out.println(“<html>”);out.println(“<head><title>FormServlet</title></head>”);out.println(“<body>”);
// Get all the parameter namesEnumeration parameters = request.getParameterNames();
Servlets and HTML
CHAPTER 4
4
SER
VLETS
AN
DH
TML
35
LISTING 4.1 Continued
![Page 55: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/55.jpg)
String param = null;
// Iterate over the names, getting the parameterswhile ( parameters.hasMoreElements() ) {
param = (String)parameters.nextElement();out.println(“<BOLD>” + param +
“ : “ + request.getParameter(param) +“</BOLD><BR>”);
}
out.println(“</body></html>”);out.close();
}
//Get Servlet informationpublic String getServletInfo() {
return “FormServlet Information”;}
}
As you look over this servlet, you will notice that it services both GET and POST requests. Youcan invoke the FormServlet by encoding a URL string or by using a form. The HTML source,used to invoke the servlet using the POST method, is shown in Listing 4.2.
LISTING 4.2 Form.html Displays HTML Required to Invoke the Servlet Using the POSTMethod
<HTML><HEAD><TITLE>Chapter 4 Form</TITLE></HEAD><BODY>
<FORM ACTION=http://localhost/djs/servlet/FormServletMETHOD=POST>
<TABLE STYLE=”HEIGHT: 173px; WIDTH: 242px”><TR>
<TD>Last Name:</TD>
Servlet Fundamentals
PART I36
LISTING 4.1 Continued
![Page 56: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/56.jpg)
<TD><INPUT NAME=”Last Name” ALIGN=”left” SIZE=”15”></TD></TR><TR>
<TD>First Name:</TD><TD><INPUT ALIGN=left NAME=”First Name” SIZE=15> </TD>
</TR><TR>
<TD>Age:</TD><TD><INPUT ALIGN=left NAME=Age SIZE=2> </TD>
</TR><TR>
<TD>SSN:</TD><TD><INPUT ALIGN=left NAME=SSN SIZE=11> </TD>
</TR><TR>
<TD>DOB:</TD><TD><INPUT ALIGN=left NAME=DOB SIZE=8> </TD>
</TR><TR>
<TD>Username:</TD><TD><INPUT ALIGN=left NAME=Username> </TD>
</TR><TR>
<TD>Password:</TD><TD><INPUT ALIGN=left NAME=Password SIZE=8 type=password>
</TD></TR></TABLE>
<INPUT TYPE=”submit” NAME=”Submit” VALUE=”Submit”><INPUT TYPE=”reset” VALUE=Reset>
</FORM>
</BODY></HTML>
After you have examined both of these listings, build and install the servlet. The next thing youwill need to do is load the HTML document in your browser. The loaded page should looksimilar to Figure 4.1.
Servlets and HTML
CHAPTER 4
4
SER
VLETS
AN
DH
TML
37
LISTING 4.2 Continued
![Page 57: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/57.jpg)
FIGURE 4.1Form HTML Page.
You should now complete the form and click the Submit button. The response you receive,which will of course depend on your entries, should look something like that shown inFigure 4.2.
How the FormServlet WorksNow that you have seen what the FormServlet does, let’s take a look at how it does it. Thearea we want to focus on is listed here:
// Get all the parameter namesEnumeration parameters = request.getParameterNames();String param = null;
// Iterate over the names, getting the parameterswhile ( parameters.hasMoreElements() ) {
param = (String)parameters.nextElement();out.println(“<BOLD>” + param +“ : “ + request.getParameter(param) +“</BOLD><BR>”);
}
Servlet Fundamentals
PART I38
![Page 58: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/58.jpg)
FIGURE 4.2FormServlet Response Page.
The code is the same for both the doPost() and doGet() methods. The first executed line callsthe getParameterNames() method for the current request. This method returns an enumeratedlist of parameter names. We then iterate over the Enumerator calling getParameter() andpassing it each one of the parameter names; it returns the value of each request parameter.These tag/value pairs are then passed to the response writer with some HTML formatting tags.The completed response is then passed back to the client and displayed in the browser.
This example shows just how easy it is to retrieve request parameters in a servlet. Although theFormServlet works fine for most requests, it does have a flaw. When we chose to usegetParameter() to retrieve our parameter values, we knew there would only be one value perrequest parameter. If you need to handle multiple values, you should use thegetParameterValues() method discussed previously.
SummaryIn this chapter we covered a lot of information. We looked at how servlets parse request para-meters. We also created an HTML package that encapsulates basic HTML. At this point youshould feel comfortable with how servlets receive information from the client.
Servlets and HTML
CHAPTER 4
4
SER
VLETS
AN
DH
TML
39
![Page 59: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/59.jpg)
In the next chapter we will look at the servlet architecture’s provisions for maintaining state,namely the HttpSession.
Servlet Fundamentals
PART I40
![Page 60: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/60.jpg)
CHAPTER
5Servlet Sessions
IN THIS CHAPTER• What Is Session Tracking? 42
• Using Hidden Form Fields 42
• Working with Cookies 46
• URL Rewriting 50
• Session Tracking with the Servlet API 51
![Page 61: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/61.jpg)
What Is Session Tracking?Session tracking is the capability of a server to maintain the current state of a single client’ssequential requests. The HTTP protocol used by Web servers is stateless. This means thatevery transaction is autonomous. This type of stateless transaction is not a problem unless youneed to know the sequence of actions a client has performed while at your site.
For example, an online video store must be able to determine each visitor’s sequence ofactions. Suppose a customer goes to your site to order a movie. The first thing he does is lookat the available titles. When he has found the title he is interested in, he makes his selection.The problem now is determining who made the selection. Because each one of the client’srequests is independent of the previous requests, you have no idea who actually made the finalselection.
Servlet Fundamentals
PART I42
You could use HTTP authentication as a method of session tracking, but each of yourcustomers would need an account on your site. This is fine for some businesses, butwould be a hassle for a high-volume site. You probably could not get every user whosimply wants to browse through the available videos to open an account.
NOTE
In this chapter, you will look at several different ways to determine the actions that a particularclient has taken. You will examine hidden form fields, cookies, URL rewriting, and the built-insession tracking functionality found in the servlet API.
Using Hidden Form FieldsUsing hidden form fields is one of the simplest session tracking techniques. Hidden form fieldsare HTML input types that are not displayed when read by a browser. The following sampleHTML listing includes hidden form fields:
<HTML><BODY>
<FORM ACTION=”someaction” METHOD=”post”>
<INPUT TYPE=”hidden” NAME=”tag1” VALUE=”value1”><INPUT TYPE=”hidden” NAME=”tag2” VALUE=”value2”>
<INPUT TYPE=”submit”>
![Page 62: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/62.jpg)
</FORM>
</BODY></HTML>
When you open this HTML document in a browser, the input types marked as hidden will notbe visible. They will, however, be transmitted in the request.
Let’s create a simple example that shows how this technique works. You’ll create a servlet thatcan service both POST and GET methods. In the doGet() method, you’ll build a form that con-tains hidden fields and an action that points to the servlet’s doPost() method. The doPost()method will then parse the hidden values sent in the request and echo them back to the client.The example is found in Listing 5.1.
LISTING 5.1 HiddenFieldServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
public class HiddenFieldServlet extends HttpServlet {
public void init(ServletConfig config)throws ServletException {
super.init(config);}
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType(“text/html”);PrintWriter out = response.getWriter();out.println(“<html>”);out.println(“<head><title>HiddenFieldServlet” +“</title></head>”);
out.println(“<body>”);
// Create the Form with Hidden Fieldsout.println(“<FORM ACTION=” +“\”/djs/servlet/HiddenFieldServlet\” METHOD=\”POST\”>”);
Servlet Sessions
CHAPTER 5
5
SER
VLET
SESSIO
NS
43
![Page 63: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/63.jpg)
// These values would be uniquely generatedout.println(“<INPUT TYPE=\”hidden\” NAME=” +“\”user\” VALUE=\”James\”>”);
out.println(“<INPUT TYPE=\”hidden\” NAME=” +“\”session\” VALUE=\”12892\”>”);
// These are the currently selected moviesout.println(“<INPUT TYPE=\”hidden\” NAME=” +“\”movie\” VALUE=\”Happy Gilmore\”>”);
out.println(“<INPUT TYPE=\”hidden\” NAME=” +“\”movie\” VALUE=\”So I Married an Axe Murderer\”>”);
out.println(“<INPUT TYPE=\”hidden\” NAME=” +“\”movie\” VALUE=\”Jaws\”>”);
out.println(“<INPUT TYPE=\”submit\” VALUE=” +“\”Submit\”>”);
out.println(“</FORM>”);
out.println(“</body></html>”);out.close();
}
//Process the HTTP Post requestpublic void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType(“text/html”);PrintWriter out = response.getWriter();out.println(“<html>”);out.println(“<head><title>HiddenFieldServlet” +“</title></head>”);
out.println(“<body>”);
// Get the hidden inputs and echo themString user = request.getParameter(“user”);String session = request.getParameter(“session”);
out.println(“<H3>” + user +“, the contents of your Shopping Basket are:</H3><BR>”);
Servlet Fundamentals
PART I44
LISTING 5.1 Continued
![Page 64: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/64.jpg)
String[] movies = request.getParameterValues(“movie”);
if ( movies != null ) {
for ( int x = 0; x < movies.length; x++ ) {
out.println(movies[x] + “<BR>”);}
}
out.println(“</body></html>”);out.close();
}
//Get Servlet informationpublic String getServletInfo() {
return “HiddenFieldServlet Information”;}
}
When you have this servlet installed, open your browser to the servlet’s URL. The URL on mylocal box is listed as follows:
http://localhost/djs/servlet/HiddenFieldServlet
When the servlet is loaded, you should only see a Submit button. If you view the currentHTML source, you will see a listing similar to this snippet:
<html><head><title>HiddenFieldServlet</title></head><body><FORM ACTION=”/djs/servlet/HiddenFieldServlet” METHOD=”POST”><INPUT TYPE=”hidden” NAME=”user” VALUE=”James”><INPUT TYPE=”hidden” NAME=”session” VALUE=”12892”><INPUT TYPE=”hidden” NAME=”movie” VALUE=”Happy Gilmore”><INPUT TYPE=”hidden” NAME=”movie” VALUE=”So I Married an Axe Murderer”><INPUT TYPE=”hidden” NAME=”movie” VALUE=”Jaws”><INPUT TYPE=”submit” VALUE=”Submit”></FORM></body></html>
Notice the hidden fields. Now click the Submit button. The form invokes the doPost() method ofthe HiddenFieldServlet. This method parses the hidden fields out of the request and displaysthem in a “shopping cart” listing. Figure 5.1 shows the results of the HiddenFieldServlet’sdoPost() method.
Servlet Sessions
CHAPTER 5
5
SER
VLET
SESSIO
NS
45
LISTING 5.1 Continued
![Page 65: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/65.jpg)
FIGURE 5.1Output of HiddenFieldServlet.
You can see that hidden form fields have their advantages. They are easy to implement and aresupported by most browsers. This technique also has its disadvantages. The hidden fields mustbe created in a particular sequence. You are not able to click the Back button on your browserwithout losing the additional fields added to the current page. You are also restricted to dynam-ically generated documents.
Working with CookiesOne of the more elegant solutions to session tracking is the use of persistent cookies. Netscapefirst introduced cookies in one of the company’s first versions of Netscape Navigator.
A cookie is a keyed piece of data that is created by the server and stored by the client browser.Browsers maintain their own list of unique cookies. This makes cookies a very viable solutionfor session tracking.
The Servlet API provides built-in support for cookies. It does this through the use of theCookie class and the HttpServletResponse.addCookie() andHttpServletRequest.getCookies() methods.
Servlet Fundamentals
PART I46
![Page 66: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/66.jpg)
The Cookie class encapsulates persistent cookies as defined by RFC 2109. The prototype forthe Cookie’s constructor takes a String representing the unique name of the cookie and aString representing the value of the cookie, and it is listed as follows:
public Cookie(String name, String value)
The Cookie class also provides accessors used to get and set the values of the cookie. Listing5.2 contains an example of using cookies to perform session handling.
LISTING 5.2 CookieServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
public class CookieServlet extends HttpServlet {//Initialize global variables
public void init(ServletConfig config)throws ServletException {
super.init(config);}
private String getCurrentUser(String value) {
String userName = new String(“”);
// This would normally be a Select from a database or// other storage area.if ( value.equals(“564XX892”) ) {
userName = new String(“Bob”);}return userName;
}
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
// Get the list of Cookies stored in the requestCookie[] cookieList = request.getCookies();String user = null;
Servlet Sessions
CHAPTER 5
5
SER
VLET
SESSIO
NS
47
![Page 67: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/67.jpg)
String responseString = null;
if ( cookieList != null ) {
// Cookies found, let’s get the session idfor ( int x = 0; x < cookieList.length; x++ ) {
String name = cookieList[x].getName();
if ( name.equals(“session_id”) ) {
// Get the user based on the session iduser = getCurrentUser(cookieList[x].getValue());break;
}}
}
if ( user == null ) {
// Let’s create a cookie that represents a unique// session id.response.addCookie(new Cookie(“session_id”, “564XX892”));responseString = new String(“Welcome to our site, “ +“we have created a session for you.”);
}else {
responseString = new String(“Hello : “ + user);}
response.setContentType(“text/html”);PrintWriter out = response.getWriter();
out.println(“<html>”);out.println(“<head><title>CookieServlet</title></head>”);
out.println(“<body>”);
out.println(responseString);
out.println(“</body></html>”);out.close();
}
Servlet Fundamentals
PART I48
LISTING 5.2 Continued
![Page 68: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/68.jpg)
//Get Servlet informationpublic String getServletInfo() {
return “CookieServlet Information”;}
}
Every time the CookieServlet services a request, it checks for cookies in theHttpServletRequest. It does this by calling the HttpServletRequest.getCookies() method.If the request does contain cookies, the servlet will iterate over the list of cookies looking for acookie with the name session_id.
If the request contains no cookies or the list of cookies does not contain a cookie named session_id, you create one and add it to the response. The code snippet that does this is listedas follows:
response.addCookie(new Cookie(“session_id”, “564XX892”));
Servlet Sessions
CHAPTER 5
5
SER
VLET
SESSIO
NS
49
LISTING 5.2 Continued
Cookies are stored in the response as HTTP headers. Therefore, you must add cookiesto the response before adding any other content.
NOTE
The best way to test this functionality is to open your browser to the CookieServlet. The firsttime it runs, you should get a response that says “Welcome to our site, we have created a ses-sion for you.” After you get this message, click the Refresh button. You should see a newresponse that says “Hello : Bob.” The servlet can now identify the user “Bob” by the sessionID stored as a cookie.
If you have trouble running this example, make sure the use of cookies is enabled inyour browser.
NOTE
![Page 69: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/69.jpg)
URL RewritingIf your browser does not support cookies, URL rewriting provides you with another sessiontracking alternative. URL rewriting is a method in which the requested URL is modified toinclude a session ID. There are several ways to perform URL rewriting. You are going to lookat one method that is provided by the Servlet API. Listing 5.3 shows an example of URLrewriting.
LISTING 5.3 URLRewritingServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
public class URLRewritingServlet extends HttpServlet {//Initialize global variables
public void init(ServletConfig config)throws ServletException {
super.init(config);}
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType(“text/html”);PrintWriter out = response.getWriter();out.println(“<html>”);out.println(“<head><title>URL Rewriting</title></head>”);out.println(“<body>”);
// Encode a URL string with the session id appended// to it.String url = response.encodeRedirectURL(“http://localhost:8000/servlet/checkout?sid=5748”);
// Redirect the client to the new URLresponse.sendRedirect(url);
out.println(“</body></html>”);out.close();
Servlet Fundamentals
PART I50
![Page 70: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/70.jpg)
}
//Get Servlet informationpublic String getServletInfo() {
return “URLRewritingServlet Information”;}
}
This servlet services a GET request and redirects the client to a new URL. This new URL hasthe string sid=5748 appended to it. This string represents a session ID. When the servlet thatservices the redirection receives the request, it will be able to determine the current user basedon the appended value. At that point, the servlet can perform a database lookup on the user andher actions based on this ID.
Two methods are involved in this redirection. The first isHttpServletResponse.encodeRedirectURL(), which takes a String that represents a redirec-tion URL and encodes it for use in the second method. The second method used is theHttpServletRequest.sendRedirect() method. It takes the String returned from theencodeRedirectString() and sends it back to the client for redirection.
The advantage of URL rewriting over hidden form fields is the capability to include sessiontracking information without the use of forms. Even with this advantage, it is still a very ardu-ous coding process.
Session Tracking with the Servlet APIThe Servlet API has its own built-in support for session tracking. The HttpSession object pro-vides this functionality. In this section, I focus on four of the HttpSession’s session trackingmethods.
The first method is the setAttribute() method. The setAttribute() method binds aname/value pair to store in the current session. If the name already exists in the session, it isreplaced. The method signature for setAttribute() is listed as follows:
public void setAttribute(String name, Object value)
The next method is the getAttribute() method, which is used to get an object that is storedin the session. The getAttribute() method takes a string representing the name that thedesired object is bound to. Its signature is listed as follows:
public Object getAttribute(String name)
Servlet Sessions
CHAPTER 5
5
SER
VLET
SESSIO
NS
51
LISTING 5.3 Continued
![Page 71: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/71.jpg)
The third session method returns an array of the current bound names stored in the session.This method is convenient if you want to remove all the current bindings in a session. Its sig-nature is listed as follows:
public String[] getAttributeNames()
The last session method is the removeAttribute() method. As its name suggests, it removes abinding from the current session. It takes a string parameter representing the name associatedwith the binding. Its method signature is listed as follows:
public void removeAttribute(String name)
Now that I have discussed the HttpSession object, let’s take a look at an example of how touse it. In this example, you will service a request that contains a list of movies to add to auser’s account. You will then parse the submitted list, add it to the customer’s session, andredisplay it for approval. When the customer approves the list, they will click the Proceed toCheckout button to commit the transaction. Listing 5.4 contains the source for this example.
LISTING 5.4 HttpSessionServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
public class HttpSessionServlet extends HttpServlet {
public void init(ServletConfig config)throws ServletException {
super.init(config);}
//Process the HTTP Get request, this method// will handle the checkoutpublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
String[] movies = null;
// Get a handle to the HttpSession Object// if there is no session create oneHttpSession session = request.getSession(true);
// Get the movies list object bound to the
Servlet Fundamentals
PART I52
![Page 72: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/72.jpg)
// name “Movies”if ( session != null ) {
movies = (String[])session.getAttribute(“Movies”);}
response.setContentType(“text/html”);PrintWriter out = response.getWriter();out.println(“<html>”);out.println(“<head><title>Session Servlet</title></head>”);out.println(“<body>”);
// Iterate over the movies array, displaying the// current list of movies stored in the sessionout.println(“<H2>Thank you for purchasing:</H2>”);for ( int x = 0; x < movies.length; x++ ) {
out.println(movies[x] + “<BR>”);}out.println(“</body></html>”);out.close();
}
//Process the HTTP Post requestpublic void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
// Parse the movies selectedString movies[] = request.getParameterValues(“Movies”);
// Get a handle to the HttpSession Object// if there is no session create oneHttpSession session = request.getSession(true);
// add the list of movies to the session// binding it to the String “Movies”if ( session != null ) {
session.setAttribute(“Movies”, movies);}
response.setContentType(“text/html”);PrintWriter out = response.getWriter();
Servlet Sessions
CHAPTER 5
5
SER
VLET
SESSIO
NS
53
LISTING 5.4 Continued
![Page 73: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/73.jpg)
out.println(“<html>”);out.println(“<head><title>Session Servlet</title></head>”);out.println(“<body>”);
out.println(“<H2>Contents of Shopping Cart</H2>”);
// Display the submitted movie arrayfor ( int x = 0; x < movies.length; x++ ) {
out.println(movies[x] + “<BR>”);}// Create a form to submit an orderout.println(“<FORM action=/djs/servlet/HttpSessionServlet “ +“METHOD=GET>”);
out.println(“<input type=\”Submit\” name=\”add\” value=” +“\”Proceed to Checkout\”></FORM>”);
out.println(“</body></html>”);out.close();
}
//Get Servlet informationpublic String getServletInfo() {
return “HttpSessionServlet Information”;}
}
To invoke this servlet, you need to create an HTML file that will make a POST request contain-ing a list of selected movies. The HTML file that contains this form is in Listing 5.5.
LISTING 5.5 HtmlSessionServlet.html
<HTML><HEAD><TITLE>Movie List</TITLE></HEAD>
<BODY><H2>Select From Available Movies</h2>
<FORM ACTION=http://localhost/djs/servlet/HttpSessionServlet method=POST>
Servlet Fundamentals
PART I54
LISTING 5.4 Continued
![Page 74: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/74.jpg)
LISTING 5.5 Continued
Servlet Sessions
CHAPTER 5
5
SER
VLET
SESSIO
NS
55
<SELECT NAME=”Movies” SIZE=”5” MULTIPLE><OPTION SELECTED>Air Force One</OPTION><OPTION>Happy Gilmore</OPTION><OPTION>So I Married an Axe Murderer</OPTION><OPTION>Austin Powers</OPTION><OPTION>Pure Luck</OPTION>
</SELECT><BR><INPUT TYPE=”Submit” NAME=”add” VALUE=”Add Movies”>
</FORM>
</BODY></HTML>
To see how this example works, load this HTML page in a browser. You should see a screensimilar to Figure 5.2.
FIGURE 5.2The Movie Selection List screen.
When this page is loaded, select a couple of the movies in the list and click the Add Moviesbutton. You should now see a screen containing the list of movies you selected. Figure 5.3 dis-plays an example of this output.
![Page 75: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/75.jpg)
FIGURE 5.3The Contents of Shopping Cart screen.
To understand how this first part works, you need to examine the doPost() method. This is themethod that services the POST request sent by your HTML document.
The first thing the doPost() method does is get the list of submitted movies from the request.It then tries to get a reference to the HttpSession object stored in the HttpServletRequest.This is done by calling the HttpServletRequest.getSession() method. The code snippet thatperforms this is listed in the following:
// Get a handle to the HttpSession Object// if there is no session create oneHttpSession session = request.getSession(true);
The getSession() method takes one parameter. This parameter is a Boolean value that, iftrue, tells the method to create an HttpSession if one doesn’t exist.
When you have a reference to the HttpSession object, you can add your movie list to it. Youdo this by calling the HttpSession.setAttribute() method, passing it the name “Movies”and the object to be bound to it: movies. The movie list is now stored in the client’s session.The last thing you do in the doPost() method is redisplay the list of selected movies and askthe user to click Proceed to Checkout.
Servlet Fundamentals
PART I56
![Page 76: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/76.jpg)
Now you are going to look at the really cool part. Click the Proceed to Checkout button. Youshould see a screen similar to Figure 5.4, which tells you “Thank you for purchasing:” and dis-plays the movies you selected.
Servlet Sessions
CHAPTER 5
5
SER
VLET
SESSIO
NS
57
Sessions do expire. Therefore, you will need to consult your server’s documentation todetermine the length of time a session is valid.
NOTE
FIGURE 5.4The Thank You screen.
The request performed by this form simply calls the same servlet using the GET method. If youlook at the URL your browser now points to, you will notice there is no movie data encoded inthe URL string.
Look at the doGet() method to see exactly how this is done. The first thing you do is get a ref-erence to the HttpSession object, which is done exactly as before with the getSession()method. When you have a reference to the session, you can get the list of movies stored in thesession. You do this by calling the HttpSession.getAttribute() method, passing it the namebound to the movies object. The following code snippet shows how this is done:
![Page 77: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/77.jpg)
// Get the movies list object bound to the// name “Movies”if ( session != null ) {
movies = (String[])session.getAttribute(“Movies”);}
Servlet Fundamentals
PART I58
Make sure that you downcast your stored object back to its original type. While inthe HttpSession, it is stored as an object.
NOTE
When you have the list of movies, thank the customer for the purchase and redisplay the list ofordered movies. That is all there is to it. As you have seen, the Servlet API provides you with avery elegant and simple-to-use method of maintaining persistent sessions.
SummaryIn this chapter, we covered several methods that you can integrate into your servlets to handlepersistent sessions. We talked about the hidden form fields, persistent cookies, URL rewriting,and the Servlet API’s built-in session handling support. At this point, you should be able toexamine your session handling requirements and determine which method satisfies your needs.You should also be able to implement a session handling solution based on your decision.
In the next chapter, we will look at communication between Java applets and servlets using amethod call HTTP tunneling.
![Page 78: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/78.jpg)
CHAPTER
6HTTP Tunneling
IN THIS CHAPTER• 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
• Pros and Cons of Applet-to-ServletCommunication 83
![Page 79: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/79.jpg)
What Is HTTP Tunneling?HTTP tunneling is a method of reading and writing serialized objects using an HTTP connec-tion. You are creating a sub-protocol inside the HTTP protocol—that is, “tunneling” insideanother protocol. This relieves you from the hassles of dealing with the actual transport layer.
Object SerializationBefore you can get started with HTTP tunneling, you need to understand object serialization.Object serialization is a feature introduced in the Java Development Kit version 1.1. It enablesyou to create objects that are persistent across several media. An exceptionally convenientcharacteristic of serialization is that it not only serializes your object, it also unwinds and seri-alizes all the objects that are referenced by your object.
To make an object serializable, it must implement the Serializable interface. This interface isfound in the java.io package. The entire Serializable interface is listed as follows:
public interface Serializable {static final long serialVersionUID = 1196656838076753133L;
}
As you can see, there is not much to this interface. Its only purpose is to signify that an objectcan be serialized.
The steps involved in serializing an object are as follows:
1. Create an OutputStream object. This can be a stream to a file, a TCP/IP connection, ormost any other target.
2. Create an ObjectOutputStream and pass to its constructor the OutputStream created inStep 1.
3. Call the ObjectOutputStream’s writeObject() method and pass to it the object thatimplements the Serializable interface.
The equivalent steps involved in reading a serialized object are as follows:
1. Create an InputStream object that points to the location of the serialized object.
2. Create an ObjectInputStream and pass to its constructor the InputStream created inStep 1.
3. Call the ObjectInputStream’s readObject() method.
4. The readObject() method returns an upcasted Object that must be downcasted back toyour original object’s type.
Servlet Fundamentals
PART I60
![Page 80: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/80.jpg)
Now, you’ll create a simple example that writes an object to a file and reads the same objectback in. The created object will contain a vector of other objects. Listing 6.1 contains theobject you will be serializing.
LISTING 6.1 StudentList.java
import java.io.*;import java.util.*;
public class StudentList implements Serializable {
// Vector holding our studentsVector list = new Vector(6);
// Default Constructorpublic StudentList() {}
public void addStudent(String value) {
// Add a String representing a student nameif ( value != null ) {
list.addElement(value);}
}
public void listStudents() {
// Iterate over list vector, printint all Stringsfor ( int x = 0; x < list.size(); x++ ) {
System.out.println(“Student “ + x + “ : “+ (String)list.elementAt(x));
}}
}
Notice that the StudentList object implements the java.io.Serializable interface. It alsocontains a vector of strings representing student names, which are also defined asSerializable.
The StudentListApplication will be used to create, store, and retrieve the StudentList frompersistent storage. In this example, the persistent storage is the file file.dat. TheStudentListApplication is found in Listing 6.2.
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G61
![Page 81: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/81.jpg)
LISTING 6.2 StudentListApplication.java
import java.io.*;
public class StudentListApplication {
// Default Constructorpublic StudentListApplication() {
}
// Adds Student Names to Listpublic void buildStudentList(StudentList value) {
value.addStudent(“Bob Robinson”);value.addStudent(“Steve Bobinson”);value.addStudent(“Rob Stevinson”);value.addStudent(“Todd Thompson”);value.addStudent(“Tom Toddson”);value.addStudent(“Rob Bobinson”);
}
// Stores the Serializable StudentList to the file “file.dat”public void putStudentList(StudentList value) {
try {
// Create the ObjectOutputStream passing it the// FileOutputStream object that points to our// persistent storage.ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(“file.dat”));
// Write the StudentList to the ObjectOutputStreamos.writeObject(value);os.flush();os.close();
}catch (IOException e) {
System.err.println(e.getMessage());}
}
public StudentList getStudentList() {
StudentList list = null;
Servlet Fundamentals
PART I62
![Page 82: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/82.jpg)
try {
// Create the ObjectInputStream passing it the// FileInputStream object that points to our// persistent storage.ObjectInputStream is = new ObjectInputStream(new FileInputStream(“file.dat”));
// Read the stored object and downcast it back to// a StudentListlist = (StudentList)is.readObject();is.close();
}catch (IOException e) {
System.err.println(e.getMessage());}catch (ClassNotFoundException ce) {
System.err.println(ce.getMessage());}return list;
}
public void invoke() {
StudentList list = new StudentList();
buildStudentList(list);
System.out.println(“Before being serialized.”);list.listStudents();putStudentList(list);
System.out.println(“After being read back in.”);// Get the StudentList and print it outStudentList inList = getStudentList();if ( inList != null ) {
inList.listStudents();}else {
System.err.println(“readObject failed.”);}
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G63
LISTING 6.2 Continued
![Page 83: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/83.jpg)
try {
System.out.println(“\n Press enter to quit.”);System.in.read();
}catch (Exception e) {
System.err.println(e.getMessage());}
}
public static void main(String[] args) {
StudentListApplication studentListApplication =new StudentListApplication();
studentListApplication.invoke();}
}
You need to look at two sections of the StudentListApplication. The first is theputStudentList() method in which the StudentList object is written to the file file.dat.This method is listed as follows:
// Stores the Serializable StudentList to the file “file.dat”public void putStudentList(StudentList value) {
try {// Create the ObjectOutputStream passing it the
// FileOutputStream object that points to our// persistent storage.ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(“file.dat”));
// Write the StudentList to the ObjectOutputStreamos.writeObject(value);os.flush();os.close();
}catch (IOException e) {
System.err.println(e.getMessage());}
}
Servlet Fundamentals
PART I64
LISTING 6.2 Continued
![Page 84: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/84.jpg)
This method follows the exact three-step process discussed earlier. It creates the appropriatestreams for writing and writes the object to persistent storage.
The second section to study is the getStudentList() method. It does the exact opposite of theputStudentList() method. One important step in this method that is not part of its counter-part is the downcast from an object to a StudentList. You must do this because when theStudentList object was stored, it was upcast to an Object. The getStudentList() method islisted as follows:
public StudentList getStudentList() {
StudentList list = null;
try {
// Create the ObjectInputStream passing it the// FileInputStream object that points to our// persistent storage.ObjectInputStream is = new ObjectInputStream(new FileInputStream(“file.dat”));
// Read the stored object and downcast it back to// a StudentListlist = (StudentList)is.readObject();is.close();
}catch (IOException e) {
System.err.println(e.getMessage());}catch (ClassNotFoundException ce) {
System.err.println(ce.getMessage());}return list;
}
Build and run the application. The output should look like the following:
Before being serialized.Student 0 : Bob RobinsonStudent 1 : Steve BobinsonStudent 2 : Rob StevinsonStudent 3 : Todd ThompsonStudent 4 : Tom ToddsonStudent 5 : Rob BobinsonAfter being read back in.
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G65
![Page 85: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/85.jpg)
Student 0 : Bob RobinsonStudent 1 : Steve BobinsonStudent 2 : Rob StevinsonStudent 3 : Todd ThompsonStudent 4 : Tom ToddsonStudent 5 : Rob Bobinson
Press enter to quit.
Notice that the objects are exactly the same before and after being serialized.
Creating an HTTP Tunneling ClientNow that you understand Java serialization, let’s put together an example using HTTP tunnel-ing. The first part of this example is the client. This will be a simple application that opens anHTTP connection to your servlet. It will then write the same StudentList object used in theprevious example to the open connection and wait for a response. The response will be theoriginal StudentList object echoed back to the client. The client can be found in Listing 6.3.
LISTING 6.3 StudentListTunnelApp.java
import java.io.*;import java.net.*;
public class StudentListTunnelApp {
public StudentListTunnelApp() {
}
// Adds Student Names to Listpublic void buildStudentList(StudentList value) {
value.addStudent(“Bob Robinson”);value.addStudent(“Steve Bobinson”);value.addStudent(“Rob Stevinson”);value.addStudent(“Todd Thompson”);value.addStudent(“Tom Toddson”);value.addStudent(“Rob Bobinson”);
}
// Write the StudentList to the Connectionpublic void writeStudentList(URLConnection connection,StudentList value) {
Servlet Fundamentals
PART I66
![Page 86: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/86.jpg)
try {
// Set this to false in order to ignore cachingconnection.setUseCaches(false);
// Set the content-type of the request// application/octet-stream is used when writing// application specific byte size dataconnection.setRequestProperty(“CONTENT_TYPE”,“application/octet-stream”);
// Set these vales to true to use the same connection// for both input and outputconnection.setDoInput(true);connection.setDoOutput(true);
// Create the ObjectOutputStream passing it the// OutputStream object.ObjectOutputStream os =new ObjectOutputStream(connection.getOutputStream());
// Write the StudentList to the ObjectOutputStreamSystem.err.println(“Writing StudentList Object.”);os.writeObject(value);os.flush();os.close();
}catch (IOException e) {
System.err.println(e.getMessage());}
}
public StudentList readStudentList(URLConnection connection){
StudentList list = null;
try {
// Create the ObjectInputStream passing it the// InputStream object from the URLConnectionObjectInputStream is = new ObjectInputStream(connection.getInputStream());
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G67
LISTING 6.3 Continued
![Page 87: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/87.jpg)
System.err.println(“Waiting for response.”);
// Read the stored object and downcast it back to// a StudentListlist = (StudentList)is.readObject();is.close();
}catch (IOException e) {
System.err.println(e.getMessage());}catch (ClassNotFoundException ce) {
System.err.println(ce.getMessage());}return list;
}
public void invoke() {
try {
StudentList list = new StudentList();
buildStudentList(list);
// create our URLURL url = new URL(“http://localhost/djs” +“/servlet/StudentListTunnelServlet”);
// Open our URLConnectionSystem.err.println(“Opening Connection.”);URLConnection con = url.openConnection();
// Write the StudentListwriteStudentList(con, list);
// Get the StudentList from the response// and print it out.StudentList inList = readStudentList(con);if ( inList != null ) {
System.out.println(“After being read back in.”);inList.listStudents();
Servlet Fundamentals
PART I68
LISTING 6.3 Continued
![Page 88: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/88.jpg)
}else {
System.err.println(“readObject failed.”);}
System.out.println(“\n Press enter to quit.”);System.in.read();
}catch (MalformedURLException mue) {
System.err.println(mue.getMessage());}catch (Exception e) {
System.err.println(e.getMessage());}
}
public static void main(String[] args) {
StudentListTunnelApp studentListTunnelApp =new StudentListTunnelApp();
studentListTunnelApp.invoke();}
}
Take a look at exactly how the client works. You need to focus on several areas of this exam-ple. The first is creating the URL and opening the URLConnection. This section is listed as fol-lows:
// create our URLURL url = new URL(“http://localhost/djs” +“/servlet/StudentListTunnelServlet”);
// Open our URLConnectionSystem.err.println(“Opening Connection.”);URLConnection con = url.openConnection();
This is a very simple procedure. It first instantiates a URL object with a string pointing to theservlet URL. It then calls the URL.openConnection() method, which returns a URLConnectionobject. This is the object you will be using as your communications medium. It will be passedto the writeStudentList() and readStudentList() methods. These methods are your nextareas of focus.
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G69
LISTING 6.3 Continued
![Page 89: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/89.jpg)
The writeStudentList() method takes a URLConnection object and a StudentList object asparameters. This method first sets the appropriate URLConnection properties. This code islisted as follows:
// Set this to false in order to ignore cachingconnection.setUseCaches(false);
// Set the content-type of the request// application/octet-stream is used when writing// application specific byte size dataconnection.setRequestProperty(“CONTENT_TYPE”,“application/octet-stream”);
// Set these vales to true to use the same connection// for both input and outputconnection.setDoInput(true);connection.setDoOutput(true);
These property settings are very important. The first executable line turns off caching for thisrequest. The second is one of the more important property settings. It specifies that you will beusing application-specific, byte-size data as your content type because you will be sending abinary data stream. The last two lines in this section set the doInput and doOutput connectionproperties to True. This makes it possible to both send and receive using the same connection.
The last section of the writeStudentList() method you will look at follows the same threesteps discussed in the section “Object Serialization.” It gets an OutputStream object from theURLConnection.getOutputStream() method. This OutputStream object is then passed to theconstructor of the ObjectOutputStream, which is used to write the object to the HTTP connec-tion. This code is listed as follows:
// Create the ObjectOutputStream passing it the// OutputStream object.ObjectOutputStream os =new ObjectOutputStream(connection.getOutputStream());
// Write the StudentList to the ObjectOutputStreamSystem.err.println(“Writing StudentList Object.”);os.writeObject(value);os.flush();os.close();
The readStudentList() method is even more simple than its counterpart. It simply followsthe object serialization steps for reading an object. It gets an InputStream object from theURLConnection and passes it to the constructor of the ObjectInputStream, which is then usedto read the StudentList object. For your convenience, it is listed in its entirety:
Servlet Fundamentals
PART I70
![Page 90: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/90.jpg)
public StudentList readStudentList(URLConnection connection){
StudentList list = null;
try {
// Create the ObjectInputStream passing it the// InputStream object from the URLConnectionObjectInputStream is = new ObjectInputStream(connection.getInputStream());
System.err.println(“Waiting for response.”);
// Read the stored object and downcast it back to// a StudentListlist = (StudentList)is.readObject();is.close();
}catch (IOException e) {
System.err.println(e.getMessage());}catch (ClassNotFoundException ce) {
System.err.println(ce.getMessage());}return list;
}
When you see how easy it is to serialize objects across an HTTP connection, or any other con-nection, you really have to give credit to the people who wrote these classes. They have savedall of us a lot of hassle. You will see again how easy it is in the next section, when you look atthe servlet side of an HTTP tunnel.
Creating an HTTP Tunneling ServletNow that you have seen the client side, let’s take a look at the server side. The servlet examplewill service requests from the StudentListTunnelApp. When it receives a request, it will readthe StudentList object from the InputStream and send it, unchanged, back to the client. Thesource for the servlet is in Listing 6.4.
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G71
![Page 91: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/91.jpg)
LISTING 6.4 StudentListTunnelServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
import StudentList;
public class StudentListTunnelServlet extends HttpServlet {
public void init(ServletConfig config)throws ServletException {
super.init(config);}
//Service the requestpublic void service(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
try {
// Create the ObjectInputStream with// the Request InputStream.ObjectInputStream ois =new ObjectInputStream(request.getInputStream());
// Read the Object. Make sure the StudentList Object// is in your CLASSPATH or you will receive a// ClassNotFoundException.StudentList list = (StudentList)ois.readObject();
// The Response Begins Hereresponse.setContentType(“application/octet-stream”);
ObjectOutputStream oos =new ObjectOutputStream(response.getOutputStream());
// Echo the object to the responseoos.writeObject(list);oos.flush();oos.close();
}catch (ClassNotFoundException cnfe) {
Servlet Fundamentals
PART I72
![Page 92: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/92.jpg)
System.err.println(cnfe.getMessage());}
}
//Get Servlet informationpublic String getServletInfo() {
return “StudentListTunnelServlet Information”;}
}
As you can see, this is a very simple servlet. The service() method is where all the function-ality is located. The StudentList objects are written and read just as they were on the clientside. The same three-step process is used on both sides.
A Practical HTTP Tunneling ExampleYou will now put HTTP tunneling to work in a practical example. Your example will be a real-time order status tool. You will use an applet as your client side, which will be calledOrderStatusApplet. It will send a serializable order object to the OrderStatusServlet. Thisservlet will then read the object off the wire, update the status attribute, and send the objectback to the applet. Listing 6.5 contains the source code for the Order object.
LISTING 6.5 Order.java
import java.io.*;
// Notice this object implements the Serializable interfacepublic class Order implements Serializable {
// This attribute holds the Order#private String order = new String(“”);// This attribute holds the Status of the Orderprivate String status = new String(“”);
// Default Constructorpublic Order() {
}
// Accessor used to set the Order #
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G73
LISTING 6.4 Continued
![Page 93: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/93.jpg)
public void setOrder(String value) {
if ( value != null ) {
order = value;}
}
// Accessor used to get the Order #public String getOrder() {
return order;}
// Accessor used to set the Order Statuspublic void setStatus(String value) {
if ( value != null ) {
status = value;}
}
// Accessor used to get the Order Statuspublic String getStatus() {
return status;}
}
The Order object encapsulates the order and its status, and it will be passed between the appletand servlet.
The OrderStatusAppletThe OrderStatusApplet will leverage some of the Java Swing classes that are bundled withthe JDK 1.1.6. You do not need to concern yourself with all the swing classes. The only twoyou need to understand are the JTextField and JTextArea classes. The JTextField will holdyour order number, and the JTextArea will display the returned status. Listing 6.6 contains thesource for the client applet.
Servlet Fundamentals
PART I74
LISTING 6.5 Continued
![Page 94: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/94.jpg)
LISTING 6.6 OrderStatusApplet.java
import java.awt.*;import java.awt.event.*;import java.applet.*;import com.sun.java.swing.*;import java.net.*;import java.io.*;
//import com.sun.java.swing.UIManager;public class OrderStatusApplet extends JApplet {
boolean isStandalone = false;JPanel jStatusPanel = new JPanel();JPanel jActionPanel = new JPanel();GridLayout gridLayout1 = new GridLayout(1, 2);JButton jGetStatusButton = new JButton();JTextField jOrderTextField = new JTextField();JLabel jLabel1 = new JLabel();JTextArea jStatusResultTextArea = new JTextArea();
//Get a parameter valuepublic String getParameter(String key, String def) {
return isStandalone ? System.getProperty(key, def) :(getParameter(key) != null ? getParameter(key) : def);
}
// Default Constructpublic OrderStatusApplet() {
}
//Initialize the appletpublic void init() {
try {
jbInit();}catch (Exception e) {
e.printStackTrace();}
}
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G75
![Page 95: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/95.jpg)
//Component initializationprivate void jbInit() throws Exception {
this.setSize(400,150);this.getContentPane().setLayout(gridLayout1);jGetStatusButton.setText(“Get Status”);jGetStatusButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jGetStatusButton_actionPerformed(e);}
});jLabel1.setText(“Order #”);jOrderTextField.setPreferredSize(new Dimension(50, 19));jStatusResultTextArea.setPreferredSize(new Dimension(175, 135));
this.getContentPane().add(jActionPanel, null);jActionPanel.add(jLabel1, null);jActionPanel.add(jOrderTextField, null);jActionPanel.add(jGetStatusButton, null);this.getContentPane().add(jStatusPanel, null);jStatusPanel.add(jStatusResultTextArea, null);
}
//Get Applet informationpublic String getAppletInfo() {
return “Applet Information”;}
//Get parameter infopublic String[][] getParameterInfo() {
return null;}
// Write the StudentList to the Connectionpublic void writeOrder(URLConnection connection,Order value) {
try {
Servlet Fundamentals
PART I76
LISTING 6.6 Continued
![Page 96: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/96.jpg)
// Set this to false in order to ignore cachingconnection.setUseCaches(false);
// Set the content-type of the request// application/octet-stream is used when writing// application specific byte size dataconnection.setRequestProperty(“CONTENT_TYPE”,“application/octet-stream”);
// Set these vales to true to use the same connection// for both input and outputconnection.setDoInput(true);connection.setDoOutput(true);
// Create the ObjectOutputStream passing it the// ByteArrayOutputStream object.ObjectOutputStream os =new ObjectOutputStream(connection.getOutputStream());
// Write the StudentList to the ObjectOutputStreamSystem.err.println(“Writing Order Object.”);os.writeObject(value);os.flush();os.close();
}catch (IOException e) {
System.err.println(e.getMessage());}
}
public Order readOrder(URLConnection connection){
Order order = null;
try {
// Create the ObjectInputStream passing it the// InputStream object from the URLConnectionObjectInputStream is = new ObjectInputStream(connection.getInputStream());
System.err.println(“Waiting for response.”);
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G77
LISTING 6.6 Continued
![Page 97: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/97.jpg)
// Read the stored object and downcast it back to// a Orderorder = (Order)is.readObject();is.close();
}catch (IOException e) {
System.err.println(e.getMessage());}catch (ClassNotFoundException ce) {
System.err.println(ce.getMessage());}return order;
}
void jGetStatusButton_actionPerformed(ActionEvent event) {
try {
// This is where the OrderStatus Transaction beginsOrder order = new Order();
order.setOrder(jOrderTextField.getText());
// create our URLURL url = new URL(“http://localhost/djs” +“/servlet/OrderStatusServlet”);
// Open our URLConnectionSystem.err.println(“Opening Connection.”);URLConnection con = url.openConnection();
// Write the OrderwriteOrder(con, order);
// Get the Order from the response,// after the status has been checked, and print it out.Order response_order = readOrder(con);if ( response_order != null ) {
// Put the status String returned from the// OrderStatusServlet into the jTextArea ObjectjStatusResultTextArea.setText(
Servlet Fundamentals
PART I78
LISTING 6.6 Continued
![Page 98: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/98.jpg)
response_order.getStatus());}else {
System.err.println(“readObject failed.”);}
}catch (MalformedURLException mue) {
System.err.println(mue.getMessage());}catch (Exception e) {
System.err.println(e.getMessage());}
}}
The three areas of the applet you must focus on are thejGetStatusButton_actionPerformed(), writeOrder(), and readOrder() methods. Thesemethods make up the functional areas of the applet.
The jGetStatusButton_actionPerformed() method is where the transaction is invoked. Itcreates an Order object, setting the order attribute to the value typed into thejOrderTextField swing component. It then opens a URL connection pointing to yourOrderStatusServlet, http://localhost/djs/servlet/OrderStatusServlet. The connec-tion and the order are then passed to the writeOrder() method.
The writeOrder() method first sets the appropriate properties of the Connection object. Itthen creates an ObjectOutputStream using the OutputStream of the connection. When theObjectOutputStream is successfully created, the Order object is written to it.
When the writeOrder() method returns, the readOrder() method is called. It takes theURLConnection object passed to it and creates an ObjectInputStream. It then calls theObjectInputStream’s readObject() method, which block reads until a response object isreceived. This new Order object is then returned to the calling method.
The jGetStatusButton_actionPerformed() method then takes the Order object that wasreturned to it and calls the getStatus() method, passing the returned status to thejStatusResultTextArea’s setText() method.
Compile these classes, making sure that the swingall.jar file, which contains all the swingcomponents, is in your CLASSPATH. The HTML used to load this applet is shown in Listing 6.7.
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G79
LISTING 6.6 Continued
![Page 99: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/99.jpg)
LISTING 6.7 OrderStatusApplet.html
<HTML><HEAD><TITLE>Order Status Page</TITLE></HEAD><BODY><APPLETARCHIVE = “swingall.jar”CODE = “OrderStatusApplet.class”NAME = “Order Status Applet”WIDTH = 400HEIGHT = 150HSPACE = 0VSPACE = 0ALIGN = middle
></APPLET></BODY></HTML>
Servlet Fundamentals
PART I80
For this example, you must copy the HTML file and the compiled class files into yourWeb server’s document area. You will also need to have the swingall.jar file in thissame area. If you are using the Tomcat server, you can copy all of the client-side filesto the SERVER_ROOT/djs/ directory. You should also note that this example has onlybeen tested using Microsoft’s Internet Explorer v5.5.
NOTE
After you have compiled and installed the HTML and class files, you can load theOrderStatusApplet.html file. Figure 6.1 shows the OrderStatusApplet after it is loaded.
The OrderStatusServletThe OrderStatusServlet services order-status requests sent by the OrderStatusApplet. Itreads the Order object from the ObjectInputStream and passes it to the getOrderStatus()method. In a “real-world” application, this method would be a client to some other real-timeserver. It could be a CORBA client, an RMI client, or even a JDBC query to a database. Forthe example, it simply calls the Order.setStatus() method, passing it the string “Your order
![Page 100: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/100.jpg)
is in transit”. The service() method then writes the Order object to theObjectOutputStream to be read by the OrderStatusApplet. Listing 6.8 contains the sourcefor the OrderStatusServlet.
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G81
FIGURE 6.1The OrderStatusApplet.
LISTING 6.8 OrderStatusServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
public class OrderStatusServlet extends HttpServlet {
//Initialize global variablespublic void init(ServletConfig config)throws ServletException {
super.init(config);}
private void getOrderStatus(Order order) {
// This could do just about anything;
![Page 101: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/101.jpg)
// It could be CORBA/RMI client// It could be a database query, etc.order.setStatus(“Your order is in transit.”);
}
//Service the requestpublic void service(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
try {
// Create the ObjectInputStream with// the Request InputStream.ObjectInputStream ois =new ObjectInputStream(request.getInputStream());
// Read the Object. Make sure the StudentList Object// is in your CLASSPATH or you will receive a// ClassNotFoundException.Order order = (Order)ois.readObject();
getOrderStatus(order);
// The Response Begins Hereresponse.setContentType(“application/octet-stream”);
ObjectOutputStream oos =new ObjectOutputStream(response.getOutputStream());
// Echo the object to the responseoos.writeObject(order);oos.flush();oos.close();
}catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());}
}//Get Servlet information
public String getServletInfo() {return “OrderStatusServlet Information”;
}}
Servlet Fundamentals
PART I82
LISTING 6.8 Continued
![Page 102: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/102.jpg)
After you have a chance to look over the source for the OrderStatusServlet, build and installit to the Tomcat server. You then need to load the OrderStatusApplet into your browser, enteran order number, and click the Get Status button. Your results should look similar to Figure 6.2.
HTTP Tunneling
CHAPTER 6
6
HTTP T
UN
NELIN
G83
The Order.class file must be in the <SERVER_ROOT>djs/WEB-INF/classes/ directory,or the OrderStatusServlet will not be able to find it.
NOTE
FIGURE 6.2Results from OrderStatusServlet.
Pros and Cons of Applet-to-Servlet CommunicationAs you have seen in the previous sections, HTTP tunneling is a very simple method for applet-to-servlet communication, but it does have its own set of pros and cons. Some of the pros ofusing HTTP tunneling are as follows:
• It is simple to use because of the Serializable interface.
• It is very fast for lightweight objects.
![Page 103: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/103.jpg)
• It shields you from the transport layer.
• It provides you with a method of tunneling through firewalls.
On the other hand, some cons of this technique are the following:
• You must make sure that all your objects and nested objects implement theSerializable interface.
• Because you are opening a connection with an applet, security issues limit you to con-necting only to the applet’s originating server.
• When you start using larger objects or collections of objects, your throughput declinesconsiderably.
• Because you are using an applet as a client, you must make sure that your users have acompatible browser.
SummaryThis chapter covered the basics of Java serialization. You created two servlets that servicedHTTP tunneling requests. You also took a look at applets and applications as HTTP tunnelingclients. At this point, you should be able to create your own servlet that can service HTTP tun-neling requests. You should understand how to create Serializable objects. You should alsobe able to determine when to use (or not use) an applet-to-servlet solution.
In the next chapter, you will look at Java’s JDBC. You will first go over a basic introduction tothe JDBC and then examine how you can leverage the JDBC in servlets.
Servlet Fundamentals
PART I84
![Page 104: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/104.jpg)
CHAPTER
7Servlets, JDBC, and Inter-Servlet Communications
IN THIS CHAPTER• What is the JDBC? 86
• Two- and Three-Tier Database Access Models 86
• JDBC Driver Types 87
• JDBC Basics 92
• A Basic JDBC Servlet 107
• A JDBC Connection Pool 112
• Inter-Servlet Communications 123
![Page 105: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/105.jpg)
Servlet Fundamentals
PART I86
What is the JDBC?The JDBC (short for Java Database Connectivity) interface is a pure Java API used to executeSQL statements. The JDBC provides a set of classes and interfaces that can be used by devel-opers to write database applications. Basic JDBC interaction, in its simplest form, can be bro-ken down into four steps:
1. Open a connection to the database.
2. Execute a SQL statement.
3. Process the results.
4. Close the connection to the database.
The following code fragment shows these steps in action:
// Step 1. Open a connection to the ODBC datasource titles.con = DriverManager.getConnection(“jdbc:odbc:titles”,
“username”, “password”);
// Step 2. Execute the SQL statement.Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(“SELECT * “ +“FROM Types”);
// Step 3. Process the Resultswhile ( rs.next() ) {
// get the type_id, which is an intSystem.err.println(“Type ID = “ + rs.getInt(“type_id”));// get the type_name, which is a StringSystem.err.println(“Type Name = “ + rs.getString(“type_name”));
}
// Step 4. Close the Connection.rs.close();con.close();
This chapter will introduce the JDBC and explore how to use it in a servlet.
Two- and Three-Tier Database Access ModelsThe JDBC provides support for two- and three-tier database access models. We will examineboth in this section.
![Page 106: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/106.jpg)
When you use the two-tier database access model, your Java application talks directly to thedatabase. This is accomplished through the use of a JDBC driver, which sends commandsdirectly to the database. The results of these commands are then sent back from the databasedirectly to the application. Figure 7.1 shows the two-tier model.
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
87
Java Application
JDBC Driver
Application Space
Database
SQL Command Result Set
FIGURE 7.1The two-tier JDBC model.
The three-tier model, as you might have guessed, is a little more complicated. When you usethe three-tier model, your JDBC driver sends commands to a middle tier, which in turn sendscommands to the database. The results of these commands are then sent back to the middletier, which communicates them back to the application. Figure 7.2 shows the three-tier model.
JDBC Driver TypesSun has defined four JDBC driver types:
• JDBC-ODBC Bridge, plus ODBC driver
• Native-API, partly Java driver
• JDBC-net, pure Java driver
• Native-protocol, pure Java driver
Each of these types meets a different application need, as we’ll discuss in the following sec-tions.
![Page 107: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/107.jpg)
FIGURE 7.2The three-tier JDBC model.
Type 1: JDBC-ODBC Bridge, Plus ODBC DriverThe first type of JDBC driver is the JDBC-ODBC Bridge. This driver type is provided by Sunwith the JDK 1.1 and later. It provides JDBC access to databases through Open DatabaseConnectivity (ODBC) drivers. The ODBC driver must be configured on the client for thebridge to work. This driver type is commonly used for prototyping or when there is no JDBCdriver available for a particular Database Management System (DBMS). Figure 7.3 shows thedriver interaction of the JDBC-ODBC Bridge.
Type 2: Native-API, Partly Java DriverThe native-API driver converts JDBC commands into DBMS-specific native calls. This ismuch like the restriction of Type 1 drivers, in that the client must have some binary codeloaded on its machine. These drivers do have an advantage over Type 1 drivers, because theyinterface directly with the database. Figure 7.4 shows the interactions of a Type 2 driver.
Servlet Fundamentals
PART I88
Database
Proprietary Protocol
Java Application
Application Server(middle-tier)
JDBC Driver
Application Space
SQL Command Result Set
![Page 108: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/108.jpg)
FIGURE 7.3The Type 1 JDBC-ODBC Bridge.
Type 3: JDBC-Net, Pure Java DriverThe JDBC-Net drivers are a three-tier solution. This type of driver translates JDBC calls into adatabase-independent network protocol that is sent to a middleware server. This server thentranslates this DBMS-independent protocol into a DBMS-specific protocol, which is sent to aparticular database. The results are routed back through the middleware server and sent back tothe client. This type of solution makes it possible to implement a pure Java client. It alsomakes it possible to swap databases without affecting the client. This is by far the most flexibleJDBC solution. Figure 7.5 shows this three-tier solution.
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
89
Database
Proprietary Protocol
Java Application
ODBC Driver
JDBC-PDBC Bridge
Application Space
SQL Command Result Set
![Page 109: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/109.jpg)
FIGURE 7.4The Type 2 Native-API JDBC driver.
Type 4: Native-Protocol, Pure Java DriverThe Type 4 drivers are pure Java drivers that communicate directly with the vendor’s database.They do this by converting JDBC commands directly into the database engine’s native proto-col. The Type 4 driver has a very distinct advantage over all the other driver types: It has noadditional translation or middleware layer, which improves performance tremendously. Figure7.6 diagrams the communications of a Type 4 driver.
Servlet Fundamentals
PART I90
Database
Proprietary Protocol
Java Application
Native Database Library
Type 2 JDBC Driver
Application Space
SQL Command Result Set
![Page 110: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/110.jpg)
FIGURE 7.5The Type 3 JDBC-Net driver.
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
91
Database
Proprietary Protocol
Java Application
Type 3 JDBC Driver
JDBC Driver
Application Space
Middleware Space
SQL Command Result Set
Java Application
Type 4 JDBC Driver
Application Space
Database
SQL CommandUsing Proprietary Protocol
Result SetUsing Proprietary Protocol
FIGURE 7.6The Type 4 native-protocol JDBC driver.
![Page 111: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/111.jpg)
JDBC BasicsNow that we have discussed what the JDBC is and some of its characteristics, let’s start learn-ing how to use it. In this section, we will discuss how to install and set up a Type 1 driver,make a connection to the database, and perform the basic SQL commands.
Installing and Setting Up a Type 1 DriverIn the JDBC examples throughout this book, you will be connecting to a Microsoft Accessdatabase using a Type 1 driver. To install the JDBC-ODBC Bridge, download the JDK and fol-low the installation directions. The JDBC-ODBC Bridge is included in version 1.1 and later.
The JDBC-ODBC Bridge requires no specific setup steps, but the ODBC driver does. For ourexamples, assume that you are using a PC and running Windows NT or 2000. If not, you willneed to create your own database using the drivers supplied by your database vendor.
To configure the ODBC data source for the examples, you will follow these steps:
1. Copy to your local drive the database file moviecatalog.mdb, which can be found on thebook’s Web site.
2. Start the application ODBC. You will see a window similar to the one in Figure 7.7.
Servlet Fundamentals
PART I92
FIGURE 7.7The ODBC Administrator.
3. Select the System DSN tab and click the Add button to add a new data source. Figure 7.8shows the Create New Data Source screen.
![Page 112: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/112.jpg)
FIGURE 7.8The Create New Data Source screen.
4. Select the Microsoft Access Driver and click the Finish button. You will now see theODBC Microsoft Access Setup screen. Figure 7.9 shows this screen.
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
93
FIGURE 7.9The ODBC Microsoft Access Setup screen.
5. Enter the string “Movie Catalog” as the data source name and click the database Selectbutton. Enter the path to the location of your moviecatalog.mdb file and click OK. Youwill now see the ODBC Microsoft Access Setup screen with your changes displayed.Click OK to commit to your changes.
6. You will now see the ODBC Data Source Administrator screen with the Movie Catalogdata source in the list. Click the OK button to close this window.
Establishing a Database ConnectionThe first thing you need to do when using the JDBC is establish a connection to the database.This is a two-step process. You must load the JDBC driver and then make a connection.
![Page 113: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/113.jpg)
Loading a JDBC driver is very simple. It takes only one line of code. In our examples, we willbe using the JDBC-ODBC Bridge. The class name for this driver issun.jdbc.odbc.JdbcOdbcDriver. The following code snippet shows you how to load this dri-ver:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
When you call the Class.forName() method, it creates an instance of the driver and registers itwith the DriverManager. This is all there is to loading a JDBC driver.
After you have the driver loaded, it is easy to make a connection. You make a call to the staticmethod DriverManager.getConnection(), which returns a connection to the database. Itsmethod signature is listed as follows:
public static synchronized Connection getConnection(String url, String user, String password) throws SQLException
The first parameter is the URL that points to your data source. In the case of the JDBC-ODBCBridge, it always begins with jdbc:odbc:DataSourceName, where the DataSourceName is thename of the ODBC data source you set up.
The next two parameters are self-explanatory. They are the username and password associatedwith the database login. For this example, you will use empty strings for each. Here is the codeused to open a connection to your Movie Catalog database:
con = DriverManager.getConnection(“jdbc:odbc:Movie Catalog”,“”, “”);
The Connection object returned from the DriverManager is an open connection to the data-base. You will be using it to create JDBC statements that pass SQL statements to the database.
Performing the Basic SQL CommandsIn this section we will look at how to create a JDBC Statement object and five JDBC exam-ples that use the Statement object. In all the examples, you will be using the Movie Catalogdatabase that you configured earlier.
Creating a JDBC Statement ObjectTo execute any SQL command using a JDBC connection, you must first create a Statementobject. To create a statement, you need to call the Connection.createStatement() method. Itreturns a JDBC statement that you will use to send your SQL statements to the database. Thefollowing code snippet shows how to create a statement:
Statement statement = con.createStatement();
Servlet Fundamentals
PART I94
![Page 114: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/114.jpg)
Creating a TableThe first thing you will do is create a database table that represents a list of movie titles.Currently two tables are in the database: the Categories table and the Types table. Table 7.1shows the composition of your new Titles table.
TABLE 7.1 Titles Table Elements
Field Name Data Type
title_id INTEGER
title_name VARCHAR(50)
rating VARCHAR(5)
price FLOAT
quantity INTEGER
type_id INTEGER
category_id INTEGER
The application that creates this table can be found in Listing 7.1. Notice that it follows thestep-by-step process that I described earlier:
1. Open a connection to the database.
2. Execute a SQL statement.
3. Process the results.
4. Close the connection to the database.
LISTING 7.1 CreateTablesApp.java
import java.sql.*;
public class CreateTablesApp {
public void createTables() {
Connection con = null;
try {
// Load the Driver class fileClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
// Make a connection to the ODBC datasource Movie Catalog
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
95
![Page 115: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/115.jpg)
con = DriverManager.getConnection(“jdbc:odbc:Movie Catalog”,“”, “”);
// Create the statementStatement statement = con.createStatement();
// Use the created statement to CREATE the database table// Create Titles Tablestatement.executeUpdate(“CREATE TABLE Titles “ +“(title_id INTEGER, title_name VARCHAR(50), “ +“rating VARCHAR(5), price FLOAT, quantity INTEGER, “ +“type_id INTEGER, category_id INTEGER)”);
}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());}catch (Exception e) {
System.err.println(e.getMessage());}finally {
try {
if ( con != null ) {
// Close the connection no matter whatcon.close();
}}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}
}}
public static void main(String[] args) {
Servlet Fundamentals
PART I96
LISTING 7.1 Continued
![Page 116: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/116.jpg)
CreateTablesApp createTablesApp = new CreateTablesApp();
createTablesApp.createTables();}
}
The section we want to focus on is listed here:
// Create the statementStatement statement = con.createStatement();
// Use the created statement to CREATE the database table// Create Titles Tablestatement.executeUpdate(“CREATE TABLE Titles “ +“(title_id INTEGER, title_name VARCHAR(50), “ +“rating VARCHAR(5), price FLOAT, quantity INTEGER, “ +“type_id INTEGER, category_id INTEGER)”);
The first statement executed creates a Statement object with the given Connection. To per-form the actual creation of the table, call the Statement.executeUpdate() method, passing itthe SQL statement to create the table. Its signature is listed as follows:
public int executeUpdate(String sql) throws SQLException
This method is used for all update-type transactions. It takes a string representation of an SQLstatement and returns an integer. The return value is either a row count for INSERT, UPDATE, andDELETE statements, or 0 for SQL statements that return nothing, such as a CREATE.
After you have created the Titles table, the table relationships of your Movie Catalog databasewill look something like Figure 7.10.
Inserting Data into a TableNow that you have all your tables in place, you can put some data into them. Listing 7.2 showsthe application used to populate your Movie Catalog database.
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
97
LISTING 7.1 Continued
![Page 117: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/117.jpg)
FIGURE 7.10The Movie Catalog database.
LISTING 7.2 InsertDataApp.java
import java.sql.*;
public class InsertDataApp {
public InsertDataApp() {}
public void insertData() {
Connection con = null;
try {
// Load the Driver class fileClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
// Make a connection to the ODBC datasource Movie Catalogcon = DriverManager.getConnection(“jdbc:odbc:Movie Catalog”,“”, “”);
Servlet Fundamentals
PART I98
![Page 118: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/118.jpg)
// Create the statementStatement statement = con.createStatement();
// Use the created statement to INSERT DATA into// the database tables.
// Insert Data into the Types Tablestatement.executeUpdate(“INSERT INTO Types “ +“VALUES (0, ‘VHS’)”);
statement.executeUpdate(“INSERT INTO Types “ +“VALUES (1, ‘DVD’)”);
statement.executeUpdate(“INSERT INTO Types “ +“VALUES (2, ‘Laserdisc’)”);
// Insert Data into the Categories Tablestatement.executeUpdate(“INSERT INTO Categories “ +“VALUES (0, ‘Action Adventure’)”);
statement.executeUpdate(“INSERT INTO Categories “ +“VALUES (1, ‘Comedy’)”);
statement.executeUpdate(“INSERT INTO Categories “ +“VALUES (2, ‘Drama’)”);
statement.executeUpdate(“INSERT INTO Categories “ +“VALUES (3, ‘Western’)”);
statement.executeUpdate(“INSERT INTO Categories “ +“VALUES (4, ‘Sci-Fi’)”);
statement.executeUpdate(“INSERT INTO Categories “ +“VALUES (5, ‘Classics’)”);
// Insert Data into the Titles Tablestatement.executeUpdate(“INSERT INTO Titles “ +“VALUES (0, ‘The Adventures of Buckaroo Banzai’, “ +“‘PG’, 19.95, 10, 0, 4)”);
statement.executeUpdate(“INSERT INTO Titles “ +“VALUES (1, ‘Saving Private Ryan’, “ +“‘R’, 19.95, 12, 1, 0)”);
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
99
LISTING 7.2 Continued
![Page 119: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/119.jpg)
statement.executeUpdate(“INSERT INTO Titles “ +“VALUES (2, ‘So I Married An Axe Murderer’, “ +“‘PG’, 19.95, 15, 1, 1)”);
statement.executeUpdate(“INSERT INTO Titles “ +“VALUES (3, ‘Happy Gilmore’, “ +“‘PG’, 19.95, 9, 1, 1)”);
statement.executeUpdate(“INSERT INTO Titles “ +“VALUES (4, ‘High Plains Drifter’, “ +“‘PG’, 29.95, 10, 2, 3)”);
statement.executeUpdate(“INSERT INTO Titles “ +“VALUES (5, ‘Cape Fear’, “ +“‘NR’, 6.99, 21, 0, 5)”);
statement.executeUpdate(“INSERT INTO Titles “ +“VALUES (6, ‘The Last Emperor’, “ +“‘PG’, 19.95, 12, 1, 2)”);
}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());}catch (Exception e) {
System.err.println(e.getMessage());}finally {
try {
if ( con != null ) {
// Close the connection no matter whatcon.close();
}}catch (SQLException sqle) {
Servlet Fundamentals
PART I100
LISTING 7.2 Continued
![Page 120: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/120.jpg)
System.err.println(sqle.getMessage());}
}}
public static void main(String[] args) {
InsertDataApp insertDataApp = new InsertDataApp();
insertDataApp.insertData();}
}
The InsertDataApp application uses the same executeUpdate() method you used to createyour tables. You only change the SQL string that you pass to it, using a basic SQL INSERTstatement instead. You insert data into your Types, Categories, and Titles tables, respectively.Also notice that you can perform all your inserts using the same Statement object. There isnothing preventing you from reusing this object, instead of creating a new one for each execu-tion.
Selecting Data from a TableThe most common SQL statement is the SELECT statement. It gives you the ability to look atthe data stored in your tables. In the previous examples, you created and populated the MovieCatalog database. In this example, we are going to look at the data you put in these tables, andwe will do it with a SELECT statement. Listing 7.3 contains the source for this example.
LISTING 7.3 SelectDataApp.java
import java.sql.*;import java.io.*;
public class SelectDataApp {
public SelectDataApp() {
}
public void selectData() {
Connection con = null;
try {
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
101
LISTING 7.2 Continued
![Page 121: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/121.jpg)
// Load the Driver class fileClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
// Make a connection to the ODBC datasource Movie Catalogcon = DriverManager.getConnection(“jdbc:odbc:Movie Catalog”,“”, “”);
// Create the statementStatement statement = con.createStatement();
// Use the created statement to SELECT the DATA// FROM the Titles Table.ResultSet rs = statement.executeQuery(“SELECT * “ +“FROM Titles”);
// Iterate over the ResultSetwhile ( rs.next() ) {
// get the title_name, which is a StringSystem.err.println(“Title Name = “ + rs.getString(“title_name”));// get the ratingSystem.err.println(“Title Rating = “ + rs.getString(“rating”));// get the priceSystem.err.println(“Title Price = “ + rs.getString(“price”));// get the quantitySystem.err.println(“Title Quantity = “ + rs.getString(“quantity”)+ “\n”);
}// Close the ResultSetrs.close();System.in.read();
}catch (IOException ioe) {
System.err.println(ioe.getMessage());}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());
Servlet Fundamentals
PART I102
LISTING 7.3 Continued
![Page 122: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/122.jpg)
}catch (Exception e) {
System.err.println(e.getMessage());}finally {
try {
if ( con != null ) {
// Close the connection no matter whatcon.close();
}}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}
}}
public static void main(String[] args) {
SelectDataApp selectDataApp = new SelectDataApp();
selectDataApp.selectData();}
}
To execute a query, use the same Statement object as in previous examples. You just call a dif-ferent method. The method to perform a query is executeQuery(). Its signature is listed here:
public ResultSet executeQuery(String sql) throws SQLException
It takes a SQL string like the executeUpdate() method. The difference fromexecuteUpdate() is that executeQuery() returns a ResultSet object containing the results ofthe query. In the example, you pass it the string “SELECT * FROM Titles”, which returns acollection of rows resulting from the query.
After you have your ResultSet object returned from executeQuery(), you can iterate over it.The following code snippet shows how the example processes the query results:
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
103
LISTING 7.3 Continued
![Page 123: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/123.jpg)
// Iterate over the ResultSetwhile ( rs.next() ) {
// get the title_name, which is a StringSystem.err.println(“Title Name = “ + rs.getString(“title_name”));// get the ratingSystem.err.println(“Title Rating = “ + rs.getString(“rating”));// get the priceSystem.err.println(“Title Price = “ + rs.getString(“price”));// get the quantitySystem.err.println(“Title Quantity = “ + rs.getString(“quantity”)+ “\n”);
}// Close the ResultSetrs.close();
The first thing you do is call the ResultSet.next() method. This method returns a Booleanvalue, indicating whether the next row in the set is valid. If it is, you can access that row usingthe Get accessors provided by the ResultSet object. In our example, you use only thegetString() method; but the Get accessors all function the same except for their return type.They take a string value representing the name of the column in the table and return the typethat is part of their method name. For example, getString() returns a java.lang.String andgetInt() returns an int. You can continue iterating over the ResultSet until next() returnsfalse; at that point you need to close the ResultSet object. When you execute this applica-tion, the results will be similar to the following output:
Title Name = The Adventures of Buckaroo BanzaiTitle Rating = PGTitle Price = 19.95Title Quantity = 10
Title Name = Saving Private RyanTitle Rating = RTitle Price = 19.95Title Quantity = 12
Title Name = So I Married An Axe MurdererTitle Rating = PGTitle Price = 19.95Title Quantity = 15
Title Name = Happy GilmoreTitle Rating = PGTitle Price = 19.95Title Quantity = 9
Servlet Fundamentals
PART I104
![Page 124: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/124.jpg)
Title Name = High Plains DrifterTitle Rating = PGTitle Price = 29.95Title Quantity = 10
Title Name = Cape FearTitle Rating = NRTitle Price = 6.99Title Quantity = 21
Title Name = The Last EmperorTitle Rating = PGTitle Price = 19.95Title Quantity = 12
Updating TablesAnother SQL command we need to examine is the UPDATE statement. It looks for a matchingcondition and makes the specified changes if the WHERE clause is true. An example of thiswould be if you sold seven copies of The Last Emperor. You would need to update its quantityto 5. The example in Listing 7.4 does just that.
LISTING 7.4 UpdateDataApp.java
import java.sql.*;
public class UpdateDataApp {
public UpdateDataApp() {
}
public void updateData() {
Connection con = null;
try {
// Load the Driver class fileClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
// Make a connection to the ODBC datasource Movie Catalogcon = DriverManager.getConnection(“jdbc:odbc:Movie Catalog”,“”, “”);
// Create the statement
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
105
![Page 125: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/125.jpg)
Statement statement = con.createStatement();
// Use the created statement to UPDATE DATA in// the database tables.// Update the Quantity of “The Last Emperor”statement.executeUpdate(“UPDATE Titles “ +“SET quantity = 5 “ +“WHERE title_name = ‘The Last Emperor’”);
}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());}catch (Exception e) {
System.err.println(e.getMessage());}finally {
try {
if ( con != null ) {
// Close the connection no matter whatcon.close();
}}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}
}}
public static void main(String[] args) {
UpdateDataApp updateDataApp = new UpdateDataApp();
updateDataApp.updateData();}
}
Servlet Fundamentals
PART I106
LISTING 7.4 Continued
![Page 126: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/126.jpg)
If you examine the executeUpdate() method in Listing 7.4, you will see the appropriate SQLstring used to perform the previously mentioned update. Run this application and then run theexample from Listing 7.3. You will see the change to the quantity value of The Last Emperor.
Deleting Data from a TableThe last topic for this section is deleting data from the database. It is not much different fromthe previous database updating functions, but it does deserve its own section.
To delete a row from a table, you again use the executeUpdate() method. The only changewill be the SQL statement you pass to it. In this example, assume you have decided to takeCape Fear off the market. It just doesn’t sell as well as it did in previous years. So, you put aSQL string together and substitute it into the executeUpdate() method. The changed call willlook something like the following snippet:
// Use the created statement to DELETE DATA// FROM the Titles table.statement.executeUpdate(“DELETE FROM Titles “ +“WHERE title_name = ‘Cape Fear’”);
After you have run this application, run SelectDataApp again and you will see that the titleCape Fear is no longer in the database.
A Basic JDBC ServletIn this section, you will connect the JDBC and servlets. You will create a servlet that gets themovie rating parameter from the request and searches for all titles with this matching rating.The servlet that does this will be called the TitleListServlet and is shown in Listing 7.5.
LISTING 7.5 TitleListServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.sql.*;
public class TitleListServlet extends HttpServlet {
public void init(ServletConfig config)throws ServletException {
super.init(config);}
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
107
![Page 127: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/127.jpg)
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
doPost(request, response);}
//Process the HTTP Post requestpublic void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
// Set the response content-typeresponse.setContentType(“text/html”);// get the Writer objectPrintWriter out = response.getWriter();
out.println(“<html>\n<body>\n<table border=\”1\” width=\”100%\”>”);
// Get the search_string parameter, passed from the// SearchServlet.String search_string =request.getParameter(“search_string”);
Connection con = null;
try {
// Load the Driver class fileClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
System.err.println(“Getting Connection!”);
// Make a connection to the ODBC datasource Movie Catalog// In this example we are opening a connection to the// database with every request.con = DriverManager.getConnection(“jdbc:odbc:Movie Catalog”,
“”, “”);
if ( con != null ) {
System.err.println(“Got Connection!”);
Servlet Fundamentals
PART I108
LISTING 7.5 Continued
![Page 128: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/128.jpg)
// Create the statementStatement statement = con.createStatement();
// Use the created statement to SELECT the DATA// FROM the Titles Table.// In this instance we are searching for an exact match.// If you were to deploy this to a production site, you// might want to use a “LIKE” clause instead of WHERE.ResultSet rs = statement.executeQuery(“SELECT * “ +
“FROM Titles WHERE rating = ‘“ +search_string + “‘“);
// Iterate over the ResultSetwhile ( rs.next() ) {
out.println(“<tr>”);
// get the id, which is an intout.println(“<td>” + rs.getInt(“title_id”) + “</td>”);
// get the name, which is a Stringout.println(“<td>” + rs.getString(“title_name”) + “</td>”);
// get the rating, which is a Stringout.println(“<td>” + rs.getString(“rating”) + “</td>”);
// get the price, which is a Floatout.println(“<td>” + rs.getFloat(“price”) + “</td>”);
// get the Quantity, which is a Integerout.println(“<td>” + rs.getInt(“quantity”) + “</td>”);
// get the Type, which is a Integerout.println(“<td>” + rs.getInt(“type_id”) + “</td>”);
// get the Category, which is a Integerout.println(“<td>” + rs.getInt(“category_id”) + “</td>”);
out.println(“</tr>”);}// Close the ResultSetrs.close();out.println(“</table>”);
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
109
LISTING 7.5 Continued
![Page 129: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/129.jpg)
}}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());}catch (Exception e) {
System.err.println(e.getMessage());}finally {
try {
if ( con != null ) {
// Close the connection no matter whatcon.close();
}}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}
}out.println(“</body></html>”);out.close();
}
//Get Servlet informationpublic String getServletInfo() {
return “TitleListServlet Information”;}
}
All the action in the TitleListServlet is taking place in the doPost() method. It first gets thesearch_string passed in the request on the URL. The next steps involved are opening a con-nection to the database, performing a query using the search_string, displaying the results,
Servlet Fundamentals
PART I110
LISTING 7.5 Continued
![Page 130: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/130.jpg)
and then closing the connection. This type of algorithm, although simple, is very time consum-ing. Opening and closing a database connection with every request is hardly an optimal solu-tion.
Now, take a look at this servlet in action. Open your browser to the following link:
http://yourserver/djs/servlet/TitleListServlet?search_string=PG
Your results should look similar to Figure 7.11. Try this several times so you can get used tothe speed.
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
111
FIGURE 7.11TitleListServlet output.
To speed up the servicing of requests, you could open the connection to the database in theinit() method and then close it in the destroy() method, but you would be limited to a sin-gle connection. If you chose to do this, you would need to have your servlet implement theSingleThreadModel interface. This interface defines a single-thread model for servlet execu-tion, guaranteeing that no two threads will execute concurrently the service() method of theimplementing servlet. This would save execution time, but would limit you to servicingrequests one at a time.
![Page 131: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/131.jpg)
A JDBC Connection PoolTo remedy the slow servicing of requests encountered in the previous section, you will create apool of connections to the database. This will give you access to a collection of already openeddatabase connections, which will reduce the time it takes to service a request, and you can ser-vice n number of requests at once.
The following are the requirements for the ConnectionPool object:
• It must hold n number of open connections.
• It must be able to determine when a connection is in use.
• If n+1 connections are requested, it must create a new connection and add it to the pool.
• When you close the pool, all connections must be released.
Now that we know what we want, let’s look at the result. The source for the ConnectionPoolis in Listing 7.6.
LISTING 7.6 ConnectionPool.java
package ConnectionPool;
import java.sql.*;import java.util.*;
public class ConnectionPool {
// JDBC Driver Nameprivate String driver = null;// URL of databaseprivate String url = null;// Initial number of connections.private int size = 0;// Usernameprivate String username = null;// Passwordprivate String password = null;// Vector of JDBC Connectionsprivate Vector pool = null;
public ConnectionPool() {
}
// Set the value of the JDBC Driver
Servlet Fundamentals
PART I112
![Page 132: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/132.jpg)
public void setDriver(String value) {
if ( value != null ) {
driver = value;}
}
// Get the value of the JDBC Driverpublic String getDriver() {
return driver;}
// Set the URL Pointing to the Datasourcepublic void setURL(String value ) {
if ( value != null ) {
url = value;}
}
// Get the URL Pointing to the Datasourcepublic String getURL() {
return url;}
// Set the initial number of connectionspublic void setSize(int value) {
if ( value > 1 ) {
size = value;}
}
// Get the initial number of connectionspublic int getSize() {
return size;}
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
113
LISTING 7.6 Continued
![Page 133: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/133.jpg)
// Set the usernamepublic void setUsername(String value) {
if ( value != null ) {
username = value;}
}
// Get the usernamepublic String getUserName() {
return username;}
// Set the passwordpublic void setPassword(String value) {
if ( value != null ) {
password = value;}
}
// Get the passwordpublic String getPassword() {
return password;}
// Creates and returns a connectionprivate Connection createConnection() throws Exception {
Connection con = null;
// Create a Connectioncon = DriverManager.getConnection(url,username, password);
return con;}
// Initialize the poolpublic synchronized void initializePool() throws Exception {
Servlet Fundamentals
PART I114
LISTING 7.6 Continued
![Page 134: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/134.jpg)
// Check our initial valuesif ( driver == null ) {
throw new Exception(“No Driver Name Specified!”);}if ( url == null ) {
throw new Exception(“No URL Specified!”);}if ( size < 1 ) {
throw new Exception(“Pool size is less than 1!”);}
// Create the Connectionstry {
// Load the Driver class fileClass.forName(driver);
// Create Connections based on the size memberfor ( int x = 0; x < size; x++ ) {
System.err.println(“Opening JDBC Connection “ + x);
Connection con = createConnection();
if ( con != null ) {
// Create a PooledConnection to encapsulate the// real JDBC ConnectionPooledConnection pcon = new PooledConnection(con);// Add the Connection to the pooladdConnection(pcon);
}}
}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}catch (ClassNotFoundException cnfe) {
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
115
LISTING 7.6 Continued
![Page 135: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/135.jpg)
System.err.println(cnfe.getMessage());}catch (Exception e) {
System.err.println(e.getMessage());}
}
// Adds the PooledConnection to the poolprivate void addConnection(PooledConnection value) {
// If the pool is null, create a new vector// with the initial size of “size”if ( pool == null ) {
pool = new Vector(size);}// Add the PooledConnection Object to the vectorpool.addElement(value);
}
public synchronized void releaseConnection(Connection con) {
// find the PooledConnection Objectfor ( int x = 0; x < pool.size(); x++ ) {
PooledConnection pcon =(PooledConnection)pool.elementAt(x);
// Check for correct Connectionif ( pcon.getConnection() == con ) {
System.err.println(“Releasing Connection “ + x);// Set its inuse attribute to false, which// releases it for usepcon.setInUse(false);break;
}}
}
// Find an available connectionpublic synchronized Connection getConnection()throws Exception {
Servlet Fundamentals
PART I116
LISTING 7.6 Continued
![Page 136: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/136.jpg)
PooledConnection pcon = null;
// find a connection not in usefor ( int x = 0; x < pool.size(); x++ ) {
pcon = (PooledConnection)pool.elementAt(x);
// Check to see if the Connection is in useif ( pcon.inUse() == false ) {
// Mark it as in usepcon.setInUse(true);// return the JDBC Connection stored in the// PooledConnection objectreturn pcon.getConnection();
}}
// Could not find a free connection,// create and add a new onetry {
// Create a new JDBC ConnectionConnection con = createConnection();// Create a new PooledConnection, passing it the JDBC// Connectionpcon = new PooledConnection(con);// Mark the connection as in usepcon.setInUse(true);// Add the new PooledConnection object to the poolpool.addElement(pcon);
}catch (Exception e) {
System.err.println(e.getMessage());}// return the new Connectionreturn pcon.getConnection();
}
// When shutting down the pool, you need to first empty it.public synchronized void emptyPool() {
// Iterate over the entire pool closing the
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
117
LISTING 7.6 Continued
![Page 137: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/137.jpg)
// JDBC Connections.for ( int x = 0; x < pool.size(); x++ ) {
System.err.println(“Closing JDBC Connection “ + x);
PooledConnection pcon =(PooledConnection)pool.elementAt(x);
// If the PooledConnection is not in use, close itif ( pcon.inUse() == false ) {
pcon.close();}else {
// If it’s still in use, sleep for 30 seconds and// force close.try {
java.lang.Thread.sleep(30000);pcon.close();
}catch (InterruptedException ie) {
System.err.println(ie.getMessage());}
}}
}}
The first steps in using the ConnectionPool are to create an instance of the object and set theappropriate accessors. This is accomplished in an init() method of a servlet that would beresponsible for initializing the ConnectionPool. This makes the ConnectionPool available toall future requests. An sample init() method follows:
//Initialize global variablespublic void init(ServletConfig config)
throws ServletException {
super.init(config);
// Instantiate the ConnectionPool
Servlet Fundamentals
PART I118
LISTING 7.6 Continued
![Page 138: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/138.jpg)
ConnectionPool pool = new ConnectionPool();
// Set the JDBC Driverpool.setDriver(“sun.jdbc.odbc.JdbcOdbcDriver”);// Set the URL to the Datasourcepool.setURL(“jdbc:odbc:Movie Catalog”);// Set the initial size of the Connection Poolpool.setSize(4);// Set the Usernamepool.setUsername(“”);// Set the Passwordpool.setPassword(“”);
// Initialize the poolpool.initializePool();
The init() method first creates an instance of the ConnectionPool. It then sets the accessorsappropriately. It sets the driver to the JDBC-ODBC Bridge, the data source URL to the MovieCatalog, and the initial number of connections to 4. The next two accessors (username andpassword) are set to empty strings. This is because the Microsoft Access database that we havecreated has no login or password.
The last executable line of the init() method initializes the ConnectionPool. This is wherethe ConnectionPool connections begin their life. An excerpt of the ConnectionPool’sinitializePool() method is listed as follows:
// Load the Driver class fileClass.forName(driver);
// Create Connections based on the size memberfor ( int x = 0; x < size; x++ ) {
System.err.println(“Opening JDBC Connection “ + x);
Connection con = createConnection();
if ( con != null ) {
// Create a PooledConnection to encapsulate the// real JDBC ConnectionPooledConnection pcon = new PooledConnection(con);// Add the Connection the pool.addConnection(pcon);
}}
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
119
![Page 139: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/139.jpg)
The initializePool() method first loads the JDBC driver. It then creates size number ofConnection objects. For each Connection object created, it creates a PooledConnectionobject, passing it the Connection in the constructor. Finally, it adds the newly createPooledConnection object to the pool.
The PooledConnection object simply wraps a JDBC Connection object in a class that holdsthe connection and a flag that determines whether the connection is in use or not. It is listed inListing 7.9.
LISTING 7.9 PooledConnection.java
package ConnectionPool;
import java.sql.*;
public class PooledConnection {
// Real JDBC Connectionprivate Connection connection = null;// boolean flag used to determine if connection is in useprivate boolean inuse = false;
// Constructor that takes the passed in JDBC Connection// and stores it in the connection attribute.public PooledConnection(Connection value) {
if ( value != null ) {
connection = value;}
}
// Returns a reference to the JDBC Connectionpublic Connection getConnection() {
// get the JDBC Connectionreturn connection;
}
// Set the status of the PooledConnection.public void setInUse(boolean value) {
inuse = value;}
Servlet Fundamentals
PART I120
![Page 140: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/140.jpg)
// Returns the current status of the PooledConnection.public boolean inUse() {
return inuse;}
// Close the real JDBC Connectionpublic void close() {
try {
connection.close();}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}
}}
Next we need to look at the doPost()/doGet() method of the servlet that initialized theConnectionPool. Whereas in the TitleListServlet you had to load the driver and call theDriverManager.getConnection() method directly, here all you have to do is call theConnectionPool.getConnection(), which will iterate through its vector of connections untilit finds an available connection. If it cannot find an available connection, it will create one andadd it to the pool. It will then mark the connection as in use and return it. A sample doPost()method follows:
//Process the HTTP Post requestpublic void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType(“text/html”);PrintWriter out = response.getWriter();
Connection con = null;try {
// Get a connection from the ConnectionPoolcon = pool.getConnection();
if ( con != null ) {
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
121
LISTING 7.9 Continued
![Page 141: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/141.jpg)
// Create the statementStatement statement = con.createStatement();
// Use the created statement to SELECT the DATA// FROM the Titles Table.ResultSet rs = statement.executeQuery(“SELECT * “ +“FROM Titles”);
// iterate over the results here, if you choose!!!
// Close the ResultSetrs.close();
}}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}catch (Exception e) {
System.err.println(e.getMessage());}finally {
// Release the connectionpool.releaseConnection(con);
}out.close();
}
When the doPost() method is finished with the connection, it must return it to the pool. To dothis, it calls the ConnectionPools’s releaseConnection() method, passing it the Connectionobject:
// Release the connectionpool.releaseConnection(con);
The releaseConnection() method searches the pool for the Connection object and marks itas available for use.
The last interaction a servlet has with the ConnectionPool is when it shuts down. In itsdestroy() method, the servlet calls the ConnectionPool.emptyPool() method. This methoditerates over the entire pool, closing connections until all the Connection objects are closed.
Now you have access to pre-opened connections to the database and can service just about anynumber of simultaneous requests.
Servlet Fundamentals
PART I122
![Page 142: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/142.jpg)
Inter-Servlet CommunicationsIn the previous section, you saw how a connection pool saves you a lot of time when servicingrequests. Wouldn’t it be nice if, instead of creating a ConnectionPool local only to one spe-cific servlet, you could have a ConnectionPool that was global to all your servlets? To do this,you will need to create a servlet that can manage a ConnectionPool object and provide a wayfor other servlets to communicate with it. Listing 7.10 contains the source for a servlet thatwill do just this.
LISTING 7.10 ConnectionPoolServlet.java
package ConnectionPool;
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
public class ConnectionPoolServlet extends HttpServlet {
//Initialize global variablespublic void init(ServletConfig config)throws ServletException {
super.init(config);
// Instantiate the ConnectionPoolConnectionPool pool = new ConnectionPool();
try {
// Set the JDBC Driverpool.setDriver(“sun.jdbc.odbc.JdbcOdbcDriver”);// Set the URL to the Datasourcepool.setURL(“jdbc:odbc:Movie Catalog”);// Set the initial size of the Connection Pool
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
123
The database you use will, of course, determine the number of connections you canreally have opened at once. Consult your database documentation or license agree-ment for this number.
NOTE
![Page 143: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/143.jpg)
pool.setSize(4);// Set the Usernamepool.setUsername(“”);// Set the Passwordpool.setPassword(“”);
// Initialize the poolpool.initializePool();
// Once the pool is Initialized, add it to the// Global ServletContext. This makes it available// To other servlets using the same ServletContext.ServletContext context = getServletContext();context.setAttribute(“CONNECTION_POOL”, pool);
}catch (Exception e) {
System.err.println(e.getMessage());}
}
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
// Set the response content-typeresponse.setContentType(“text/html”);// get the Writer objectPrintWriter out = response.getWriter();out.println(“This Servlet does not service requests!”);out.close();
}
public void destroy() {
// Access the ServletContext using the getAttribute()// method, which returns a reference to the ConnectionPool.ServletContext context = getServletContext();ConnectionPool pool =
(ConnectionPool)context.getAttribute(“CONNECTION_POOL”);
if ( pool != null ) {
Servlet Fundamentals
PART I124
LISTING 7.10 Continued
![Page 144: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/144.jpg)
// empty the poolpool.emptyPool();// Remove the Attribute from the ServletContextcontext.removeAttribute(“CONNECTION_POOL”);
}else {
System.err.println(“Could not get a reference to Pool!”);}
}
//Get Servlet informationpublic String getServletInfo() {
return “ConnectionPoolServlet Information”;}
}
The two areas of the ConnectionPoolServlet that you need to examine are the init() anddestroy() methods. The doGet() method is just a placeholder; it has no functionality.
The ConnectionPoolServlet.init() method creates the ConnectionPool and makes it avail-able to the other servlets. It does this by first creating an instance of the ConnectionPool justlike any other application would. It then takes the newly created ConnectionPool object andadds it to the shared ServletContext. It does this in the following code snippet:
// Once the pool is Initialized, add it to the// Global ServletContext. This makes it available// To other servlets using the same ServletContext.ServletContext context = getServletContext();context.setAttribute(“CONNECTION_POOL”, pool);
The preceding code gets a reference to the ServletContext, which is shared by all servletsthat exist in the same ServletContext. It then calls the setAttribute() method, passing it astring that represents a key and a reference to the ConnectionPool object. This makes theConnectionPool available to other servlets.
The destroy() method does just the opposite. It first gets a reference to the ConnectionPoolby calling the ServletContext.getAttribute() method. The signature for this method is asfollows:
public java.lang.Object getAttribute(java.langString name)
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
125
LISTING 7.10 Continued
![Page 145: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/145.jpg)
It takes a string that represents the key that was used to add the object in the setAttribute()
method, and returns a reference to an object. You must downcast the object back to aConnectionPool because when it was stored in the ServletContext, it was stored as an object.
The destroy() method then empties the ConnectionPool and removes the attribute from theServletContext using the removeAttribute() method. The destroy() method is listed in thefollowing:
public void destroy() {
// Access the ServletContext using the getAttribute()// method, which returns a reference to the ConnectionPool.ServletContext context = getServletContext();ConnectionPool pool =(ConnectionPool)context.getAttribute(“CONNECTION_POOL”);
if ( pool != null ) {
// empty the poolpool.emptyPool();// Remove the Attribute from the ServletContextcontext.removeAttribute(“CONNECTION_POOL”);
}else {
System.err.println(“Could not get a reference to Pool!”);}
}
Servlet Fundamentals
PART I126
You might want to set up the ConnectionPoolServlet as a preloaded servlet. This willmake sure that the connections are already available before the first request is made.You can do this by including the following lines in your web.xml file:
<servlet><servlet-name>ConnectionPool.ConnectionPoolServlet</servlet-name><servlet-class>ConnectionPool.ConnectionPoolServlet</servlet-class><load-on-startup>1</load-on-startup>
</servlet>
NOTE
![Page 146: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/146.jpg)
Now that you have created and understand the ConnectionPoolServlet, you can put it to usewith another example. This example is based on your TitleListServlet, except that you willdo a generic query with no request parameters. There are two important changes to this servlet.The first is how it gets a connection and the second is how it releases that connection.
The TitleListGlobalPooledServlet gets a Connection object by calling theServletContext.getAttribute() method, passing it the key “CONNECTION_POOL”, whichreturns a reference to the ConnectionPool object. It can then call theConnectionPool.getConnection() method to get a JDBC connection:
// Get a reference to the ConnectionPool from the Global// ServletContextpool =(ConnectionPool)getServletContext().getAttribute(“CONNECTION_POOL”);
// Get a connection from the ConnectionPoolcon = pool.getConnection();
When the servlet finishes with the connection, it must release it. This is done by calling theConnectionPool’s releaseConnection() method:
// Release the connectionpool.releaseConnection(con);
That is all there is to it. After you are finished with the ConnectionPool, it still resides in theServletContext waiting on future requests. You’ll find the entire source for theTitleListGlobalPooledServlet in Listing 7.11.
LISTING 7.11 TitleListGlobalPooledServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.sql.*;
import ConnectionPool.*;
public class TitleListGlobalPooledServlet extends HttpServlet {
public void init(ServletConfig config)throws ServletException {
super.init(config);}
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
127
![Page 147: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/147.jpg)
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
// If we get a GET request, pass the request/response to// the doPost() methoddoPost(request, response);
}
//Process the HTTP Post requestpublic void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType(“text/html”);PrintWriter out = response.getWriter();
out.println(“<html>\n<body>\n<table border=\”1\” width=\”100%\”>”);
Connection con = null;ConnectionPool pool = null;
try {
// Get a reference to the ConnectionPool from the Global// ServletContextpool =(ConnectionPool)getServletContext().getAttribute(“CONNECTION_POOL”);
// Get a connection from the ConnectionPoolcon = pool.getConnection();
if ( con != null ) {
// Create the statementStatement statement = con.createStatement();
// Use the created statement to SELECT the DATA// FROM the Titles Table.ResultSet rs = statement.executeQuery(“SELECT * “ +“FROM Titles”);
Servlet Fundamentals
PART I128
LISTING 7.11 Continued
![Page 148: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/148.jpg)
// Iterate over the ResultSetwhile ( rs.next() ) {
out.println(“<tr>”);
// get the id, which is an intout.println(“<td>” + rs.getInt(“title_id”) + “</td>”);
// get the name, which is a Stringout.println(“<td>” + rs.getString(“title_name”) + “</td>”);
// get the rating, which is a Stringout.println(“<td>” + rs.getString(“rating”) + “</td>”);
// get the price, which is a Floatout.println(“<td>” + rs.getFloat(“price”) + “</td>”);
// get the Quantity, which is a Integerout.println(“<td>” + rs.getInt(“quantity”) + “</td>”);
// get the Type, which is a Integerout.println(“<td>” + rs.getInt(“type_id”) + “</td>”);
// get the Category, which is a Integerout.println(“<td>” + rs.getInt(“category_id”) + “</td>”);
out.println(“</tr>”);}// Close the ResultSetrs.close();out.println(“</table>”);
}}catch (SQLException sqle) {
System.err.println(sqle.getMessage());}catch (Exception e) {
System.err.println(e.getMessage());}finally {
// Release the connection
Servlets, JDBC, and Inter-Servlet Communications
CHAPTER 7
7
SER
VLETS, JD
BC
,&
INTER-S
ERV
LETC
OM
MU
NIC
ATIO
NS
129
LISTING 7.11 Continued
![Page 149: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/149.jpg)
pool.releaseConnection(con);}out.println(“</body></html>”);out.close();
}
//Get Servlet informationpublic String getServletInfo() {
return “TitleListGlobalPooledServlet Information”;}
}
To see how your new servlet works, load the following URL into your browser:
http://yourserver/djs/servlet/TitleListGlobalPooledServlet
SummaryThis chapter covered the basics of the JDBC. I discussed setting up the JDBC-ODBC Bridgeand how to load JDBC drivers. You took a look at the most common SQL statements and howto execute them using the JDBC. You then merged the JDBC with the servlets and performedsome basic queries.
Finally, you looked at some ways to optimize the use of JDBC in servlets. You did this byusing a connection pool and inter-servlet communications.
At this point, you should be able to create your own servlet that can access a database usingeither a straight JDBC connection or a connection pool. You should understand how to createand execute basic SQL statements. You should also understand and be able to use theServletContext for inter-servlet communications.
In the next chapter we will take a look at JavaMail and how we can incorporate JavaMail intoservlets.
Servlet Fundamentals
PART I130
LISTING 7.11 Continued
![Page 150: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/150.jpg)
CHAPTER
8Servlets and JavaMail
IN THIS CHAPTER• JavaMail and Internet E-mail 132
• Preparing to Use JavaMail 133
• A JavaMail Example 133
• Using JavaMail in a Servlet 137
![Page 151: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/151.jpg)
Servlet Fundamentals
PART I132
JavaMail and Internet E-mailTraditionally when you needed to interact with a mail server from within code, you encoun-tered a messy collection of socket code containing a lot of string parsing. The code would haveto send a request to the server, wait for the response, and then break down the response toparse the necessary information. The JavaMail API has provided a clean and easy-to-use Javainterface to design and implement messaging and Internet e-mail solutions.
Internet e-mail is comprised of several standards detailing the format and makeup of a messagethat is to be sent across the Internet. Standards, as well as some proposed standards, dictatehow Internet e-mail services handle the messages.
JavaMail ServicesThe two types of services that JavaMail offers are the transport and store services. The trans-port service has several jobs, but we will simply think of it as the service that takes our mes-sage and sends it to the recipient. The message can make several stops along the way, but theintricacies of these stops are not within the scope of this book.
The second type of service that a JavaMail system deals with is the store service. The storemanipulates the persistent storage of messages. The storage of messages is done in what mostof us know as mailboxes: for example, your inbox. JavaMail refers to these mailboxes as fold-ers because it is possible for one folder to contain other folders, messages, or both. The physi-cal structure of the folders on a mail server depends on the mail server used to create andmanage them. So, to put it simply, a store service allows you to read and manipulate your fold-ers and messages.
Store and transport are generic terms used by the JavaMail API to refer to the protocols thatactually implement these services. In the case of Internet e-mail, the most widely used trans-port protocol is the Simple Mail Transfer Protocol (SMTP). The most widely used protocolsthat implement the store service are the Post Office Protocol (POP3) and Internet MessageAccess Protocol (IMAP4).
JavaMail provides you with an interface to a messaging system. For it to be useful, you alsorequire service providers that implement the JavaMail API. Packaged with the JavaMail API,Sun Microsystems supplies you with both an SMTP and an IMAP service provider. A POPprovider can be downloaded through Sun. These providers are the companies’ implementationsof the JavaMail API, designed to interact with each of the different protocols.
![Page 152: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/152.jpg)
Preparing to Use JavaMailBefore you get started using JavaMail, you probably want to know what you will need to usethe JavaMail API, and where to locate it. The JavaMail API can be downloaded from
http://www.javasoft.com/products/javamail/index.html
The archive you will get contains the JavaMail API jar file, all of the javadoc files, theJavaMail Specification in PDF format, the guide for service providers in PDF format, and adecent collection of demo code with documentation.
JavaMail makes extensive use of the JavaBeans Activation Framework (JAF), so you will alsoneed to download this Java extension. It can be found at
http://www.javasoft.com/beans/glasgow/jaf.html
This archive contains a collection of files similar to the JavaMail archive. The two importantfiles you will need are mail.jar and activation.jar. Both of these archives must be addedto your classpath before you can begin working with JavaMail.
A JavaMail ExampleLet’s walk through a simple example of sending a message using JavaMail.
Servlets and JavaMail
CHAPTER 8
8
SER
VLETS
AN
DJA
VAM
AIL
133
Anyone can write his own implementation of the JavaMail API, to interact with theseor other protocols. The document titled “The JavaMail Guide for Service Providers” ispackaged with the JavaMail archive and specifies how to develop and package a ser-vice provider.
NOTE
The JavaMail API provides an interface to perform many more complex tasks, includ-ing sending MIME-encoded attachments with your mail. And, as we discussed earlier,you can retrieve and manipulate messages from your mailboxes. The demo code thataccompanies JavaMail gives good examples of some of the other features that youcan use. With a little creativity, you are not limited in what you can accomplish.
NOTE
![Page 153: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/153.jpg)
Listing 8.1 contains the JavaMail example.
LISTING 8.1 SimpleSendMessage.java
import java.util.*;
import javax.mail.*;import javax.mail.internet.*;import javax.activation.*;
public class SimpleSendMessage {
public static void main(String[] args) {
// Collect the necessary information to send a simple message// Make sure to replace the values for host, to, and from with// valid information.// host - must be a valid smtp server that you currently have// access to.// to - whoever is going to get your email// from - whoever you want to be. Just remember that many smtp// servers will validate the domain of the from address// before allowing the mail to be sent.String host = “server.myhost.com”;String to = “[email protected]”;String from = “[email protected]”;String subject = “JavaMail Rules!”;String messageText = “I am sending a message using the”+ “ JavaMail API.\n”
+ “I can include any text that I want.”;boolean sessionDebug = false;
// Create some properties and get the default Session.Properties props = System.getProperties();props.put(“mail.host”, host);props.put(“mail.transport.protocol”, “smtp”);
Session session = Session.getDefaultInstance(props, null);
// Set debug on the Session so we can see what is going on// Passing false will not echo debug info, and passing true// will.session.setDebug(sessionDebug);
try {
Servlet Fundamentals
PART I134
![Page 154: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/154.jpg)
// Instantiate a new MimeMessage and fill it with the// required information.Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));InternetAddress[] address = {new InternetAddress(to)};msg.setRecipients(Message.RecipientType.TO, address);msg.setSubject(subject);msg.setSentDate(new Date());msg.setText(messageText);
// Hand the message to the default transport service// for delivery.Transport.send(msg);
}catch (MessagingException mex) {
mex.printStackTrace();}
}}
In analyzing Listing 8.1, the first topic we must discuss is the Session class. The Session rep-resents a mail session and is typically the first thing that you will set up in code using theJavaMail API. It collects properties and defaults that will be used by different pieces through-out the API.
In the following code snippet, you retrieve the system properties, add the JavaMail-specificinformation to them, and retrieve a default session using them. The properties you use here arejust some of the JavaMail-specific attributes that can be used; however, they are the only onesnecessary to accomplish sending a simple message:
String host = “server.myhost.com”;String to = “[email protected]”;String from = “[email protected]”;String subject = “JavaMail Rules!”;String messageText = “I am sending a message using the”+ “ JavaMail API.\nI can include any text that I want.”;boolean sessionDebug = false;
// Create some properties and get the default Session.Properties props = System.getProperties();
Servlets and JavaMail
CHAPTER 8
8
SER
VLETS
AN
DJA
VAM
AIL
135
LISTING 8.1 Continued
![Page 155: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/155.jpg)
props.put(“mail.host”, host);props.put(“mail.transport.protocol”, “smtp”);
Session session = Session.getDefaultInstance(props, null);
The mail.host environment property specifies the default mail server. In many cases theservers for transport and store are the same machine. However, they can be specified separatelyif this is not the case. For our purposes it does not matter, because you will only need access tothe transport service.
Servlet Fundamentals
PART I136
You will need to change the mail host in the application to use your ISP’s mail host.
NOTE
Using the mail.transport.protocol property tells the Session what protocol to use as thedefault transport provider. You specified smtp as the default transport, so the Session nowknows that whenever you use a transport, this is the service provider you want. This becomesimportant later when you actually send the message, because you use a static method in theTransport class to send, and you never specify what type of transport you want to use.
In the next code snippet, you create a message and prepare it to be shipped. There is quite a bitmore that can take place before a message is sent, but in this case we are only interested in thebare necessities:
String to = “[email protected]”;String from = “[email protected]”;String subject = “JavaMail Rules!”;String messageText =“I am sending a message using the JavaMail API.\n”+ “I can include any text that I want.”;
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));InternetAddress[] address = {new InternetAddress(to)};msg.setRecipients(Message.RecipientType.TO, address);msg.setSubject(subject);msg.setSentDate(new Date());msg.setText(messageText);
The first thing you might notice is the use of the MimeMessage class. It implements theMessage abstract class, and uses certain criteria to make sure the message adheres to theInternet e-mail standards. It formats the message and message headers in the proper MIME
![Page 156: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/156.jpg)
style to be sent over the Internet. (A discussion of the MIME Standard is beyond the scope ofthis book.)
The next several method calls fill the message with the needed information. Addresses used bya MimeMessage are implemented by the InternetAddress class. You will notice that this classis used for both the sender and recipients. Neither the subject nor the content of the message isrequired to successfully transport the message, but let’s face it, how exciting would it be with-out them?
Now that the Message is ready to be sent, all you have to do is ask your default transportprovider to send it for you. The code snippet to accomplish this is simple and looks like this:
Transport.send(msg);
That is all there is to sending a simple e-mail using the JavaMail API.
Using JavaMail in a ServletNext, let’s look at what is necessary to send an e-mail using JavaMail and servlets. For theservlet example, you’ll use an HTML form to submit the mail message and a servlet to parseand send the submitted message. The HTML form can be found in Listing 8.2.
LISTING 8.2 MailForm.html
<html><head><title>JavaMail Form</title>
</head>
<body><form action=”http://localhost/djs/servlet/MailServlet” method=”post”><table cellspacing=”2” cellpadding=”2” border=”1”><tr><td>To:</td><td><input type=”text” name=”to” size=”30” maxlength=”30”>
</td></tr><tr><td>From:</td><td><input type=”text” name=”from” size=”30” maxlength=”30”>
</td></tr><tr>
Servlets and JavaMail
CHAPTER 8
8
SER
VLETS
AN
DJA
VAM
AIL
137
![Page 157: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/157.jpg)
<td>Subject</td><td><input type=”text” name=”subject” size=”30” maxlength=”30”>
</td></tr><tr><td colspan=”2”><textarea cols=”40” rows=”10” name=”body”></textarea>
</td></tr><tr><td><input type=”submit” name=”submit” value=”Submit”><input type=”Reset”>
</td></tr>
</table></form>
</body></html>
You can see that there is nothing special about this form. You should only notice that the actionattribute of the form points to your servlet, found in Listing 8.3.
LISTING 8.3 MailServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*;
public class MailServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {super.init(config);
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
Servlet Fundamentals
PART I138
LISTING 8.2 Continued
![Page 158: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/158.jpg)
throws ServletException, IOException {
doPost(request, response);}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
// Create some properties and get the default Session.String host = “YOURMAILHOST”;String to = request.getParameter(“to”);String from = request.getParameter(“from”);String subject = request.getParameter(“subject”);String messageText = request.getParameter(“body”);boolean sessionDebug = false;
response.setContentType(“text/html”);PrintWriter out = response.getWriter();
out.println(“<html>”);out.println(“<head><title>MailServlet</title></head>”);
Properties props = System.getProperties();props.put(“mail.host”, host);props.put(“mail.transport.protocol”, “smtp”);
Session mailSession = Session.getDefaultInstance(props, null);
// Set debug on the Session so we can see what is going on// Passing false will not echo debug info, and passing true// will.mailSession.setDebug(sessionDebug);
// Instantiate a new MimeMessage and fill it with the// required information.Message msg = new MimeMessage(mailSession);
try {
msg.setFrom(new InternetAddress(from));InternetAddress[] address = {new InternetAddress(to)};msg.setRecipients(Message.RecipientType.TO, address);msg.setSubject(subject);
Servlets and JavaMail
CHAPTER 8
8
SER
VLETS
AN
DJA
VAM
AIL
139
LISTING 8.3 Continued
![Page 159: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/159.jpg)
msg.setSentDate(new Date());msg.setText(messageText);
// Hand the message to the default transport service// for delivery.Transport.send(msg);
out.println(“<body>”);
out.println(“Mail was sent to “ + to);out.println(“ from “ + from);out.println(“ using host “ + host + “.”);
out.println(“</body></html>”);}catch (MessagingException mex) {
mex.printStackTrace();}finally {
out.close();}
}}
As you look over the MailServlet, you will notice only a few differences from the JavaMailapplication in Listing 8.1. The first change is the addition of the code to get the necessaryrequest parameters, which is included in the following snippet:
String to = request.getParameter(“to”);String from = request.getParameter(“from”);String subject = request.getParameter(“subject”);String messageText = request.getParameter(“body”);
The only other notable change is that, instead of referring to the Session with the variablename session, we have changed the variable name to mailSession.
To see this example in action, copy the HTML file and the MailServlet into your<SERVER_ROOT>/djs/ Web application and load the following URL into your browser:
http://localhost/djs/MailForm.html
You should see a page similar to Figure 8.1.
Servlet Fundamentals
PART I140
LISTING 8.3 Continued
![Page 160: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/160.jpg)
FIGURE 8.1Output of the MailForm.html.
Servlets and JavaMail
CHAPTER 8
8
SER
VLETS
AN
DJA
VAM
AIL
141
You will need to change the mail host in the servlet to use your ISP’s mail host.
NOTE
Now fill in the appropriate form data and click the Submit button. You should see a responsethat tells you who received the mail, who sent the mail, and the mail host. To test the example,it is probably best to send mail to yourself, so you can check the message.
SummaryIn this chapter, we covered what JavaMail is and how you can use it. We also looked at howyou can use JavaMail with servlets.
In the next chapter we are going to take a look at servlet security.
![Page 161: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/161.jpg)
![Page 162: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/162.jpg)
CHAPTER
9Servlet Security
IN THIS CHAPTER• Introduction to Security 144
• Roll Your Own 144
• Basic Authentication 148
• Digest Authentication 148
• Secure Sockets Layer (SSL) 149
![Page 163: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/163.jpg)
Servlet Fundamentals
PART I144
Introduction to SecurityThe need for security has increased as the Internet’s traffic has increased. Every day more peo-ple are transferring their credit card numbers or other confidential information over theInternet. If these transfers are not secured, they are exposed to just about any evildoer with anetwork connection. In this chapter, we will cover some of the more common security methodsfrom rolling your own to Secure Sockets Layer (SSL).
One of the key benefits of servlets is that they inherit the security of the server, without anyadditional effort on your part. They are protected because they are resources of the server.
Roll Your OwnThe first security method we will discuss is probably the worst method, but at the same timeprobably safe enough if you are protecting non-vital information.
In your homegrown version of security, you are going to use a basic form to query the user foran ID and password. When you have the request, parse off the ID/password combination anddo a lookup to make sure that the user is approved for access. When you have approval, addthe ID to the user’s HttpSession object as proof of approval for future transactions. Listing 9.1contains the servlet code for this example.
LISTING 9.1 RollYourOwnSecurityServlet
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
public class RollYourOwnSecurityServlet extends HttpServlet {
public void init(ServletConfig config)throws ServletException {
super.init(config);}
private boolean validateUser(String id, String password) {
// This is a dummy method. If you really implement// a method like this, you will need to store id/password// combinations somewhere else and they should also be// encrypted.return true;
![Page 164: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/164.jpg)
}
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
// Get the current sessionHttpSession session = request.getSession(true);// Get the id stored in the session after approvalString id = (String)session.getAttribute(“id”);
response.setContentType(“text/html”);PrintWriter out = response.getWriter();out.println(“<html>”);out.println(“<head><title>Roll Your Own</title></head>”);out.println(“<body>”);
out.println(“Hello “ + id + “ how can we help you today?”);
out.println(“</body></html>”);out.close();
}
//Process the HTTP Post requestpublic void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
// Get the id/password combination from the requestString id = request.getParameter(“id”);String password = request.getParameter(“password”);
HttpSession session = null;
// Check to see if this is a valid id/password combination.boolean valid = validateUser(id, password);
// If it is valid, get the session// and add the id for future transactionsif ( valid == true ) {
session = request.getSession(true);session.setAttribute(“id”, id);
Servlet Security
CHAPTER 9
9
SER
VLET
SEC
UR
ITY145
LISTING 9.1 Continued
![Page 165: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/165.jpg)
}
response.setContentType(“text/html”);PrintWriter out = response.getWriter();out.println(“<html>”);out.println(“<head><title>Roll Your Own</title></head>”);out.println(“<body>”);
if ( valid == true ) {
// Successful validation, redirect to the GET method// of this servletresponse.sendRedirect(“/djs/servlet/” +“RollYourOwnSecurityServlet”);
}else {
out.println(“We don’t know who you are please leave!”);}out.println(“</body></html>”);out.close();
}
//Get Servlet informationpublic String getServletInfo() {
return “RollYourOwnSecurityServlet Information”;}
}
This is a simple example of implementing your own security model. The first step is to displaythe login form when the user accesses the Web site. The HTML source for the login screen isin Listing 9.2.
LISTING 9.2 LoginScreen.html
<HTML><HEAD><TITLE>Login Screen</TITLE></HEAD>
Servlet Fundamentals
PART I146
LISTING 9.1 Continued
![Page 166: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/166.jpg)
<BODY>
<CENTER><H2>Please Login</H2></CENTER>
<FORM ACTION=”http://localhost/djs/servlet/RollYourOwnSecurityServlet” ➥METHOD=”POST”>
User Id:<input type=”Text” name=”id” ><BR>Password:<input type=”Password” name=”password”><BR><input type=”Submit” name=”login” value=”Login”>
</FORM>
</BODY></HTML>
Load the HTML file into your browser. You should see a screen similar to Figure 9.1.
Servlet Security
CHAPTER 9
9
SER
VLET
SEC
UR
ITY147
LISTING 9.2 Continued
FIGURE 9.1The login screen.
![Page 167: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/167.jpg)
When the user submits her ID/password, it is parsed by the doPost() method of the servlet andchecked against a database of valid users (in the example, everybody is approved). When theuser is validated, her ID is added to her HttpSession object and she is redirected to theservlet’s doGet() method. Now future requests only need to check for the user’s ID in the ses-sion to verify that she has been properly validated.
Basic AuthenticationBasic authentication is a challenge/response security model. It is based on the fact that theclient must authenticate itself with a user ID/password combination for each resource it wantsto access. A protected resource could be a directory, a servlet, or even a specific page. Thesteps involved in authenticating a client are as follows:
1. The client makes an unauthorized request for a protected resource.
2. The server responds with a challenge to authenticate.
3. The client sends a username/password combination (separated by a colon) within abase64-encoded string.
4. The server decodes the string containing the user ID/password combination and looks inits database for a match.
5. If the server finds a match, it grants access to the requested resource.
When you deploy your applications to a commercial level server you will need to consult theserver documentation to configure protected resources and users.
Digest AuthenticationDigest authentication, like basic authentication, is based on the challenge/response model. Infact, digest authentication was created as a direct result of basic authentication’s shortcomings.The main difference between basic and digest authentication is that the digest scheme neversends the user’s password across the network. It instead sends a digest representation of thepassword.
Servlet Fundamentals
PART I148
Currently there is no support for digest authentication.
NOTE
![Page 168: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/168.jpg)
Two steps are involved in creating a digest value. The first is to apply a mathematical formulato the ID/password combination. The second is to permute the mathematical calculation with anonce. This makes each request more secure because the digest is unique to each request.
Servlet Security
CHAPTER 9
9
SER
VLET
SEC
UR
ITY149
A nonce is a server-specific data string that is uniquely generated each time a pro-tected resource is requested.
NOTE
Secure Sockets Layer (SSL)The Secure Sockets Layer (SSL) is an authentication protocol used to send encrypted informa-tion over the Internet. It was originally developed by Netscape to transfer secure informationbetween its Web browser and Web server products. Since then, it has been widely adopted andis now one of the most popular methods for sending encrypted information over the Internet.SSL is implemented as a layer between the TCP/IP protocol and the application layer.
The following steps are involved in sending secure messages using the SSL protocol:
1. A client makes a request for a resource located on a secure site.
2. The server signs its public key with its private key and sends the public key back to theclient.
3. The client takes the returned public key and makes sure the appropriate owner signed it.
4. The client verifies that the key was signed by an approved certificate authority.
5. The client creates a key that is encrypted with the public key of the server and sends thenewly constructed key back to the server.
6. The server optionally compresses the information requested by the client.
7. The server encrypts the message using the key created in step 5.
8. The server transmits the message to the client.
9. The client receives the message.
10. The message is decrypted using the same key created in step 5.
11. The message is decompressed if necessary and delivered to the client.
12. All further requests restart at step 6, using the same public key.
The first 5 steps make the SSL protocol a very secure way to send information across theInternet. The only real drawback of the SSL protocol is the performance degradation taken dur-ing the public key encryption and decryption required during these first five steps.
![Page 169: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/169.jpg)
The SSL protocol is very involved and is beyond the scope of this book. If you have furtherinterest, I suggest getting the latest specification from the Netscape Web site athttp://www.netscape.com/eng/ssl3/3-SPEC.HTM#7-1.
SummaryIn this chapter, we briefly discussed some of the more common security protocols. You sawhow you can roll your own security, a technique that really isn’t secure. We covered basic anddigest authentication and their problems. Finally, we discussed the Secure Sockets Layer proto-col, which is a very secure and widely used protocol.
In the next chapter, you will learn about the basics of XML and servlets.
Servlet Fundamentals
PART I150
![Page 170: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/170.jpg)
CHAPTER
10Servlets and XML
IN THIS CHAPTER• XML and Java 153
• Using XML in a Servlet 159
![Page 171: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/171.jpg)
The Extensible Markup Language, or XML, is a metalanguage for creating markup languagesused to describe structured data. XML is a self-describing language, composed of tags and val-ues. It is often used to describe objects that are passed in messages between applications. Anexample of a simple XML document is included in Listing 10.1.
LISTING 10.1 item.xml
<?xml version=”1.0”?>
<ITEM><ID>33445</ID><DESCRIPTION> Austin Powers: International Man of Mystery</DESCRIPTION><PRICE>19.95</PRICE><QUANTITY>56</QUANTITY>
</ITEM>
The first line of this snippet describes a processing instruction that states that this XML docu-ment is based on version 1 of the XML specification. Processing instructions begin with a less-than sign and a question mark (<?) and end with a question mark and a greater than sign (?>).
The rest of this document describes an ITEM object with four attributes: ID, DESCRIPTION,PRICE, and QUANTITY. Each of these attributes is contained in an open <TAG> and closed </TAG>pair. You should notice how the hierarchy of the object is described in a container-like fashion,wherein the attributes of the ITEM are between the ITEM’s open and closing tags. This shows theparent/child relationship of the ITEM object. All XML documents can be viewed as navigabletree structures. Figure 10.1 shows the standard structure of an XML document.
Servlet Fundamentals
PART I152
Document Root
ITEM
ID
DESCRIPTION
PRICE
QUANTITY
FIGURE 10.1The XML document tree structure.
![Page 172: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/172.jpg)
Although this is hardly a complete definition of XML, which is well beyond the scope of thisbook, it is complete enough for us to see in this chapter how XML and servlets can be usedtogether.
XML and JavaNow that you understand XML basics, let’s take a look at how we can use XML and Javatogether. Many Java parsers have been developed to interact with XML documents. The threemost common have been developed by Sun Microsystems, IBM, and Microsoft. For our exam-ple, you will use Sun’s Java API for XML Processing (JAXP), which can be downloaded fromthe following URL:
http://java.sun.com/xml/download.html
Follow the installation instructions for your platform, including adding the jaxp.jar and theparser.jar files to your classpath.
Sun’s API is composed of two core components, the Document Object Model (DOM) and theSimple API for XML (SAX API). The DOM is a tree-based API, and the SAX is an event-based API. For our examples, you will use the SAX API.
Using the SAX APIAs we stated earlier, the SAX API is an event-based API. This means that, as the parser parsesthe XML document, it triggers certain events based upon encountered elements of the docu-ment. To see exactly how this works, let’s take a look at Listing 10.2.
LISTING 10.2 XMLTest.java
import java.io.*;import java.util.Hashtable;import java.util.Enumeration;
import org.w3c.dom.*;import org.xml.sax.*;import javax.xml.parsers.SAXParserFactory;import javax.xml.parsers.SAXParser;
public class XMLTest {
public static void main (String argv []) throws IOException {
// Check for the appropriate usageif ( argv.length != 1 ) {
Servlets and XML
CHAPTER 10
10
SER
VLETS
AN
DX
ML
153
![Page 173: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/173.jpg)
System.err.println (“USAGE: java XMLTest filename”);System.exit(1);
}
try {
// Get the path to the fileString xmlResource = “file:” +new File(argv[0]).getAbsolutePath();
Parser parser;// Get an instance of the SAXParserFactorySAXParserFactory spf = SAXParserFactory.newInstance();// Get a SAXParser instance from the factorySAXParser sp = spf.newSAXParser();
// Create an instance of our HandlerBaseSAXHandler handler = new SAXHandler();
// Set the Document handler to call our SAXHandler when// SAX event occurs while parsing our XMLResourcesp.parse(xmlResource, handler);// After the resource has been parsed get the resulting tableHashtable cfgTable = handler.getTable();
// Print the config settings that we are interested in.System.out.println(“ID == “ +(String)cfgTable.get(new String(“ID”)));
System.out.println(“DESCRIPTION == “ +(String)cfgTable.get(new String(“DESCRIPTION”)));
System.out.println(“PRICE == “ +(String)cfgTable.get(new String(“PRICE”)));
System.out.println(“QUANTITY == “ +(String)cfgTable.get(new String(“QUANTITY”)));
}catch (Exception e) {
e.printStackTrace();}System.exit(0);
}}
Servlet Fundamentals
PART I154
LISTING 10.2 Continued
![Page 174: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/174.jpg)
As you look over this document, you can see that its main function is to take an XML filefrom the command line, parse it, and print out the elements that you are looking for. The firstthing you should notice is the following section:
Parser parser;// Get an instance of the SAXParserFactorySAXParserFactory spf = SAXParserFactory.newInstance();// Get a SAXParser instance from the factorySAXParser sp = spf.newSAXParser();
In this section, you are creating a reference to a parser that will be used to actually parse theXML document. To do this you use the static factory methodSAXParserFactory.newInstance(), which obtains a new instance of a SAXParserFactory.After you have an instance of a SAXParserFactory, you create a new SAXParser, by callingthe SAXParserFactory.newSAXParser() method. The SAXParser defines the API that wrapsan org.xml.sax.Parser implementation class. By using this class, an application can parsecontent using the SAX API.
The next section we need to examine is
// Create an instance of our HandlerBaseSAXHandler handler = new SAXHandler();
This section of code creates an instance of your event handler SAXHandler. To capture eventsinvoked by the parser, you need to either create a class that implements theorg.xml.sax.DocumentHandler interface or extend the class org.xml.sax.HandlerBase,which implements default handlers defined by the DocumentHandler interface. For our exam-ple, you have extended HandlerBase so you only have to implement the methods you are inter-ested in handling. This is much like the event handlers of the AWT.
After you have an instance of your event handler, you can start the parser. The snippet for thisis
// Set the Document handler to call our SAXHandler when// SAX event occurs while parsing our XMLResourcesp.parse(xmlResource, handler);
The SAXParser.parse() method takes an InputSource that contains an XML stream and areference to your handler. As the parser parses your XML document, it will trigger events thatwill be handled by your SAXHandler, which can be found in Listing 10.3.
LISTING 10.3 SAXHandler.java
import java.io.*;import java.util.Hashtable;
Servlets and XML
CHAPTER 10
10
SER
VLETS
AN
DX
ML
155
![Page 175: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/175.jpg)
import org.xml.sax.*;
public class SAXHandler extends HandlerBase {
private Hashtable table = new Hashtable();private String currentElement = null;private String currentValue = null;
// Simple Accessor for the Hashtable of parsed valuespublic void setTable(Hashtable table) {
this.table = table;}
// Simple Accessor for the Hashtable of parsed valuespublic Hashtable getTable() {
return table;}
// Called when a new element is encounteredpublic void startElement(String tag, AttributeList attrs)throws SAXException {
// hold onto the new element tag, that will be placed in// our Hashtable when matching character data is encountered.currentElement = tag;
}
// Called when character data is found inside an elementpublic void characters(char[] ch, int start, int length)throws SAXException {
// create a String containing the characters// found in the elementcurrentValue = new String(ch, start, length);
}
// Called when the end of element is encounteredpublic void endElement(String name) throws SAXException {
// Make sure we have a matching closing elementif ( currentElement.equals(name) ) {
Servlet Fundamentals
PART I156
LISTING 10.3 Continued
![Page 176: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/176.jpg)
// Put the element/value pair into the Hashtabletable.put(currentElement, currentValue);
}}
}
As you look over this handler, you will notice that there are only five methods, two of whichare only accessors to a Hashtable. The other three methods represent the events you are inter-ested in responding to. Each of these methods will be discussed in the following sections. Thefirst method overridden is startElement(), which is shown here:
// Called when a new element is encounteredpublic void startElement(String tag, AttributeList attrs)throws SAXException {
// hold onto the new element tag, that will be placed in// our Hashtable when matching character data is encountered.currentElement = tag;
}
This method is called whenever the parser encounters a new element in the XML document. Anew element would be a starting tag similar to <ID>. When your overridden method is called,you simply hold onto the passed-in tag representing the element name.
The next method you override is the characters() method. The overridden method is shownhere:
// Called when character data is found inside an elementpublic void characters(char[] ch, int start, int length)throws SAXException {
// create a String containing the characters// found in the elementcurrentValue = new String(ch, start, length);
}
This method is invoked when the parser encounters character data inside an element. An exam-ple of this would be the value 33445 found in the element <ID>33445</ID>. When your over-ridden method is called, you create a string from the character array and hold onto the stringfor later use.
The last method you override from the HandlerBase class is the endElement() method, whichis included in the following code snippet:
Servlets and XML
CHAPTER 10
10
SER
VLETS
AN
DX
ML
157
LISTING 10.3 Continued
![Page 177: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/177.jpg)
// Called when the end of element is encounteredpublic void endElement(String name) throws SAXException {
// Make sure we have a matching closing elementif ( currentElement.equals(name) ) {
// Put the element/value pair into the Hashtabletable.put(currentElement, currentValue);
}}
The endElement() method is the final event handler that we are concerned with. It is calledwhenever the end of an element is encountered. If we use the same example from thestartElement() method, then endElement() would be invoked when the </ID> tag wasencountered. The overridden endElement() method takes the passed-in name and compares itwith the current element being processed. If they match, the endElement() method puts theelement and its character data into the Hashtable.
Now that you understand what happens as each event is triggered, we will return to ourXMLTest application. The remainder of our application is listed in the following code snippet:
// After the resource has been parsed get the resulting tableHashtable cfgTable = handler.getTable();
// Print the config settings that we are interested in.System.out.println(“ID == “ +(String)cfgTable.get(new String(“ID”)));System.out.println(“DESCRIPTION == “ +(String)cfgTable.get(new String(“DESCRIPTION”)));System.out.println(“PRICE == “ +(String)cfgTable.get(new String(“PRICE”)));System.out.println(“QUANTITY == “ +(String)cfgTable.get(new String(“QUANTITY”)));
As you can see, after the parser is finished parsing, the application calls your handler’sgetTable() method. This method returns a Hashtable containing the elements and their textdata that was parsed from the XML file.
The final steps you perform are printing the elements you are interested in from the parsed file.To see this in action, compile and build the handler and application and then execute the appli-cation with the XML file we described earlier. Your command line should be similar to the fol-lowing:
java XMLTest item.xml
Servlet Fundamentals
PART I158
![Page 178: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/178.jpg)
The output should look similar to the following:
ID == 33445DESCRIPTION == Austin Powers: International Man of MysteryPRICE == 19.95QUANTITY == 56
Using XML in a ServletNow let’s take the previous example and incorporate it into a servlet. The only difference isthat the XML file that you are parsing has been hard coded into the servlet; therefore, you willneed to replace the <SERVER_ROOT> with the location of your installed Tomcat server. The bet-ter route would be to use an init parameter, but I want to keep the example as simple as possi-ble. Listing 10.4 contains our servlet example.
LISTING 10.4 XMLServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
import java.util.Hashtable;import org.w3c.dom.*;import org.xml.sax.*;import javax.xml.parsers.*;import SAXHandler;
public class XMLServlet extends HttpServlet {
private static final String CONTENT_TYPE = “text/html”;
private String moviefile = “<SERVER_ROOT>\\djs\\item.xml”;
public void init(ServletConfig config)throws ServletException {
super.init(config);}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
doPost(request, response);
Servlets and XML
CHAPTER 10
10
SER
VLETS
AN
DX
ML
159
![Page 179: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/179.jpg)
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();
// Load the movie fileFile file = new File(moviefile);FileReader reader = new FileReader(file);
Parser parser;
out.println(“<html>”);out.println(“<head><title>XMLServlet</title></head>”);out.println(“<body>”);
try {
// Get an instance of the SAXParserFactorySAXParserFactory spf = SAXParserFactory.newInstance();// Get a SAXParser instance from the factorySAXParser sp = spf.newSAXParser();
// Create an instance of our HandlerBaseSAXHandler handler = new SAXHandler();
// Set the Document handler to call our SAXHandler when// SAX event occurs while parsing our XMLResourcesp.parse(new InputSource(reader), handler);// After the resource has been parsed get the resulting tableHashtable cfgTable = handler.getTable();
out.println(“<table align=\”center\” width=\”600\”>”);out.println(“<caption>XML Item</caption>”);
// Print the config settings that we are interested in.out.println(“<tr><td align=\”left\”>ID</td>” +
“<td align=\”center\”>” +(String)cfgTable.get(new String(“ID”)) + “</td></tr>”);
out.println(“<tr><td align=\”left\”>DESCRIPTION</td>” +“<td align=\”center\”>” +
Servlet Fundamentals
PART I160
LISTING 10.4 Continued
![Page 180: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/180.jpg)
(String)cfgTable.get(new String(“DESCRIPTION”)) +“</td></tr>”);
out.println(“<tr><td align=\”left\”>PRICE</td>” +“<td align=\”center\”>” +(String)cfgTable.get(new String(“PRICE”)) +“</td></tr>”);
out.println(“<tr><td align=\”left\”>QUANTITY</td>” +“<td align=\”center\”>” +(String)cfgTable.get(new String(“QUANTITY”)) +“</td></tr>”);
out.println(“</table>”);}catch (SAXException e) {
out.println(“Exception received: “ +e.getMessage() + “<br>”);
}catch (ParserConfigurationException pce) {
out.println(“Exception received: “ +pce.getMessage() + “<br>”);
}out.println(“</body></html>”);
}
public void destroy() {}
}
As you can see, there is really very little difference in the application code and the servletcode. The only noticeable differences are the way you load the XMLResource and the way yououtput the results.
To see this servlet run, you will need to copy the SAXHandler class file to the<SERVER_ROOT>/djs/WEB-INF/classes/ directory, copy the item.xml file to the<SERVER_ROOT>/djs/ directory, and build XMLServlet. Then load the following URL into yourbrowser:
http://yourserver/djs/servlet/XMLServlet
You should see a page similar to Figure 10.2.
Servlets and XML
CHAPTER 10
10
SER
VLETS
AN
DX
ML
161
LISTING 10.4 Continued
![Page 181: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/181.jpg)
FIGURE 10.2Output from XMLServlet.
SummaryThis chapter covered the basics of XML. We covered how to use Sun’s SAX parser, and wealso looked at an example of how you would incorporate XML and servlets.
In the next chapter we will talk about servlets and the Lightweight Directory Access Protocol(LDAP).
Servlet Fundamentals
PART I162
![Page 182: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/182.jpg)
CHAPTER
11Servlets and LDAP
IN THIS CHAPTER• A Brief Discussion of Directories 164
• LDAP 165
• JNDI 166
• Using JNDI to Access LDAP 166
• Accessing LDAP from a Servlet 184
![Page 183: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/183.jpg)
Servlet Fundamentals
PART I164
A Brief Discussion of DirectoriesA directory provides a method of persistence where information can be organized and searchedquickly. This might sound similar to the relational databases that you are used to; however,there are some fundamental differences.
The most noticeable difference is the way the stored information is organized. In a relationaldatabase, information is stored in tables that are interconnected using foreign keys that refer-ence a related table. The structure of the information stored in a directory is quite different.The information is stored in more of a hierarchy that provides a logical relationship betweenthe objects. The informational structure will look something like Figure 11.1.
o = Airius.com
ou = Groups ou = People
cn = Tad Hanssn = HansgivenName = Taduid = thansmail = [email protected] = (123) 432-6581pager = (123) 239-0911
cn = ManagersuniqueMember = uid=thans, ou=People, o=Airius.comdescription = The Bosses
cn = Bob Smithsn = SmithgivenName = Bobuid = bsmithmail = [email protected] = (800) 123-4567
FIGURE 11.1Organization of the data stored in a directory.
The following notes summarize the other differences between a directory and a relational data-base:
• Directories are more suitable for environments where the data is being read quite a bitand is not being modified often.
• Directories generally come with a preexisting schema.
• Directories do not support complex joining during searches like a relational database.
• Directories have better support for substring searches and for searching on similarities.
• Directories are usually quicker and easier to configure and manage than relational data-bases. They are generally less expensive also.
![Page 184: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/184.jpg)
AttributesYou will notice in Figure 11.1 that all of the information is stored in an object based onattribute names. The possible attribute names are based on the object schema. This is similar tocolumn names for a table in a relational database. When using a directory server, there is gen-erally a preexisting schema that will handle your data with little or no change. In many cases,this directory structure and schema is standardized across different directory vendors. This isdifferent from using a database because you are not required to design and define the neces-sary schema.
Each attribute provided for an object in the schema is used for a specific purpose. For example,in Figure 11.1, the attribute cn refers to the common name of the object. You will see thisattribute in many of the objects from all directory providers.
Distinguished NamesAnother important topic to discuss is how to refer to a specific point in the directory structure.Every object or point in the directory structure can be located using its Distinguished Name(DN). The DN is very much like the primary key from a relational database. The DN for anobject is made up of the path through the tree, listing the objects beginning at the root. Forexample, the DN for the Tad Hans object in Figure 11.1 would look like this:
uid=thans, ou=People, o=airius.com
This DN is actually used in the previous example to place Tad in the Managers group. It is alsopossible to have a relative DN, or RDN. Based on the DN above,
uid=thans
is an RDN from
ou=People, o=Airius.com
By prepending the RDN onto the base, you have the full DN for the object. This will becomemore apparent when we begin to do searches and begin each search from a specific base.
One of the first uses for directories was to store phone book information. This scenario is whatthe examples throughout this chapter will display.
LDAPWith an understanding of a directory, it is now time to learn how to access the informationstored within the directory. Each vendor of a directory server will usually provide a proprietaryAPI that can be used to access a directory. They can also provide the capability to access thedirectory server using one or more of several other available protocols.
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
165
![Page 185: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/185.jpg)
Lightweight Directory Access Protocol (LDAP) is a standard protocol that can be used toaccess a directory structure. Currently, it is the most popular protocol available. For this reason,many directory vendors provide access to their server through LDAP.
Any of the LDAP-compliant servers can be accessed using LDAP, and to the client can seem tobe working the same way. This does not mean that they store and handle the information thesame way internally, only that they will return it to the LDAP client in a specific manner.
JNDIThe Java Naming and Directory Interface (JNDI) provides a standard API for interacting withnaming and directory services. JNDI allows a Java client to interact with several differentdirectory protocols using this standard API.
JNDI places another layer of abstraction on top of the directory protocol. This is accomplishedby using the JNDI API with the appropriate service provider plugged in to talk to your direc-tory API. By doing this, the client Java code only needs to be aware of the JNDI API. By plug-ging in different service providers, your client can switch from LDAP to Novell’s NDS, forexample, without changing the client code.
This is a very powerful design pattern that is widely used throughout Java. Another example isJava Database Connectivity (JDBC), which provides a standard API to communicate withmany databases.
It is because of this flexibility, and the fact that JNDI is a standard API, that JNDI is the properchoice for communicating with LDAP servers from within Java code.
Using JNDI to Access LDAPWith a basic understanding of LDAP and JNDI, we can take a look at how to use the twotogether to access information stored in a directory. In this section we will take a look atsearching, adding, modifying, and deleting objects stored in an LDAP server.
You will develop two utility classes that can be used with any LDAP server. The first class willcontain all of the code to perform the LDAP operations. This class will be namedLDAPManager. Sections of this class will be revealed in pieces and explained; the full listing forLDAPManager.java is found later in the chapter in Listing 11.2.
The examples in this chapter were developed using Netscape Directory Server (NDS). To workthrough the examples, you’ll need to download, install, and configure NDS as described in thefollowing section.
Servlet Fundamentals
PART I166
![Page 186: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/186.jpg)
Installing Netscape Directory ServerTo download Netscape, direct your browser to the following:
http://www.iplanet.com
Begin here and work your way to the downloads page. Download the NDS version 4.12 that iscorrect for your platform. The download will give you an executable file that will install theNetscape server.
When you run the installation, first you will accept the licensing agreement. Then select theinstallation of Netscape Servers from the Setup screen.
Accept all of the default options during the installation. There are several screens where youmust enter information about your computer and about how the application should be config-ured.
The first screen where you will need to enter information will appear just as in Figure 11.2.
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
167
FIGURE 11.2Input of computer information.
Three input areas are on this dialog. The first is Server Identifier. Type your computer’s namehere. The second is the port number. Allow this to default to the standard LDAP port of 389.The last is for the Suffix for your server. For all of our examples we have used our company’sname; so type o=virtuas.com.
![Page 187: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/187.jpg)
The next screen will ask you to enter a password to access the admin account of for the AdminServer. Use something you will remember here.
The setup program will then ask you to enter the Administration Domain for your server. Onceagain, type virtuas.com.
At this point you will be asked for a password for the server’s Directory Manager. The screenaccepting this information will look just like Figure 11.3.
Servlet Fundamentals
PART I168
FIGURE 11.3Input of Directory Manager password.
To enable all of the examples developed in this chapter, you must use directory as the pass-word for the Directory Manager. Type this into both text boxes, and click Next.
From here through the completion of installation, accept all of the default values. On the finalscreen, click Finish and you are ready to go.
ConnectingOnly a little information is required to make an initial connection to the LDAP server. Thisconnection comes in the form of the Context class that is part of the JNDI package. All of thenecessary information could be retrieved from a properties file, however for simplicity you willjust provide the information directly in the manager class. In the following code snippet, youcollect the necessary information:
![Page 188: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/188.jpg)
protected String factory = “com.sun.jndi.ldap.LdapCtxFactory”;protected String serverName = “yourServerName”;protected int port = 389;protected String securityAuthentication = “simple”;protected String dirManager = “cn=Directory Manager”;protected String dirManagerPw = “directory”;
All of these attributes have matching accessor methods so their values can be changed howeveryou initialize them with some default values. The factory specifies the LDAP Context factoryclass that you would like to use to bind your Contexts. The serverName is the host machine ofthe LDAP server. The standard port used by an LDAP server is port 389. The other threeattributes deal with authenticating with the LDAP server upon binding. You have the usernameand password to bind with, and the authentication method. The standard setup of a LDAPserver allows anonymous connections. This means that if there is no password specified theserver tries to bind the client anonymously. Most servers will only allow searching anony-mously. To change the data in some way requires a valid username and password. You arehard-coding a username and password into the class as an example, however this would notprovide any security for an actual application.
The following code contains a method to collect all of the information needed for binding:
protected Hashtable getEnvironment() {
Hashtable env = new Hashtable();
// generate LDAP host URLStringBuffer url = new StringBuffer(“ldap://”);url.append(serverName).append(“:”).append(port);
// set Context Factory classenv.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, factory);// set host URLenv.put(javax.naming.Context.PROVIDER_URL, url.toString());
// Only set authentication information if there is a username// presentif ((dirManager != null) && (dirManager.trim().length() > 0)) {
env.put(javax.naming.Context.SECURITY_AUTHENTICATION,securityAuthentication);
env.put(javax.naming.Context.SECURITY_PRINCIPAL, dirManager);env.put(javax.naming.Context.SECURITY_CREDENTIALS, dirManagerPw);
}
return env;}
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
169
![Page 189: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/189.jpg)
To actually bind to the LDAP server you need to create a Context based on these criteria.Because you are dealing with some sort of directory server, more specifically an LDAP server,you use a more specific Context called a DirContext. The DirContext includes some methodsand functionality specifically suited to binding to and manipulating a directory server. Here ishow you create a new Context to bind to your LDAP server:
DirContext ctx = new InitialDirContext(env);
The Hashtable that was generated in the getEnvironment() method is what is passed into theconstructor for the InitialDirContext.
You now have a Context that is properly bound to the LDAP server. It is ready to performmany different functions on the data stored in the server.
Searching the LDAP ServerSearching for information in an LDAP server is probably the most important function becausethis is what LDAP servers are made for—storing a lot of information that is searched often.
To search an LDAP server you need to know where in the directory tree you would like tobegin the search. You need to know how far down the tree you are going to search from there.Finally you need to know the criteria you are searching on.
The search base can be any valid point in the directory tree, and you specify this location usingits DN. You can begin your search at the base of the tree by specifying o=virtuas.com as yoursearch base. You can also begin the search in the People branch by specifyingou=People,o=virtuas.com instead.
From this beginning point, there are three different depths for the search:
• OBJECT_SCOPE—The shallowest search; searches just the named object.
• ONELEVEL_SCOPE—Searches only objects that exist one level directly below the namedpoint in the tree.
• SUBTREE_SCOPE—Searches all objects below the starting point. This is the default thatyou specify in your LDAPManager.
After you have decided how the search will be accomplished, you must specify the criteria youwant to use to select the objects. Naming the criteria is done by using a string to filter theobjects. For example, you could search for all objects where uid=jgoodwill.
The necessary attributes and method used to search your LDAP server look like this:
protected String searchBase = null;protected int searchScope = SearchControls.SUBTREE_SCOPE;
Servlet Fundamentals
PART I170
![Page 190: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/190.jpg)
public Vector search(String[] returnAttributes, String searchFilter)throws NamingException {
Vector ldapObjects = new Vector();SearchControls ctls = new SearchControls();ctls.setReturningAttributes(returnAttributes);ctls.setSearchScope(searchScope);NamingEnumeration results = null;
// bind to the LDAP server.DirContext ctx = getInitialContext(getEnvironment());// perform the search on the LDAP server.results = ctx.search(searchBase, searchFilter, ctls);while ((results != null) && (results.hasMore())) {
// get the next set of results from the search.SearchResult sr = (SearchResult)results.next();// get all of the attributes for this object.Attributes attributes = sr.getAttributes();NamingEnumeration attEnum = attributes.getAll();// create an LDAPObject to hold the results.LDAPObject tmpObj = new LDAPObject();
// set the Distinguished Name for the object. Append// the relative dn and the searcb base together.tmpObj.setDn(sr.getName() + “,” + searchBase);// iterate through the attributes setting them in the LDAPObjectwhile (attEnum.hasMore()) {
// get the next attributeAttribute att = (Attribute)attEnum.next();// set the attribute in the LDAPObjecttmpObj.setAttribute(att.getID(), att.get());
}// add the object to the list of return objectsldapObjects.add(tmpObj);
}
return ldapObjects;}
You have included the search base as an attribute to the class instead of as a parameter for thesearch method. This is because it is common to set the search base and perform severalsearches from there. This eliminates the need to set the search base each time you search.
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
171
![Page 191: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/191.jpg)
The next important piece of information is the search scope. This also is an attribute to theclass, and is defaulted to perform subtree searches.
The search method requires two pieces of information. The first is an array of strings that spec-ify which attributes should be returned from the search. Here you must provide exactly whichattributes should be returned for each object that meets your search criteria. The second para-meter to the search method is the search filter for this particular search.
After you have results from your search, you transfer them into a container object calledLDAPObject. This is not a standard object, just a simple container that makes it easier to returnthe information to the client. The full listing of this class is in Listing 11.1.
LISTING 11.1 LDAPObject.java
import java.util.Hashtable;
public class LDAPObject {
protected String dn = null;protected Hashtable attributes = new Hashtable();
public LDAPObject() {
}
public String getDn() {
return dn;}
public void setDn(String dn) {
this.dn = dn;}
public Object getAttribute(String attName) {
return (String)attributes.get(attName);}
public void setAttribute(String attName, Object attValue) {
attributes.put(attName, attValue);}
}
Servlet Fundamentals
PART I172
![Page 192: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/192.jpg)
Now let’s take a look at the client code that uses this method to search the LDAP server:
LDAPManager lm = new LDAPManager();lm.setSearchBase(“o=virtuas.com”);String[] returnAtts = {“cn”, “sn”, “mail”, “telephoneNumber”};
String searchFilter = “uid=proy”;Vector results = null;
try {
results = lm.search(returnAtts, searchFilter);}catch (NamingException e) {
e.printStackTrace();}
Iterator iter = results.iterator();while (iter.hasNext()) {
LDAPObject lobj = (LDAPObject)iter.next();System.out.println(lobj.getDn());System.out.println(lobj.getAttribute(“cn”));System.out.println(lobj.getAttribute(“sn”));System.out.println(lobj.getAttribute(“mail”));System.out.println(lobj.getAttribute(“telephoneNumber”));
}
This client first creates a new LDAPManager and then sets the appropriate search base. It thendefines the required return attributes and the search filter. After all of this information is inorder, it uses the LDAPManager to perform the search. It can then easily iterate through theresults, using a simple container object, and print out the information.
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
173
Many attributes in an LDAP server can hold multiple values. For example, a personcould have two telephone numbers, both of which are stored in the attributetelephoneNumber. If this is the case, both values are returned as values for the singleAttribute object holding the telephone number.
All of the code written for this chapter allows for only one value for each attribute.This is done for simplicity reasons; however, multiple values are possible.
NOTE
![Page 193: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/193.jpg)
These are the basics of searching an LDAP server. Now we can move on and learn how to useJNDI to manipulate the information that is stored there.
Adding an Object to an LDAP ServerAdding an object to an LDAP server is not difficult, as long as you have a little knowledge ofthe structure of the information in the server.
The first piece of knowledge necessary is the object type. There is a special attribute for everyobject in the LDAP server called objectClass. As we discussed earlier, the directory servercomes with a predefined schema. The schema includes definitions for many objects, includingthe possible attributes available for each object. The existing object definitions can be reusedby other objects, similar to inheritance in Java. The objectClass attribute holds multiple val-ues, specifying which object definitions are used to define the object’s schema. This attribute isrequired when adding an object so that the LDAP server knows what type of object is beingadded.
You also need to know where to place the object into the directory tree. Essentially you aregoing to bind a group of attributes to a new DN in the structure. The simple method used tobind a new object in an LDAP server looks like this:
public void add(String dn, HashMap attributes, String[] objectClass)throws NamingException {
// parse the attributes that were passed inAttributes atts = parseAttributes(attributes);
// add objectClass attribute to the list of attributesAttribute oc = new BasicAttribute(“objectClass”);for (int i = 0; i < objectClass.length; i++) {
oc.add(objectClass[i]);}atts.put(oc);
// perform the addition to the LDAP serverDirContext ctx = getInitialContext(getEnvironment());ctx.bind(dn, null, atts);
}
This method is very simple. As you can see, you accept the object type information as an arrayof strings, and build an Attribute object out of them. All the attribute names and values toplace in the new object are passed to the method using a standard Java collection so that theclient does not need to learn to handle the Attribute and Attributes objects. This collectionis parsed into the required form in another method in the LDAPManager. That method is used inseveral places and appears like this:
Servlet Fundamentals
PART I174
![Page 194: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/194.jpg)
public Attributes parseAttributes(HashMap attributes) {
if (attributes == null) {
return null;}
Attributes newAtts = new BasicAttributes();
// get an iterator for all of the keys in the HashMapIterator attIter = attributes.keySet().iterator();while (attIter.hasNext()) {
// get the value for the key.String attName = (String)attIter.next();Object value = attributes.get(attName);
// create a new AttributeAttribute attribute = new BasicAttribute(attName, value);
// add the attribute to the list of attributesnewAtts.put(attribute);
}
return newAtts;}
Client code can use this method to add objects to any place in the directory tree. Because youare dealing with a phone book, you will be adding the proper information in the Peoplebranch. The client code to do this would look like this:
LDAPManager lm = new LDAPManager();String[] objectClass = {“top”,
“person”,“organizationalPerson”,“inetOrgPerson”};
String dn = “uid=bjones,ou=People,o=virtuas.com”;
HashMap atts = new HashMap();atts.put(“cn”, “Bob Jones”);atts.put(“sn”, “Jones”);atts.put(“givenName”, “Bob”);atts.put(“uid”, “bjones”);atts.put(“mail”, “[email protected]”);atts.put(“telephoneNumber”, “(800) 456-4908”);
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
175
![Page 195: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/195.jpg)
try {
lm.add(dn, atts, objectClass);}catch (NamingException e) {
e.printStackTrace();}
After all of the information has been collected, all you need to do is ask your LDAPManager toadd the object to the server. Here you define the person object by combining the inheritedobjects that include the attributes that you want. These include top, person,organizationalPerson, and inetOrgPerson. To find this information, you have to know a lit-tle about the schema that came with the LDAP server you are using. These object definitionsmake up the standard user object in the Netscape Directory Server.
Removing an ObjectRemoving an object from an LDAP server is very easy. There is little information that is neces-sary. All that is required is the object’s DN. Hand the DN to the Context and ask it to removethe object for you. It is that simple.
The method to perform the deletion from an LDAP server appears in the manager class as fol-lows:
public void remove(String dn) throws NamingException {
// perform the deletion from the LDAP server based on the objects DNDirContext ctx = getInitialContext(getEnvironment());ctx.destroySubcontext(dn);
}
All the client code must do is provide the manager with the object’s DN. The method would beinvoked like this:
LDAPManager lm = new LDAPManager();try {
lm.remove(“uid=bjones,ou=People,o=virtuas.com”);}catch (NamingException e) {
e.printStackTrace();}
That is all there is to removing entire objects from a directory service.
Servlet Fundamentals
PART I176
![Page 196: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/196.jpg)
Modifying Information Stored in LDAPModifying the attributes of an existing object in an LDAP server requires slightly morethought than the rest of the operations. When changing the values for the attributes for anobject, there are three ways in which the modification can be performed.
The three possible modification operations are: ADD, REPLACE, and REMOVE. When theADD_ATTRIBUTE operator is used, any values that are specified for an attribute are added to theexisting values already stored in the LDAP object.
The REPLACE_ATTRIBUTE operator specifies that any values already present for the attributeshould be replaced with the new values. No matter how many values are already assigned tothe attribute in the LDAP server, they will all be removed and replaced with the values that aregiven to the modify method.
Finally, you can remove values and entire attributes from an existing LDAP object by using theREMOVE_ATTRIBUTE operator. When using the REMOVE operator, if a value is specified for theattribute that is passed into the modify method, only those given values will be removed fromthe LDAP object. On the other hand if no value is given for the attribute in conjunction with aREMOVE operator, all values will be removed from the attribute.
Now let’s take a look at the method in the LDAPManager that modifies an existing LDAP object.Here is what it looks like:
public void modify(String dn, HashMap attributes, int modOp)throws NamingException {
// perform the modification on all of the given attributes// based on the modOp that was passed inDirContext ctx = getInitialContext(getEnvironment());ctx.modifyAttributes(dn, modOp, parseAttributes(attributes));
}
There is not a lot to this method. The DN for the object that you are modifying must be presentso the LDAP server knows where to make the changes. The modify operation that we dis-cussed earlier is specified so the LDAP server knows how to make the changes. The attributesto be modified must be given so that the LDAP server knows what changes to make. Noticethat you use the parseAttributes() method, defined earlier, to build the list of attributes froma Java HashMap.
Here is an example of how you might use this method to change the value for someone’s e-mail address
LDAPManager lm = new LDAPManager();
try {
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
177
![Page 197: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/197.jpg)
HashMap modifications = new HashMap();modifications.put(“mail”, “[email protected]”);
lm.modify(“uid=proy,ou=People,o=virtuas.com”, modifications,DirContext.REPLACE_ATTRIBUTE);
}catch (NamingException e) {
e.printStackTrace();}
In this example we are replacing the existing value for the e-mail address with the new value of“[email protected]”. This change is made to the object specified by the DN “uid=proy,ou=People, o=virtuas.com”. It is important to note that more than one attribute can be modi-fied at the same time, however the attributes will all be bound by the same modification opera-tor.
The full listing for the manager class we have been developing appears in Listing 11.2.
LISTING 11.2 LDAPManager.java
import java.util.Map;import java.util.Vector;import java.util.Hashtable;import java.util.HashMap;import java.util.Iterator;import java.util.Vector;import javax.naming.NamingEnumeration;import javax.naming.directory.*;import javax.naming.NamingException;
public class LDAPManager {
protected String factory = “com.sun.jndi.ldap.LdapCtxFactory”;protected String serverName = “serverName”;protected int port = 389;protected String securityAuthentication = “simple”;protected String dirManager = “cn=Directory Manager”;protected String dirManagerPw = “directory”;protected String searchBase = null;protected int searchScope = SearchControls.SUBTREE_SCOPE;
public LDAPManager() {
}
Servlet Fundamentals
PART I178
![Page 198: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/198.jpg)
/*** Returns all of the necessary environment information required to* create a Context and bind to an LDAP server.*/protected Hashtable getEnvironment() {
Hashtable env = new Hashtable();
// generate LDAP host URLStringBuffer url = new StringBuffer(“ldap://”);url.append(serverName).append(“:”).append(port);
// set Context Factory classenv.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, factory);// set host URLenv.put(javax.naming.Context.PROVIDER_URL, url.toString());
// Only set authentication information if there is a username// presentif ((dirManager != null) && (dirManager.trim().length() > 0)) {
env.put(javax.naming.Context.SECURITY_AUTHENTICATION,securityAuthentication);
env.put(javax.naming.Context.SECURITY_PRINCIPAL, dirManager);env.put(javax.naming.Context.SECURITY_CREDENTIALS, dirManagerPw);
}
return env;}
/*** Creates a new Directory Context based on the local settings.*/protected DirContext getInitialContext(Hashtable env) throws
➥NamingException {
return new InitialDirContext(env);}
/*** Searches the ldap server using the search filter that is passed to the* method.*/
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
179
LISTING 11.2 Continued
![Page 199: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/199.jpg)
public Vector search(String[] returnAttributes, String searchFilter)throws NamingException {
Vector ldapObjects = new Vector();SearchControls ctls = new SearchControls();ctls.setReturningAttributes(returnAttributes);ctls.setSearchScope(searchScope);NamingEnumeration results = null;
// bind to the LDAP server.DirContext ctx = getInitialContext(getEnvironment());
// perform the search on the LDAP server.results = ctx.search(searchBase, searchFilter, ctls);while ((results != null) && (results.hasMore())) {
// get the next set of results from the search.SearchResult sr = (SearchResult)results.next();// get all of the attributes for this object.Attributes attributes = sr.getAttributes();NamingEnumeration attEnum = attributes.getAll();// create an LDAPObject to hold the results.LDAPObject tmpObj = new LDAPObject();
// set the Distinguished Name for the object. Append// the relative dn and the searcb base together.tmpObj.setDn(sr.getName() + “,” + searchBase);// iterate through the attributes setting them in the LDAPObjectwhile (attEnum.hasMore()) {
// get the next attributeAttribute att = (Attribute)attEnum.next();// set the attribute in the LDAPObjecttmpObj.setAttribute(att.getID(), att.get());
}// add the object to the list of return objectsldapObjects.add(tmpObj);
}
return ldapObjects;}
/*** Updates the given object in the LDAP server.*/
Servlet Fundamentals
PART I180
LISTING 11.2 Continued
![Page 200: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/200.jpg)
public void modify(String dn, HashMap attributes, int modOp)throws NamingException {
// perform the modification on all of the given attributes// based on the modOp that was passed inDirContext ctx = getInitialContext(getEnvironment());ctx.modifyAttributes(dn, modOp, parseAttributes(attributes));
}
/*** Adds a new object to the LDAP server with the give attributes.*/public void add(String dn, HashMap attributes, String[] objectClass)
throws NamingException {
// parse the attributes that were passed inAttributes atts = parseAttributes(attributes);
// add objectClass attribute to the list of attributesAttribute oc = new BasicAttribute(“objectClass”);for (int i = 0; i < objectClass.length; i++) {
oc.add(objectClass[i]);}atts.put(oc);
// perform the addition to the LDAP serverDirContext ctx = getInitialContext(getEnvironment());ctx.bind(dn, null, atts);
}
/*** Remove the specified object from the LDAP server.*/public void remove(String dn) throws NamingException {
// perform the deletion from the LDAP server based on the objects DNDirContext ctx = getInitialContext(getEnvironment());ctx.destroySubcontext(dn);
}
public Attributes parseAttributes(HashMap attributes) {
if (attributes == null) {
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
181
LISTING 11.2 Continued
![Page 201: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/201.jpg)
return null;}
Attributes newAtts = new BasicAttributes();
// get an iterator for all of the keys in the HashMapIterator attIter = attributes.keySet().iterator();while (attIter.hasNext()) {
// get the value for the key.String attName = (String)attIter.next();Object value = attributes.get(attName);
// create a new AttributeAttribute attribute = new BasicAttribute(attName, value);
// add the attribute to the list of attributesnewAtts.put(attribute);
}
return newAtts;}
public void setFactory(String factory) {
this.factory = factory;}
public String getServerName() {
return serverName;}
public void setServerName(String serverName) {
this.serverName = serverName;}
public int getPort() {
return port;}
Servlet Fundamentals
PART I182
LISTING 11.2 Continued
![Page 202: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/202.jpg)
public void setPort(int port) {
this.port = port;}
public String getSearchBase() {
return searchBase;}
public void setSearchBase(String sb) {
searchBase = sb;}
public String getSecurityAuthentication() {
return securityAuthentication;}
public void setSecurityAuthentication(String sa) {
this.securityAuthentication = sa;}
public String getDirManager() {
return dirManager;}
public void setDirManager(String dirManager) {
this.dirManager = dirManager;}
public String getDirManagerPw() {
return dirManagerPw;}
public void setDirManagerPw(String dirManagerPw) {
this.dirManagerPw = dirManagerPw;}
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
183
LISTING 11.2 Continued
![Page 203: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/203.jpg)
public int getSearchScope() {
return searchScope;}
public void setSearchScope(int sc) {
searchScope = sc;}
}
Accessing LDAP from a ServletBy using the LDAP manager class that we have developed, accessing the LDAP server fromany servlet is very simple. You acquire all the information you need to perform the specificoperation and then make the appropriate call to LDAPManager.
If you download the source code for this book, an extra class is provided to help load severalpeople into a LDAP server. This class is named LDAPInsertData. All you need to do is com-pile it and run it to insert 14 people into the server. This will work as long as you have installedthe root of your LDAP tree as “o=virtuas.com”. The source code for LDAPInsertData appearsin Listing 11.3.
LISTING 11.3 LDAPInsertData.java
import java.util.HashMap;import javax.naming.NamingException;
public class LDAPInsertData {
public LDAPInsertData() {
}
public static void main(String[] args) {
LDAPManager lm = new LDAPManager();String[] objectClass = {“top”,
“person”,“organizationalPerson”,“inetOrgPerson”};
Servlet Fundamentals
PART I184
LISTING 11.2 Continued
![Page 204: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/204.jpg)
String[] snArray = {“Berry”,“Blake”,“Bourque”,“Drury”,“Foote”,“Forsberg”,“Hejduk”,“Hinote”,“Nieminen”,“Parker”,“Podein”,“Roy”,“Sakic”,“Tanguay”};
String[] fnArray = {“Rick”,“Rob”,“Ray”,“Chris”,“Adam”,“Peter”,“Milan”,“Dan”,“Ville”,“Scott”,“Shjon”,“Patrick”,“Joe”,“Alex”};
String[] uidArray = {“rberry”,“rblake”,“rbourque”,“cdrury”,“afoote”,“pforsberg”,“mhejduk”,“dhinote”,“vnieminen”,“sparker”,“spodein”,“proy”,“jsakic”,“atanguay”};
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
185
LISTING 11.3 Continued
![Page 205: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/205.jpg)
String[] phoneArray = {“(800) 123-4567”,“(800) 123-4365”,“(800) 135-4568”,“(800) 320-7428”,“(800) 622-4589”,“(800) 124-4570”,“(800) 827-4561”,“(800) 425-1564”,“(800) 626-7526”,“(800) 322-8864”,“(800) 821-3957”,“(800) 120-5565”,“(800) 320-0539”,“(800) 123-456”};
try {
for (int i = 0; i < snArray.length; i++) {
String dn = “uid=” + uidArray[i] + “,ou=People,o=virtuas.com”;
HashMap atts = new HashMap();atts.put(“cn”, fnArray[i] + “ “ + snArray[i]);atts.put(“sn”, snArray[i]);atts.put(“givenName”, fnArray[i]);atts.put(“uid”, uidArray[i]);atts.put(“mail”, uidArray[i] + “@virtuas.com”);atts.put(“telephoneNumber”, phoneArray[i]);
lm.add(dn, atts, objectClass);}
}catch (NamingException e) {
e.printStackTrace();}
}}
We have already written the foundation for many simple LDAP applications. Here is an exam-ple of a servlet that selects information from an LDAP server by searching on the user’s lastname and then outputs the results. The full listing for LDAPTestServlet is in Listing 11.4.
Servlet Fundamentals
PART I186
LISTING 11.3 Continued
![Page 206: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/206.jpg)
LISTING 11.4 LDAPTestServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import javax.naming.NamingException;
public class LDAPTestServlet extends HttpServlet {
private static final String CONTENT_TYPE = “text/html”;
/**Initialize global variables*/public void init(ServletConfig config) throws ServletException {
super.init(config);}
/**Process the HTTP Get request*/public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// define what results we want from the searchString[] returnAtts = {“cn”,
“sn”,“givenName”,“mail”,“telephoneNumber”};
// get the search criteria from the requestString lName = request.getParameter(“lName”);
// create a search filter, searching on the last name passed inString filter = “sn=” + lName.trim();
// create and initialize an LDAPManagerLDAPManager lm = new LDAPManager();lm.setSearchBase(“o=virtuas.com”);
// perform the searchVector results = null;try {
results = lm.search(returnAtts, filter);}catch (NamingException ex) {
Servlets and LDAP
CHAPTER 11
11
SER
VLETS
AN
DLD
AP
187
![Page 207: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/207.jpg)
throw new ServletException(ex);}
// output the resultsresponse.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();out.println(“<html>”);out.println(“<head><title>LDAPTestServlet</title></head>”);out.println(“<body>”);out.println(“<p>The search results are:</p>”);
Iterator iter = results.iterator();while (iter.hasNext()) {
LDAPObject lobj = (LDAPObject)iter.next();out.println(lobj.getDn());out.println(“cn: “ + lobj.getAttribute(“cn”) + “<br>”);out.println(“sn: “ + lobj.getAttribute(“sn”) + “<br>”);out.println(“givenName: “ + lobj.getAttribute(“sn”) + “<br>”);out.println(“mail: “ + lobj.getAttribute(“mail”) + “<br>”);out.println(“telephoneNumber: “
+ lobj.getAttribute(“telephoneNumber”) + “<br>”);out.println(“<br> <br>”);
}
out.println(“</body></html>”);}/**Clean up resources*/public void destroy() {
}}
SummaryLDAP provides an alternative method of persistent storage. It is well suited for systems thatrequire a high volume of read operations combined with a limited number of modifications.The data is represented in a tree-like hierarchy and consists of objects containing name-valuepairs. Java provides an API to access LDAP servers called Java Naming and DirectoryInterface (JNDI). JNDI makes accessing LDAP servers simple, and it is a good choice formany systems.
In the next chapter we are going to discuss Enterprise JavaBeans and how they can be lever-aged to encapsulate Web application business logic.
Servlet Fundamentals
PART I188
LISTING 11.4 Continued
![Page 208: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/208.jpg)
CHAPTER
12Servlets and EnterpriseJavaBeans
IN THIS CHAPTER• What Are Enterprise JavaBeans? 190
• EJB Terminology 191
• Installing JRun 191
• The Enterprise JavaBean 192
• Session Beans 194
• Entity Beans 206
• Deploying Your EJB to Your Application Server 218
• Servlets as EJB Clients 220
![Page 209: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/209.jpg)
Servlet Fundamentals
PART I190
What Are Enterprise JavaBeans?Sun’s Enterprise JavaBean specification defines the EJB architecture as follows: “TheEnterprise JavaBeans architecture is a component-based architecture for the development anddeployment of component-based distributed business applications. Applications written usingthe Enterprise JavaBeans architecture are scalable, transactional, and multi-user secure. Theseapplications may be written once, and then deployed on any server platform that supports theEnterprise JavaBeans specification.”
The definition mentions component-based–distributed business applications. The EJB architec-ture enables different components of a system to exist on distributed machines and to operatetogether as if they all existed in the same application space. Alone this might not sound muchdifferent from Java’s Remote Method Invocation (RMI), and actually EJB makes use of RMIas part of its underlying structure. However, it is not this one aspect of EJB that makes thearchitecture so powerful but it is this in combination with the other traits that are mentioned.
EJB systems are easily scalable. You will see how simple it is to add and remove functionalityto a system that has been written using the EJB architecture. Not only are the applications scal-able in terms of functionality, but they can easily scale to handle changing numbers of clientsaccessing the application. Because an application server manages EJBs, their number can beincreased or reduced depending on the need. This is a topic that will be discussed later.
Previously the application developer was responsible for writing and maintaining transactionalmanagement code. The EJB designer has the ability to decide whether to let the EJBs manageall transactions and how each individual EJB will participate in the transactions. It is importantto have all related tasks included within one transaction to make sure that all necessary tasksare completed or that none of them are. This is the concept of ACID (Atomicity, Consistency,Isolation, and Durability) transactions that are so talked about by database designers.
Another topic that we will discuss is the ability to reuse EJBs across many systems with verylittle work. The two types of EJBs are the session bean and the entity bean. One holds the keyissues related to business logic, and the other acts as an object-oriented interface to your persis-tence layer. Both can be easily moved from system to system, database to database, and fromplatform to platform without the slightest code change. This is a great characteristic of anysoftware component, but when combined with the rest of the EJB concepts, it becomes a greatbuilding block for all software systems.
The rest of this chapter will help you understand the power associated with designing a systemusing EJBs. This is a brief chapter on a very complex topic. The specification itself is over 500pages, and although it lays out exactly what all of the pieces of an EJB system are responsiblefor, it does not discuss all of the intricacies of properly developing an EJB system. This chapterattempts to give you an awareness of the topic, the ability to write and deploy simpleEnterprise JavaBeans, and the foundation to continue your education on the topic.
![Page 210: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/210.jpg)
EJB TerminologyFor the purposes of this chapter we must define several concepts as they relate to EnterpriseJavaBeans. Each of these pieces has a specific role that is defined by the EJB specification,which lays out very precisely the responsibilities of each and how they interact with eachother. These components are as follows:
• EJBs—The server-side objects containing your business logic. This is where you will doall of your work to define the functionality of the system.
• Application Server—Provides the deployment tools necessary to deploy the EJBs, aswell as runtime support for the deployed EJBs. The interaction between applicationserver and EJB is important, and we will discuss how the application server manages thelifecycle of each EJB instance.
• EJB Client—The client to an EJB is the software that is accessing and making methodinvocations to the EJB, either through its home or remote interfaces, both of which willbe discussed later. The EJB client can be an applet, a servlet, or any code, including anyother EJB.
All of these pieces must work flawlessly together for an EJB system to accomplish its goals.As mentioned before, all of the interactions between these pieces are defined in the specifica-tion, and this contractual agreement is what enables an EJB application to be easily deployedon different systems.
Installing JRunBefore we get started developing our example, you need to download and install an EJB con-tainer. For our examples we are going to be using Allaire’s JRun. Installing and configuringJRun is very simple. The first thing to do is to download the product from Allaire. This can bedone at
http://www.allaire.com
You will download an executable that will install the program. The first thing that you will doduring installation is to accept the licensing agreement. The setup program will then ask youfor a serial number; you should leave this blank. By leaving the serial number blank you willgain access to a developer’s license for the product. This license is a full working version ofthe application server, but it only allows three simultaneous connections.
After this, accept all of the default entries for the installation of JRun. After the product installsyou will be guided through the configuration of the Admin server for JRun. Choose a passwordfor the admin account that you will remember. You should also write down the port that is cho-sen for the Admin server. You will need both pieces of information to access the Admin serverto deploy your EJBs.
Now you are ready to deploy and test your Enterprise JavaBeans.
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
191
![Page 211: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/211.jpg)
The Enterprise JavaBeanEnterprise JavaBeans come in two fundamentally different flavors: the entity bean and the ses-sion bean. Entity beans model a real-world object, a noun if you will. The entity bean is associ-ated with persistent state held in a database. Simple examples are an employee, anorganization, a company, and any other object that might be represented in a database. Notonly does the entity bean represent the persistent data associated with the object, it also pro-vides the functionality to make changes directly to the object.
Session beans on the other hand are not associated with a persistent state. They encompass aprocess or task. This is where the business logic of your application exists. Session beans addmeaning to the changes that might be made on an entity bean. For example, reducing the num-ber of a specific item in inventory and billing a customer are two tasks that by themselves donot make much sense. However, they have a solid meaning when combined into the specificcontext of selling the item to the customer.
The total transaction of billing a customer for a specific item, having it shipped, and maintain-ing proper records on inventory makes use of many different objects. A customer bean and anitem bean are some entity beans that would be required to accomplish this task. A session beanis required to perform all of the necessary steps and make all of the changes to the entity beansto complete the process of selling this item to the customer.
There is resulting persistent data in the form of entity beans: for example, updated inventory, abill for the customer, and possibly a record of the credit card transaction, however the sessionbean is inherently transient. The process begins, the steps are carried out, and then it is fin-ished.
Interfaces and ClassesNow that you have some understanding of the difference between entity beans and sessionbeans, let’s take a look at the objects and interfaces that make up an EJB.
Home InterfaceThe home interface for an EJB defines the lifecycle methods for the bean. It has methods forcreating, removing, and in the case of entity beans, searching beans. This is the first interactionwith an EJB that most clients have. The home interface extends the javax.ejb.EJBHome inter-face.
Remote InterfaceThe remote interface defines the business methods that can be performed on the bean. This isthe API that the bean presents the outside world for use. The remote interface extends thejavax.ejb.EJBObject interface.
Servlet Fundamentals
PART I192
![Page 212: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/212.jpg)
Bean ObjectThe bean object is made up of the methods that implement the business logic for the bean.Clients never directly access the methods in this object. They always make use of the homeand remote interfaces.
An interesting note is that the bean object does not implement either the home or remote inter-faces. However, it must have methods that match the signatures for all of the methods in theremote interface and methods that correspond with many of the methods in the home interface.These are some of the interaction regulations that are laid out in the specification. We will takea deeper look at these rules later. Depending on whether the bean is a session bean or entitybean, the bean object must extend either javax.ejb.SessionBean or javax.ejb.EntityBean.
Primary KeyThe primary key class is specific to entity beans. It is a very simple class that specifies theattributes that make up the unique primary key for the entity bean. The only requirement is thatit implements java.io.Serializable.
Naming ConventionsThe naming conventions for the interfaces and classes associated with an EJB do not actuallyhave any specific rules, however there is a recommended convention. This convention holdstrue for both session and entity beans, and will be used throughout this chapter.
We will use a fictitious entity bean—Employee—to illustrate the naming conventions associ-ated with an EJB. The overall component made up of all of the interfaces and classes neces-sary for a bean is referred to as the bean itself, for example Employee Bean.
The home interface class is generally named after the bean with Home appended. In the case ofthe Employee Bean, the home interface is named EmployeeHome. The remote interface is theclient’s real view of the bean; therefore it takes the bean’s name alone. The name of the remoteinterface for the Employee Bean is simply Employee. The bean object containing the data forthe bean takes the bean’s name and adds the word Bean, for example EmployeeBean.
The primary key class associated with entity beans is somewhat more ambiguous. If a specificuser-defined class will be the primary key, a good convention is the bean’s name followed byPK. Our Employee Bean’s primary key class would be named EmployeePK. The ambiguityarises because it is possible to use any Serializable class in Java. A very commonly used pri-mary key class found in Java is Integer. It is up to the bean designer to define the primarykey.
With the knowledge of the different classes and interfaces that are required for an EJB, we canand look at the ways EJBs are used by clients and managed by application servers.
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
193
![Page 213: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/213.jpg)
Session BeansSession beans define a process or task. Software systems are made up of collections ofprocesses, and in many instances each process is composed of smaller tasks. This architectureis exactly what session beans are designed to build. This is how you should design the businesslogic of your software using session beans.
If you develop processes that are generic and reusable on many systems, you can use these ses-sion beans independently, or develop more detailed session beans that string together several ofthese processes. Think of a session bean that processes a credit card transaction or a sessionbean with methods to provide several different billing mechanisms. This is certainly a usefulutility from which many systems can benefit.
Stateless Versus StatefulWithin the family of session beans there are two types, stateless and stateful. Session beans donot have persistence, but that does not prevent them from having attributes and holding state.The distinction between stateless and stateful is that a stateful session bean can have attributesthat hold a conversational state between method invocations. This state is necessary and mustnot be lost between method calls. An example is an e-commerce shopping cart. When the cartis created it will be empty, but eventually a call will be made to add an item, and then tochange the quantity of that item in the cart. More items can be added, but at some point theuser will want to check out. If all of the information about the items previously placed in thebasket is lost at some point during this process, the customer will be angry.
This is a great concept, but allowing a session bean to maintain state does not come without aprice. A stateful session bean is less efficient than a stateless bean for more than one reason.One of the big costs comes from the fact that more stateful session beans need to exist simulta-neously because they cannot be shared as readily as stateless session beans. How would youlike it if somebody else placed things in your shopping cart? The topic of bean pooling andreuse will be discussed later.
Stateless session beans on the other hand hold no state that is required to be kept betweenmethod invocations. After the method has finished processing, it returns and no longer main-tains any information specific to the client that it just serviced. A session bean used to processa credit card payment illustrates this. The method to handle this business process would takeall the necessary information as parameters, and would return success or failure. None of theinformation needs to be retained by the session bean. This fictitious bean can also contain thebusiness logic to process a payment by check.
Each session bean in a system should be evaluated as to whether it needs to maintain conversa-tional state. In most cases it will be obvious after the processes are clearly specified.
Servlet Fundamentals
PART I194
![Page 214: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/214.jpg)
Session Bean Interfaces and ClassesThe differences that occur in the interfaces and classes required to build a session bean dependon whether the bean is stateful or stateless. You will develop a sample session bean throughoutthe next section.
The sample session bean is a stateless session bean, CalculateLoan, with a method that can beused to calculate the monthly payment for a loan, given the necessary information.
Remote InterfaceThe remote interface for any session bean defines the client’s access to the business logic con-tained within the bean. These are the methods that define the usefulness of the bean.
This interface will drive the development for the bean class. Here you must design the client’sinteraction with the bean. After this API is well defined it usually remains static. After it hasbeen integrated into client code, changing the existing prototypes will have detrimental effectson the client. Because this is only an interface and contains no code, after it is finished it ispossible for clients to begin integrating it.
Defining the remote interface is governed by a few regulations. The interface must extend thejavax.ejb.EJBObject. Every method must follow the rules for RMI/Internet Inter-ORBProtocol (IIOP). This means that each parameter and return type must be of valid types forRMI/IIOP. Also, each method must include at least java.rmi.RemoteException in the throwsclause. Other than these two simple regulations all you must do is define what the public inter-face for your session bean will contain.
The remote interface for the CalculateLoan bean is very simple. The source code for theremote interface is in Listing 12.1.
LISTING 12.1 CalculateLoan.java
import javax.ejb.EJBObject;import java.rmi.RemoteException;
public interface CalculateLoan extends EJBObject{
public Float calcMonthlyPayment(Integer months, Float principal)throws RemoteException;
public Float getCurrentInterestRate() throws RemoteException}
Let’s look at the exceptions in this class. You will see that all of the methods throwRemoteException as required by the EJB specification. As long as this exception is included inthe throws clause, any other exception can also be included in the throws clause. Once againthese exceptions are system specific and defined by the bean designer.
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
195
![Page 215: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/215.jpg)
Notice also that the calcMonthlyPayment() method does not take an interest rate as a parame-ter. This is because the interest rate will be used to illustrate how values can be deployed in aspecific bean’s environment and made available to the bean at any time. This will also give yousome understanding of how an EJB system can be configured upon deployment without anycode changes.
Home InterfaceThe home interface for an EJB defines lifecycle methods. In the case of a session bean theimportant lifecycle events are creation and removal. The only thing that you need to worryabout as a bean designer is the creation of session beans. The remove method and functionalityare contained within the base interface.
The home interface for a session bean has slightly more stipulations associated with it than theremote interface. It must extend javax.ejb.EJBHome. All of the RMI/IIOP regulations thatwere in place for the remote interface are also present for the home interface; it is an interfaceto a remote object.
The other rules apply specifically to the name and prototypes of the methods contained withinthe home interface. The first stipulation on the methods is that there must be one or more cre-ation methods. Each of these methods must be named create(). They must also includejavax.ejb.CreateException, as well as the RemoteException specified by the RMI/IIOPrules. Once again there is no rule that limits any other exceptions from being present in thethrows clause.
Each create() method must return the specific remote interface type for that bean. This allowsthe client access to the business logic after it has retrieved the home interface and created aninstance of the bean. For example the create() methods for the CalculateLoanHome interfacewill return the CalculateLoan interface.
These create() methods provide the first difference you will see between stateless and statefulsession beans. In almost all cases, a stateless session bean will contain only one create()method that takes no parameters. The reason for this is that any parameters passed to the create() method would be client-specific information that would need to be stored in the beanafter the creation until the next method invocation. This is a conversational state that the state-less session bean cannot maintain.
The CalculateLoan bean in Listing 12.2 shows only one create() method because it is beingdefined as a stateless session bean.
LISTING 12.2 CalculateLoanHome.java
import javax.ejb.EJBHome;import javax.ejb.CreateException;import java.rmi.RemoteException;
Servlet Fundamentals
PART I196
![Page 216: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/216.jpg)
public interface CalculateLoanHome extends EJBHome{
public CalculateLoan create()throws RemoteException, CreateException;
}
This is a simple interface that has only a few rules to follow. Now we will look at the beanclass and some of the more difficult to understand rules that the specification imparts to EJBcode.
Bean ClassThe bean class holds the implementation for the EJB. It has certain requirements in relation toboth the home and remote interfaces. The rules related to each interface are different, so wewill go through them independently.
First we will cover the general requirements for the session bean’s bean class. It must imple-ment the javax.ejb.SessionBean interface. In implementing SessionBean, four methodsmust be implemented: ejbActivate(), ejbPassivate(), ejbRemove(), andsetSessionContext(). All of these methods will be discussed briefly later in the chapter.
The class must contain a public constructor that takes no arguments. This is the only construc-tor that is useful in any EJB because all client construction of these beans is done through thecreate() methods.
The first requirement is related to the home interface. For each create() method in the homeinterface, the bean class must have an ejbCreate() method with an argument list that exactlymatches the signature of the corresponding create() method. The ejbCreate() method alsodefines the same throws clause as the matching create() method. Each ejbCreate() methodmust be public and return void. The following code snippet gives an example of a create()method from a home interface and the matching ejbCreate() method that would exist in thebean class:
public BeanRemote create(Integer number)throws RemoteException, CreateException, AppDefinedException;
public void ejbCreate(Integer number)throws RemoteException, CreateException, AppDefinedException
{this.number = number;
}
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
197
LISTING 12.2 Continued
![Page 217: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/217.jpg)
Notice the matching argument lists and throws clauses. As mentioned before, because thiscreate() method accepts an argument list, it would probably be associated with a stateful ses-sion bean. This also explains why the body of the ejbCreate() method initializes the bean’sstate. The create()/ejbCreate() combination of methods acts as a pseudoconstructor that theclient uses for the bean.
Next are the responsibilities of the bean class in relation to the remote interface. The bean classmust implement each of the business methods defined in the remote interface. This includesfollowing all the rules laid out for these methods, for example RMI/IIOP compliance. Oneimportant rule is that the name of these methods cannot begin with ejb, to avoid naming con-flicts with the callback methods that begin this way. The sample bean class still remains afairly simple class. You can find the source for the bean class in Listing 12.3.
LISTING 12.3 CalculateLoanBean.java
import javax.ejb.SessionBean;import javax.ejb.SessionContext;import java.rmi.RemoteException;import javax.naming.Context;import javax.naming.InitialContext;
public class CalculateLoanBean implements SessionBean {
protected SessionContext ctx = null;
public CalculateLoanBean() {
}
public Float calcMonthlyPayment(Integer months,Float principal)
throws RemoteException {
Float yearlyIntTmp = getCurrentInterestRate();
// Perform all of the calculations to figure out// the monthly payment.float yearlyInt = yearlyIntTmp.floatValue() / 100;float monthlyInt = yearlyInt / 12;
double payment = (principal.floatValue() * monthlyInt) /(1 - (Math.pow(1 / (1 + monthlyInt),months.intValue())));
return new Float((float)payment);}
Servlet Fundamentals
PART I198
![Page 218: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/218.jpg)
public Float getCurrentInterestRate() throws RemoteException {Float yearlyInt = null;
try {
// Obtain the enterprise bean’s environment// naming context.Context initCtx = new InitialContext();Context myEnv =
(Context)initCtx.lookup(“java:comp/env”);
// Obtain the yearly interest rate from the// bean’s environmentyearlyInt = (Float)myEnv.lookup(“interestRate”);
}catch (javax.naming.NamingException nex) {
// If there was a problem with JNDI,// getting the yearly interest// rate, we will just default it to 8%yearlyInt = new Float(8.0f);
}
return yearlyInt;}
public void ejbCreate() throws javax.ejb.CreateException,java.rmi.RemoteException {
}
public void ejbActivate() throws javax.ejb.EJBException,java.rmi.RemoteException {
}public void ejbPassivate() throws javax.ejb.EJBException,
java.rmi.RemoteException {
}
public void ejbRemove() throws javax.ejb.EJBException,java.rmi.RemoteException {
}
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
199
LISTING 12.3 Continued
![Page 219: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/219.jpg)
public void setSessionContext(SessionContext ctx)throws javax.ejb.EJBException, java.rmi.RemoteException {
this.ctx = ctx;}
}
Remember that there is an ebjCreate() method to match each of the create() methods in thehome interface. The bean class fully implements each of the business methods specified in theremote interface. Note the exact same signatures between the two methods.
All of the abstract methods defined in the base class SessionBean have been implemented,even though most of them are empty. Every session bean is required to maintain theSessionContext, which will be assigned to it by the container. The attribute is set through thesetSessionContext() method. This and the other callback methods, ejbActivate(),ejbPassivate(), and ejbRemove(), will all be discussed when we look at the container’s inter-action with the session bean and the bean’s lifecycle.
The business method, calcMonthlyPayment(), includes code to perform the necessary calcula-tions. This method is not written differently from any other Java method. The one piece ofcode that is specific to an EJB is in the getCurrentInterestRate() method where you obtainthe yearly interest rate from the EJB’s environment.
Deployment DescriptorDeploying a group of EJBs gives the application server a description of each bean as well as aset of instructions that tell it how to manage the beans. One or more EJBs are grouped into ajar file along with an ejb-jar.xml file (the deployment descriptor), and they are deployed tothe application server to handle.
The ejb-jar.xml file can contain two types of information. The EJB’s structural informationprovides all of the dependency information for an EJB. This information is required, and isusually not changed after it is solidified, because change will affect not only the structure ofthe bean, but the clients that use it. The second type of information that can be present in theejb-jar.xml file is application assembly information. This information defines how each EJBinteracts to compose a larger application unit. The application assembly information isoptional, and by changing it you are only affecting how the bean works in the larger group.
The ejb-jar.xml file contains XML tags to describe all the necessary information. The struc-ture of the ejb-jar.xml file is regulated by a document type definition (DTD) that can befound at http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd. We will use only a small subsetof the XML tags that are possible in an EJB deployment descriptor.
Servlet Fundamentals
PART I200
LISTING 12.3 Continued
![Page 220: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/220.jpg)
The ejb-jar.xml file must include a directive pointing to the DTD. The following code snip-pet is an example of this directive:
<!DOCTYPE ejb-jar PUBLIC “-//Sun Microsystems, Inc.//DTD EnterpriseJavaBeans 1.1//EN” “http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd”>
This line must appear at the top of every ejb-jar.xml file.
The outermost tag in the ejb-jar.xml file is <ejb-jar>. Everything will be contained withinthis tag. You will have two main sections within this tag, one to define the EJB structural infor-mation, contained inside the <enterprise-beans> tag, and a second section to define theapplication assembly information, contained inside the <assembly-descriptor> tag.
You describe the dependencies of a session bean with an entry inside the <enterprise-beans>tag. The following code snippet gives an example of this description:
<session><description>
Makes calculations related to a loan</description><ejb-name>CalculateLoan</ejb-name><home>CalculateLoanHome</home><remote>CalculateLoan</remote><ejb-class>CalculateLoanBean</ejb-class><session-type>Stateless</session-type><transaction-type>Container</transaction-type>
</session>
This is a basic descriptor for our session bean. Each session bean in the jar file will have anentry similar to this in the ejb-jar.xml file. The <ejb-name> tag identifies the name underwhich the home interface will be kept by Java Naming and Directory Interface (JNDI). JNDIprovides a standard method for accessing named objects. This is the name needed to look it up.It is arbitrary, however it must be unique within the application. Many times a prefix will beused to avoid naming collisions with other EJB packages, for example,bookExamples.CalculateLoan.
The <home>, <remote>, and <ejb-class> tags all contain the fully qualified classpath to theirrespective interface or class. The <session-type> tag can contain only two values, Statelessor Stateful. This identifies whether you have decided to include conversational state in thesession bean.
The last tag you see is <transaction-type>. It can hold two possible values—Container orBean. You have seen that it is possible to allow the container to manage all of the transactions,and that each individual bean participates in the transactions. This tag specifies whether to letthe container take these responsibilities or have the bean handle them itself. For our example,the container will handle all of the dirty work.
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
201
![Page 221: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/221.jpg)
You must add one more section to your bean descriptor, allowing you to use the environmentvariable. The bean’s environment is made available to the bean by the container. The valuesthat are available to the bean are specific to each bean type. The variable values are set up atdeployment time, and are not changeable at runtime. The environment is provided under thecontext java:comp/env.
Each environment variable is declared in the deployment descriptor for the bean. The possiblevalues for these basic variables are: String, Integer, Boolean, Double, Byte, Short, Long, andFloat. The deployment of the interest rate is added to the session description you already have,and looks like the following code snippet:
<session>...<env-entry>
<description>The yearly interest rate.
</description><env-entry-name>interestRate</env-entry-name><env-entry-type>java.lang.Float</env-entry-type><env-entry-value>8.2</env-entry-value>
</env-entry></session>
This is just a brief introduction to the uses of the EJB’s environment. It is also possible to placeSQL DataSources, other EJB’s home interfaces, and other useful items into the environment.This is a more advanced topic.
This is all we need to provide in the EJB structure part of the deployment descriptor. We willalso provide a small entry in the application assembly section to tell the container how to han-dle transactions. The entire application assembly description appears as follows:
<assembly-descriptor><container-transaction>
<method><ejb-name>CalculateLoan</ejb-name><method-name>*</method-name>
</method><trans-attribute>Required</trans-attribute>
</container-transaction></assembly-descriptor>
Here you tell the container that for every method in CalculateLoan, the transaction setting isRequired; this setting means that if the client is not already involved in a transaction, a newtransaction should be started when entering the bean. How the transactions are handled can bedefined at the method level. Each method in the home and remote interface of your bean could
Servlet Fundamentals
PART I202
![Page 222: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/222.jpg)
be specified here. Definitions for the six different transactional attributes are in the EJB speci-fication.
You can see the contents of the entire ejb-jar.xml file in Listing 12.4
LISTING 12.4 ejb-jar.xml
<?xml version=”1.0”?>
<!DOCTYPE ejb-jar PUBLIC “-//Sun Microsystems, Inc.//DTD EnterpriseJavaBeans 1.1//EN” “http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd”>
<ejb-jar><enterprise-beans>
<session><description>
Makes calculations related to a loan</description><ejb-name>CalculateLoan</ejb-name><home>CalculateLoanHome</home><remote>CalculateLoan</remote><ejb-class>CalculateLoanBean</ejb-class><session-type>Stateless</session-type><transaction-type>Container</transaction-type><env-entry>
<description>The yearly interest rate.
</description><env-entry-name>interestRate</env-entry-name><env-entry-type>java.lang.Float</env-entry-type><env-entry-value>8.2</env-entry-value>
</env-entry></session>
</enterprise-beans><assembly-descriptor>
<container-transaction><method>
<ejb-name>CalculateLoan</ejb-name><method-name>*</method-name>
</method><trans-attribute>Required</trans-attribute>
</container-transaction></assembly-descriptor>
</ejb-jar>
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
203
![Page 223: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/223.jpg)
Now that you have all of the interfaces and the deployment descriptor finished, it is time tocreate a jar file containing all of the class files, and the ejb-jar.xml file in the META-INFdirectory. After this jar file is complete, you must follow the deployment directions specific toyour application server. This topic is discussed in a later section, “Deploying Your EJB to YourApplication Server.”
Client View of a Session BeanWe have talked quite a bit about what goes into the writing of an EJB and session beans. Nowwe will finish the picture by discussing how a client accesses an EJB.
The first thing that any client must do is locate the home interface for the session bean itrequires. If you remember, the home interface is stored in a JNDI service, so we must use aJNDI context to look it up. The code looks like this:
Context initialContext = getInitialContext();CartHome cartHome =
(CartHome)javax.rmi.PortableRemoteObject.narrow(initialContext.lookup(“CalculateLoan”), CalculateLoanHome.class);
Creating the InitialContext for the JNDI lookup can be specific to the application server youare using. In general client code, it requires that a Context factory class be passed to it.However, when another EJB is acting as the client, other bean home interfaces can be deployedinto the bean’s environment.
Deploying a home interface into another bean’s environment is similar to the variable youdeployed earlier. When this is done, the lookup becomes easier because the client already hassome knowledge of the home interface.
The method of casting the object returned from the JNDI lookup is unique. You will notice thatthe static narrow() method of the PortableRemoteObject class is used prior to casting thehome interface with a simple casting operator. According to the Enterprise JavaBeansSpecification, this method of narrowing the remote object is required if your code is to be usedamong different EJB-compliant containers. It also states that programs that use the castingoperator to narrow the remote and home interfaces are likely to fail if the current container isusing RMI/IIOP as the underlying communication. Because many of the most popular applica-tion servers implement their EJB container using RMI/IIOP, it is strongly recommended thatyou narrow the interfaces using this method.
After the client has obtained the home interface it requires, it must obtain the remote interfacebefore it can perform any business logic calls to the bean. Because you have developed a state-less session bean, you really only have one choice, and that is the no-argument create()method. The create() method will return the remote interface which gives you access to thebusiness logic of the session bean.
Servlet Fundamentals
PART I204
![Page 224: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/224.jpg)
Session Bean LifecycleThe application server is responsible for many resources. The way in which it hands out andmanages the lifecycle of each Enterprise JavaBean is most important here. For system designpurposes this is important, but I only describe how this works at a very high level because it isout of the scope of this text.
An important concept to know is instance pooling. For efficiency purposes the applicationserver will pool instances of each EJB. By maintaining several instances of an individual beanand sharing them among clients, the application server can reduce the amount of time neces-sary to create and remove a bean every time a client requests one. The client holds a remoteinterface to a bean, but in reality this remote interface interacts with a container class aroundthe bean instance.
A session bean can be in several states while the application is running. Different actions per-formed by both the client and the application server can move the bean instance between thestates. I briefly describe the states and movement for each type of session bean in the follow-ing text. Full descriptions, including state diagrams, are in the EJB Specification.
Stateless Session BeansA stateless session bean can exist in only two states—does not exist and method-ready
pool. The does not exist state is the state that the bean is in prior to the application servercreating the bean and moving it into the pool.
The method-ready pool state is the state that the bean is in when the bean is on the serverwaiting for a client to request it. As you have seen, a stateless session bean holds no statebetween method invocations. This means that when the bean is finished processing a requestfor a client, it is immediately moved back into a waiting state until another request is made forits services. Even if the client maintains a copy of the remote interface for the bean, it is onlyattached to an actual instance of the bean for the duration of one method call.
Stateful Session BeansStateful session beans have a slightly modified lifecycle. We will review the basics at a highlevel. A stateful session bean also begins in the does not exist state. From here it will bemoved into the method ready state when a client invokes any creation method.
When it is in the method ready state, it is considered to have client-specific conversationalstate, and that instance of the bean belongs to the client. It will continue to service that client’srequests. It can be removed from this state back into the does not exist state when the clientcalls the remove method.
Another possibility from the method ready state is to have the bean passivated. Passivationoccurs when a client has a remote interface to a stateful session bean, but is in between methodcalls; the application server can choose to allow the bean instance to service another client.
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
205
![Page 225: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/225.jpg)
The application server will store the conversational state somewhere and initialize the bean foranother client. When this client needs to make another method call the application server willactivate an instance of the bean for it to use. When a bean is passivated, the conversationalstate is stored so that it is not lost. When an instance of the bean is activated again for use bythis client, the conversational state is restored to the same condition it was in at passivation.Subsequent method calls are not necessarily handled by the same instance of the bean, how-ever it does not matter because whenever a new instance is given to the client the conversa-tional state is restored.
Activation and passivation are where the callback methods in the bean class come into play.The ejbActivate() and ejbPassivate() methods are called during this process in case somespecial processing is required to release or restore the state of the bean object.
Entity BeansPersistence is the primary difference between a session bean and an entity bean. The entitybean represents some persistence, and this determines many of the processes involved in writ-ing, deploying, and even using an entity bean.
When a client is accessing an entity bean, any changes that are made are automaticallyreflected in the database. There is no need to tell the entity bean to store itself, or to hand it toa database manager to be updated. This is all part of the contract between the container and allentity beans. It is a great concept and we will take a brief look at how it is taken care of.
Entity beans are not totally different from session beans. They are all still Enterprise JavaBeansand follow many of the same principles. There is still the concept of a home interface, whichcontrols lifecycle events; a remote interface, which provides access to business logic; and abean class, which handles all of the requests. For this reason, we will not repeat all of the con-cepts discussed earlier on session beans. We will point out how they differ and address the con-cepts specific to entity beans.
Who Handles the Persistence?The Enterprise JavaBeans Specification enables the developer to write all of the code to handlepersistence, or enables the container to take care of everything. These two concepts are calledbean-managed persistence and container-managed persistence, respectively.
It is possible to write an entity bean and never write any database-related code. This is usuallythe case when implementing beans using container-managed persistence. This sounds great,but there are also disadvantages to this scheme also. You have less control over how the data isstored, and possibly over the efficiency of the database transaction.
Servlet Fundamentals
PART I206
![Page 226: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/226.jpg)
On the other hand, with bean-managed persistence you must write the SQL statements andlogic to store the information to the database. However, you also have the ability to performcomplex joins, as well as use several statements if necessary to access your data.
Both methods of persistence have advantages and disadvantages and once again the one youuse is a decision you must make. For the purposes of this chapter you will develop a simplebean implemented using container-managed persistence.
Entity Bean Interfaces and ClassesLet’s jump right in and look at the necessary parts to develop an entity bean. The sample entitybean you will develop is a Quote Bean. This container-managed bean will represent a cus-tomer’s loan quote that was acquired from your CalculateLoan Bean.
Remote InterfaceThe remote interface provides access to the entity bean’s business logic, just like the sessionbean’s. With an entity bean, the most common remote interface contains accessor methods forall of the bean’s attributes. This way the client has the capability to set and get the value foreach attribute. This is common in many Java objects; the unique concept here is that changesthat are made are also made in the database.
The Quote remote interface is only going to provide the accessor methods. Listing 12.5 con-tains the source for your Quote remote interface.
LISTING 12.5 Quote.java
import javax.ejb.EJBObject;import java.rmi.RemoteException;
public interface Quote extends EJBObject{
public void setCustomerName(String name) throws RemoteException;public String getCustomerName() throws RemoteException;public void setPhoneNumber(String phone) throws RemoteException;public String getPhoneNumber() throws RemoteException;public void setLoanAmount(Float amt) throws RemoteException;public Float getLoanAmount() throws RemoteException;public void setMonthlyPayment(Float pmt) throws RemoteException;public Float getMonthlyPayment() throws RemoteException;public void setInterestRate(Float rate) throws RemoteException;public Float getInterestRate() throws RemoteException;
}
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
207
![Page 227: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/227.jpg)
There is nothing special about this interface. Note once again that every method throwsRemoteException. There is really no difference between the session bean and entity beanremote interface. Moving on to the home interface, you will begin to see some of the majordifferences.
Home InterfaceThe home interface still provides access to methods that control the EJB’s lifecycle. There arealso some added implications because the entity bean is associated with persistence.
Two types of methods can exist in an entity bean’s home interface—creation methods andfinder methods. You have seen create() methods in the session bean’s home interface, whereyou were required to have at least one such method. The process of creation returns to theclient a remote interface associated with a bean that has been initialized depending on the para-meters passed to the create() method. Also, during this process, a new entry is added to thedatabase. When the client receives the remote interface, the bean has already been inserted intothe database. Creation methods are not required for an entity bean, allowing for information inyour database that is read only.
The second type of method in the entity bean’s home interface is the finder method. Thesemethods allow the client to look for information in the database. These methods also returnremote interfaces for the specific bean type, however the beans are initialized from informationfrom the database. There were no finder methods present in the session bean. This makes senseconsidering that there is nothing to look up when dealing with session beans.
Finder methods all have unique names that are structured find<method>. For examplefindByName(). This will be one of the finder methods for your Quote Bean so that it is possi-ble to look up all of the quotes with the same customer name. The parameters passed to thefinder method are usually used to build the search criteria.
Every finder method must either return the remote interface for the bean, or a collection ofthese remote interfaces. This is determined while the bean is being designed, and depends onwhether the associated search always returns a unique result, or can return multiple entries.
Every entity bean is required to include a findByPrimaryKey() method in their home inter-face. This is a single-object finder that takes the bean’s primary key class as a search parame-ter. We will talk a little more about the primary key class in the next section. Listing 12.6contains the source for the QuoteHome interface.
LISTING 12.6 QuoteHome.java
import java.util.Collection;import javax.ejb.EJBHome;import javax.ejb.CreateException;
Servlet Fundamentals
PART I208
![Page 228: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/228.jpg)
import javax.ejb.FinderException;import java.rmi.RemoteException;
public interface QuoteHome extends EJBHome{
public Quote create(Integer id) throws RemoteException, CreateException;public Quote create(Integer id, String name)throws RemoteException, CreateException;
public Quote findByPrimaryKey(Integer pk)throws RemoteException, FinderException;
public Collection findByName(String name)throws RemoteException, FinderException;
}
Primary Key ClassThe primary key class is specific to entity beans. Every entity bean must have a primary keyclass specified in the deployment descriptor. This is the simplest class involved when writingan entity bean. Many times it is as simple as using the java.lang.Integer class as the pri-mary key.
The primary key class contains attributes to uniquely identify one bean from another of thesame type. It is the primary key for the entry in the database. There are few specifications forthe primary key class. It must be serializable and have a public default constructor. It is alsorecommended that the class properly implement the hashCode() and equals(Object)() meth-ods. This is to simplify the management of primary keys by both the client and the container.
It is possible to use preexisting classes like java.lang.Integer, however you will develop asimple primary key class for the Quote Bean. Its source code is in Listing 12.7.
LISTING 12.7 QuotePk.java
import java.io.Serializable;
public class QuotePk implements Serializable {
public Integer id = null;
public QuotePk() {
}
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
209
LISTING 12.6 Continued
![Page 229: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/229.jpg)
public QuotePk(int pk) {
id = new Integer(pk);}
public boolean equals(Object obj) {
if (obj instanceof QuotePk) {
return id.equals(((QuotePk)obj).id);}else {
return false;}
}
public int hashCode() {
return id.hashCode();}
public void setId(Integer id) {
this.id = id;}
public Integer getId() {
return id;}
}
It is important to note that the attributes contained in the primary key class must be a subset ofthe container-managed fields when using container-managed persistence. This enables the con-tainer to match up the proper attributes from the bean class to those in the primary key class.
Bean ClassThis EJB’s bean class contains the business logic of the entity bean. It has similar rules to thebean class for a session bean, just many more of them. It implements all of the business meth-ods from the remote interface. It has methods that match each of the methods in the homeinterface. There is also a group of callback methods that are used by the container to managethe bean.
Servlet Fundamentals
PART I210
LISTING 12.7 Continued
![Page 230: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/230.jpg)
The business methods work just like those of the session bean. There must be a method thatexactly matches the signature for each method in the remote interface. Your accessor methodsshould be a breeze.
The methods that correspond to those in the home interface have rules slightly different whendealing with a bean written with bean-managed persistence versus container-managed persis-tence. Because the Quote Bean you are writing is a container-managed bean I will focus onthose concepts.
Creation, as you have seen, inserts an entry into the database. There is still a matchingejbCreate() method for each create() method in the home interface. In this method all ofthe bean attributes must be initialized based on the parameters passed in. With container-managed persistence, the database insert will be processed after the ejbCreate() method, so ifthe container-managed fields are not initialized properly the insert will reflect the corrupt data.At a minimum, the fields representing the primary key must be initialized. A bean written withbean-managed persistence must complete the database insert inside the ejbCreate().
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
211
For the Quote example in this chapter, you will manually supply a primary key duringcreation. This is not necessarily a good technique to use. Many algorithms and designpatterns can be used to obtain a primary key for entity bean creation.
NOTE
Another method is required in the creation process for entity beans. There must be anejbPostCreate() method with the same parameter list as each of the ejbCreate() methods.This method is used in case any processing is required after the database insert is complete andbefore the client has access to the bean.
You have now created the entity bean and have a new entry in the database. What happenswhen a client wants to find this entry later? There is a finder method in the home interfacethat the client will call, and because you are implementing a container-managed bean, you donot have to write any more code. You will define the select criteria during deployment to theapplication server. Writers of bean-managed beans must provide ejbFind<method> methods inthe Bean class to perform the database query. The source code for the QuoteBean is included inListing 12.8.
LISTING 12.8 QuoteBean.java
import javax.ejb.EntityBean;import javax.ejb.EntityContext;import javax.ejb.CreateException;import java.rmi.RemoteException;
![Page 231: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/231.jpg)
public class QuoteBean implements EntityBean{
protected EntityContext ctx = null;
public Integer id = null;public String customerName = null;public String phoneNumber = null;public Float loanAmount = null;public Float monthlyPayment = null;public Float interestRate = null;
public QuoteBean(){}
public QuotePk create(Integer id)throws RemoteException, CreateException {
this.id = id;return null;
}
public void ejbCreate(Integer id) {
}
public QuotePk create(Integer id, String name)throws RemoteException, CreateException {
this.id = id;this.customerName = name;return null;
}
public void ejbCreate(Integer id, String name) {
}
public void setCustomerName(String name)throws RemoteException {
customerName = name;}
Servlet Fundamentals
PART I212
LISTING 12.8 Continued
![Page 232: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/232.jpg)
public String getCustomerName()throws RemoteException {
return customerName;}
public void setPhoneNumber(String phone)throws RemoteException {
phoneNumber = phone;}
public String getPhoneNumber()throws RemoteException {
return phoneNumber;}
public void setLoanAmount(Float amt)throws RemoteException {
loanAmount = amt;}
public Float getLoanAmount()throws RemoteException {
return loanAmount;}
public void setMonthlyPayment(Float pmt)throws RemoteException {
monthlyPayment = pmt;}
public Float getMonthlyPayment()throws RemoteException {
return monthlyPayment;}
public void setInterestRate(Float rate)throws RemoteException {
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
213
LISTING 12.8 Continued
![Page 233: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/233.jpg)
interestRate = rate;}
public Float getInterestRate()throws RemoteException {
return interestRate;}
public void ejbActivate()throws javax.ejb.EJBException,java.rmi.RemoteException {
}
public void ejbPassivate()throws javax.ejb.EJBException,java.rmi.RemoteException {
}
public void ejbLoad()throws javax.ejb.EJBException,java.rmi.RemoteException {
}
public void ejbStore()throws javax.ejb.EJBException,java.rmi.RemoteException {
}
public void ejbRemove()throws javax.ejb.RemoveException,javax.ejb.EJBException,java.rmi.RemoteException {
}
public void setEntityContext(EntityContext ctx)throws javax.ejb.EJBException,java.rmi.RemoteException {
Servlet Fundamentals
PART I214
LISTING 12.8 Continued
![Page 234: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/234.jpg)
this.ctx = ctx;}
public void unsetEntityContext()throws javax.ejb.EJBException,java.rmi.RemoteException {
ctx = null;}
}
The class includes all of the information you want to store as a quote entry in the database.Each of the attributes in this class is a container-managed field. When you deploy the bean,you will have to map each of these attributes to a field in the database. Also, it is important toknow that every container-managed field must be specified as a public attribute. This is so thatthe container can handle them directly. This breaks some important encapsulation rules that aregenerally followed in object-oriented (OO) design, however, because clients always access thisclass through a remote interface, and it is not accessible to any code directly, it is all right todeclare the attributes as public.
A unique note on the ejbCreate() methods in a container-managed entity bean: Notice that itreturns null. This return value is actually ignored by the container, but it must return a value sothat the method signature matches that of a bean-managed bean. This way it is easier to switchbetween the two methods of persistence, so that all of the bean classes appear to be the same.
You also see several callback methods that were not present in the session bean class,ejbLoad() and ejbStore(). You might be able to guess what these methods do by theirnames. Each of these methods is more important when dealing with a bean-managed bean,however we will discuss them further in the section dealing with the lifecycle of entity beans,“Entity Bean Life Cycle.”
The Quote Bean class is a very simple container-managed bean. We have looked at some of thebasic concepts involved in writing an entity bean; however, to develop an enterprise-level sys-tem using EJB there is much more information required.
Deployment DescriptorWriting the deployment descriptor for an entity bean is similar to doing so for a session bean.The concept is the same, however the information required for an entity bean is different. Theinformation will go inside of the same ejb-jar.xml file. As a matter of fact all of the deploy-ment information for every EJB that is packaged into one jar file is included in the same ejb-jar.xml file. This includes both session and entity beans.
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
215
LISTING 12.8 Continued
![Page 235: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/235.jpg)
An <entity> entry in the structural section defines the makeup of the entity bean. The struc-tural information for our Quote Bean is listed in the following code snippet:
<entity><description>Describes a persistent quote.
</description><ejb-name>Quote</ejb-name><home>QuoteHome</home><remote>Quote</remote><ejb-class>QuoteBean</ejb-class><prim-key-class>QuotePk</prim-key-class><persistence-type>Container</persistence-type><reentrant>False</reentrant>
<cmp-field><field-name>id</field-name></cmp-field><cmp-field><field-name>customerName</field-name></cmp-field><cmp-field><field-name>phoneNumber</field-name></cmp-field><cmp-field><field-name>loanAmount</field-name></cmp-field><cmp-field><field-name>monthlyPayment</field-name></cmp-field><cmp-field><field-name>nterestRate</field-name></cmp-field>
</entity>
There are a couple of additions here. The first is the declaration of the primary key class. Justlike the other class declarations, this is the fully qualified Java classname for the primary keyclass.
The entry for persistence type must be present and specified whether the given entity bean’spersistence is container-managed or bean-managed. We discussed the difference between thesetwo in the earlier section, “Who Handles the Persistence?” The two possible values of for thisentry are Container and Bean.
Because you have decided to let the container manage the persistence for the Quote bean, youmust tell the container which fields in the entity bean it is required to manage. Each of theseattributes is declared inside the container-managed persistence entry, <cmp-field>. If youremember, each of these attributes was declared as public in the bean class so that the con-tainer has access to it.
A concept that we have not discussed yet is reentrance. The Quote Bean is defined as non-reentrant by specifying the false value for the <reentrant> tag. Reentrance defines whetherthe entity bean can be looped back into during the same execution context. An example ofreentrance would be: A client makes a call to entity bean A, bean A then invokes a method inbean B, and bean B tries to invoke a method in bean A and reenter it. When developing beansdeployed to enable reentrance, take this multithreading into consideration. If reentrance isdenied in the deployment descriptor, an exception will be thrown if the system tries to reenteran object.
Servlet Fundamentals
PART I216
![Page 236: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/236.jpg)
As with session beans, you can also define quite a bit about how the container should managethe entity bean in the application. This information is placed in the section that defines application-assembly information. Here you can define transactional attributes, set up clientroles, and assign permissions to bean methods, among other things.
Client View of an Entity BeanThe client of an entity bean is similar to the client to a session bean. The same statement canbe used to look up the home interface for the entity bean that you would like to use.
After you have the home interface, major differences appear to the client. There are more waysto obtain remote interfaces for an entity bean. Not only are there creation methods that enableyou to create a new entity bean, there are finder methods that allow you to look up existinginformation from the persistent storage.
Creation is an acceptable option for any entity bean that is not defined as read-only. Searching by use of finder methods is always an option. Every entity bean defines afindByPrimaryKey() method that enables the client to find a specific bean instance by itsunique identifier. Other finder methods can also be defined that search based on other criteria.
With the creation methods, the remote interface for the new bean instance is returned from themethod. Remember that finder methods can be defined to return either a single remote inter-face or a collection of remote interfaces.
The following code snippet gives an example of finding an entity bean:
Context initialContext = getInitialContext();QuoteHome quoteHome =
(QuoteHome)javax.rmi.PortableRemoteObject.narrow(initialContext.lookup(“Quote”), QuoteHome.class);
Quote = quoteHome.findByPrimaryKey(new QuotePk(1));
After the client has hold of a remote interface for an entity bean, it is business as usual. At thispoint the client can invoke methods that access the entity bean’s business logic. In many cases,these method calls represent database updates.
Entity Bean Life CycleThe life cycle for an entity bean instance is unique. Like session beans, it is driven by bothclient activity and actions performed by the application server. An entity bean instance canexist in three states.
The first state is the does not exist state. This is the state before the application server hasstarted. When the application server starts it will create a pool of entity beans. The number ofpooled beans is configurable during deployment. The bean instance will sit in the pooled stateuntil it is needed.
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
217
![Page 237: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/237.jpg)
A bean instance will be moved into the ready state when a client makes a call to one of thecreate() methods in the home interface. In the ready state, the bean instance is available tothe client for use. As with session beans, there is instance sharing of entity bean instances.They can be moved in and out of the pooled state when the application server feels it isacceptable to share the bean instance with another client. The application server uses the sameprocesses of passivation and activation that it does when dealing with session beans. Next weneed to talk about persistence. As we have discussed, an entity bean is tied to an entry in adatabase. When an instance of an entity bean is used during a transaction, it must be stored tothe database. There are also times when the instance needs to be filled with the information itrepresents in the database. The timing of these stores and loads is up to the application server.
For loading and storing the persistent information you must implement the ejbLoad() andejbStore() methods. As their names indicate, ejbLoad() loads information from the databaseinto the bean instance and ejbStore() stores the information back to the database.
For bean-managed beans the ejbStore() and ejbLoad() methods are very important. It is herethat the developer must provide the update and select SQL statements.
For any container-managed bean these methods provide the capability to do any processing ofthe data before it is stored or after it is loaded. The application server will call ejbStore()immediately before it stores the container-managed fields to the database. Consequently, it willalso call ejbLoad() immediately after loading the information into the bean instance again.We have left these two methods empty because there is no processing required for the QuoteBean.
Deploying Your EJB to Your Application ServerThe process of deploying your Enterprise JavaBeans is not regulated by any specification, so itis usually different for each application server. There are, however, some concepts that are thesame.
Packaging the jar FileFirst is packaging all of your classes and the deployment descriptor in a jar file. As we havediscussed before, all of the beans that are described in the ejb-jar.xml deployment descriptorwill be included within one jar file. Archive all of the class files as well as the ejb-jar.xmlfile into a jar file. The ejb-jar.xml file belongs in the meta-inf directory in the archive.
Many existing application servers provide a graphical deployment tool. Each one will appeardifferently. One of the major steps that is taken when deploying your jar file to any applicationserver is to run the EJB compiler over it. In many cases, the application server does this duringthe process of using its deployment tool. However, many developers choose to handle this dur-ing the build process of their beans. The EJB compiler will create all of the necessary client-and server-side classes required to process the remote-method invocations.
Servlet Fundamentals
PART I218
![Page 238: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/238.jpg)
The instructions provided here are for deploying to Allaire JRun 3.0. Instructions for installingJRun are found at the beginning of this chapter, in the section “Installing JRun.”
JRun configures all of its bean information by using a property file. This can be done with aseparate file for each bean. These property files can include all of the necessary information, tothe point where the standard ejb-jar.xml file is not necessary. An alternate route is to includeeach of the properties as an environment property in the ejb-jar.xml deployment descriptor.
We will split the difference and use a combination of these two methods. Your deploymentdescriptor will include all of the standard information, enabling you to deploy the beans to anycompliant application server. You will also include a property file for the other information toconfigure JRun. This information goes in a file named <bean>.properties; for the QuoteBean the file name is Quote.properties.
The database mappings for the container-managed Quote Bean is the most important informa-tion you have. This information is always defined differently when deploying to applicationservers. JRun requires you to write a SQL statement and bind the bean’s attributes to the SQLstatement. A different SQL statement is required for each type of database transaction: cre-ation, loading, storing, and finding.
The following code snippet contains an example for your load method. This is the databasetransaction that will be called when ejbLoad() is invoked by the container and the bean is tobe loaded from the information in the database.
ejipt.loadSQL= SELECT name, phone, amount, pmt, rateFROM quote WHERE id = ?
ejipt.loadSQL.source= bookDataSourceejipt.loadSQL.params= idejipt.loadSQL.paramTypes= INTEGERejipt.loadSQL.fields= customerName, phoneNumber,
loanAmount, monthlyPayment, interestRate
This block of properties includes all of the information necessary to load a Quote Bean fromthe database. It also defines which fields to load with the information returned from the query.The list of properties that JRun accepts is quite extensive. After this property file is completedfor each bean, include it in the jar file.
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
219
You might wonder about the benefits of container-managed persistence if you stillhave to write SQL. There are many pros and cons of both ways of persistence man-agement, but here all you must do is change a properties file to change the databasemapping or data source.
NOTE
![Page 239: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/239.jpg)
Deploying the jar FileNow you are ready to deploy your jar file. Start JRun’s administration server, and bring up theadministration application. Log in to the application using the username and password that youset up during installation. On the left side of the window, expand the entry in the tree for JRunDefault Server. Select the link at the bottom of the tree for Enterprise JavaBeans.
The main window now displays the main page for the EJB tool. On this page you can selectthe option for deployment, which then brings up the page for deploying EJB jar files. Click theBrowse button and choose the jar file that contains your EJBs. Also make sure that the selec-tion under JRun Server Name is JRun Default Server.
You will use a large text box for placing deployment properties to deploy a data source to thecontainer. This is the data source that the entity beans will use to interact with the database.The data source must be set up on your system and be associated with a valid database. OnMicrosoft Windows systems, you can add a data source by using the Data Sources (ODBC)tool under the Control Panel|Administrative Tools.
Add the following code snippet to JRun’s Deploy Properties text box:
bookDataSource.ejipt.sourceURL=jdbc:odbc:bookDataSourcebookDataSource.ejipt.sourceUser=bookDataSource.ejipt.sourcePassword=ejipt.jdbcSources=bookDataSource
The name of the data source, bookDataSource, is also the name specified for all of the SQLstatements in the individual bean’s properties files.
Now everything is ready for deployment. Click the Deploy button and wait. It takes a momentfor the EJB compiler to be run and for everything to be packaged. After it is finished you willreceive a message in red text on the left side of the page. Hopefully it tells you that deploy-ment was successful. After you have successfully deployed the beans, you must restart theJRun server.
Viewing Deployed BeansNow that your Enterprise JavaBeans are deployed, you can view all of the deployment infor-mation associated with each bean by expanding the navigation tree in the left panel of theadministration application. Expand the entry titled Enterprise JavaBeans, and it will list all ofyour deployed beans. Select the bean you want to view and all of the information will appearin the main window.
Servlets as EJB ClientsListing 12.9 contains the source for a simple servlet that accepts the necessary parameters, cal-culates the monthly loan payment, and then stores the quote to the database.
Servlet Fundamentals
PART I220
![Page 240: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/240.jpg)
LISTING 12.9 EJBTestServlet.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.lang.Class;import java.util.Hashtable;import java.rmi.RemoteException;import javax.rmi.PortableRemoteObject;import javax.ejb.CreateException;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;
public class EJBTestServlet extends HttpServlet {
// EJB Context factory for Allaire JRun.private static final String CTX_FACTORY =
“allaire.ejipt.ContextFactory”;private static final String CONTENT_TYPE = “text/html”;
protected Context ctx = null;
/**Initialize global variables*/public void init(ServletConfig config)
throws ServletException {
super.init(config);
// Establish the environment used to create// the initial contextHashtable env = new Hashtable();env.put(Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY);
try {
// Create a context with default credentialsctx = new InitialContext(env);
}catch (NamingException ex) {
throw new ServletException(“Naming Exception: creating”+ “ InitialContext - “ + ex.getMessage());
}}
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
221
![Page 241: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/241.jpg)
/**Process the HTTP Get request*/public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
// Get all of the information from the request.Integer months =
new Integer(request.getParameter(“months”));Float principal =
new Float(request.getParameter(“principal”));String custName = request.getParameter(“name”);String phoneNumber = request.getParameter(“phone”);Float payment = null;Float interestRate = null;
CalculateLoanHome clHome = null;CalculateLoan cl = null;QuoteHome quoteHome = null;Quote quote = null;try{
// Lookup the home interface for the CaluclateLoan BeanObject obj = ctx.lookup(“CalculateLoan”);clHome = (CalculateLoanHome)
PortableRemoteObject.narrow(obj,Class.forName(“CalculateLoanHome”));
// Create a new remote interfacecl = clHome.create();
// Calculate the monthly payment and get the// current interest rate.payment = cl.calcMonthlyPayment(months, principal);interestRate = cl.getCurrentInterestRate();
// Lookup the home interface for the Quote Beanobj = ctx.lookup(“Quote”);quoteHome = (QuoteHome)
PortableRemoteObject.narrow(obj,Class.forName(“QuoteHome”));
// Insert a new Quote into the database with the id of ‘1’quote = quoteHome.create(new Integer(1));// Update the database entry with all// of the necessary information.
Servlet Fundamentals
PART I222
LISTING 12.9 Continued
![Page 242: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/242.jpg)
quote.setCustomerName(custName);quote.setPhoneNumber(phoneNumber);quote.setLoanAmount(principal);quote.setMonthlyPayment(payment);quote.setInterestRate(interestRate);
}catch (ClassNotFoundException ex) {
throw new ServletException(ex);}catch (NamingException ex) {
throw new ServletException(ex);}catch (CreateException ex) {
throw new ServletException(ex);}catch (RemoteException ex) {
throw new ServletException(ex);}
// Create a simple screen as output from the servlet.response.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();out.println(“<html>”);out.println(“<head><title>EJBTestServlet</title></head>”);out.println(“<body>”);out.println(“<p>”);out.println(“The current interest rate is: “
+ interestRate + “<br>”);out.println(“For the loan amount of: “ +
principal + “<br>”);out.println(“Your monthly payment will be: “ + payment +
“<br>”);out.println(“</p>”);out.println(“</body></html>”);
}
/**Clean up resources*/public void destroy() {
Servlets and Enterprise JavaBeans
CHAPTER 12
12
SER
VLETS
AN
DE
NTER
PRISE
JAV
ABEA
NS
223
LISTING 12.9 Continued
![Page 243: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/243.jpg)
try {
ctx.close();}catch (NamingException ex) {
}}
}
To see this servlet in action, compile and copy the EJBTestServlet to the<SERVER_ROOT>/servers/default/default-app/WEB-INF/classes directory and open yourbrowser to the following URL:
http://localhost/servlet/EJBTestServlet?months=360&principle=250000&name=Bob&phone=(303)555-1212
SummaryEnterprise JavaBeans are a very robust and scalable option for building the business logic andpersistence layers for your Web application. They provide the ability to easily distribute theapplication without making any code changes. If it is architected correctly, the application’sinfrastructure is easily changed with a simple redeployment.
This chapter is a beginning look at Enterprise JavaBeans. EJBs are quite powerful and hope-fully you now have enough knowledge to further your understanding and develop enterpriselevel applications using Enterprise JavaBeans.
In the next chapter you will create a Controller servlet that will be at the core of our case studies.
Servlet Fundamentals
PART I224
LISTING 12.9 Continued
![Page 244: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/244.jpg)
CHAPTER
13A Servlet Controller
IN THIS CHAPTER• What Is a Controller? 226
• A Servlet Controller 226
• The Service Interface 229
• A Sample Service 230
![Page 245: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/245.jpg)
Servlet Fundamentals
PART I226
What Is a Controller?As we described in Chapter 1, “Web Applications and the Model View Controller (MVC)Design Pattern,” a Controller defines the way the user interface reacts to the user’s input. Forour purposes the Controller is the heart of our Web applications. The Controller is what deter-mines how your incoming requests are handled.
A Servlet ControllerYou will be implementing your Controller as a servlet. It will act as a factory to instantiate aclass that is determined by the request. We call these instantiated classes Services. They will befurther defined in the next section.
To create your servlet Controller, you need to create a servlet that takes the incoming request,parses the named Service, executes the created Service, and then forwards the results to a tar-get that is also included on the request. An example of a request containing these elements islisted below:
http://localhost/djs/servlet/Controller?service=Search&target=/➥searchresults.jsp
This requests that the Service Search be executed and the results be forwarded to thesearchresults.jsp page. Now let’s define a servlet that will represent this Controller. Listing13.1 contains the source for your Controller servlet.
LISTING 13.1 Controller.java
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
public class Controller extends HttpServlet {
/****/
public void init(ServletConfig config) throws ServletException {super.init(config);
}
/** The forward method forwards the results of the Service to the passed intarget.@throws VSException if an IOException or ServletException is thrown by theRequestDispatcher.
![Page 246: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/246.jpg)
*/protected void forward(HttpServletRequest request,HttpServletResponse response,String target) throws ServletException {try {ServletContext context = getServletContext();RequestDispatcher dispatcher =context.getRequestDispatcher(target);dispatcher.forward(request, response);
}catch (IOException ioe) {throw new ServletException(ioe.getMessage());
}}
/**Calls the <code>doPost()</code> with the request and response.*@param request the ServletEngine created HttpServletRequest.@param response the ServletEngine created HttpServletResponse.@throws ServletException if an Exception is not handled by the
➥web application.@throws IOException if there is an IO error during the request.*/
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{doPost(request, response);
}
/**Services all requests for the controllers. It expects a requestparameter, <code>service</code>, specifying the name of thetransaction that is to be executed.*@param request the ServletEngine created HttpServletRequest.@param response the ServletEngine created HttpServletResponse.@throws ServletException if an Exception is not handled by the
➥web application.@throws IOException if there is an IO error during the request.*/
public void doPost(HttpServletRequest request,HttpServletResponse response)
A Servlet Controller
CHAPTER 13
13
A S
ERV
LETC
ON
TRO
LLER227
LISTING 13.1 Continued
![Page 247: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/247.jpg)
throws ServletException, IOException {// Get the name of the Transaction to performString serviceName = request.getParameter(“service”);if (serviceName == null) {throw new ServletException(“No service named!”);
}
// Get the target of the requestString target = request.getParameter(“target”);if (target == null) {throw new ServletException(“No target named!”);
}
ServletContext context = getServletContext();// Create and execute an instance of the named servicetry {// Create an instance of the fully qualified Service ClassClass cls = Class.forName(serviceName);Service service = (Service)cls.newInstance();// Execute the Transactionservice.execute(request, response, context);
}catch (ClassNotFoundException ce) {throw new ServletException(ce.getMessage());
}catch (IllegalAccessException iae) {throw new ServletException(iae.getMessage());
}catch (Exception e) {throw new ServletException(e.getMessage());
}
// Forward the resultsforward(request, response, target);
}}
We need to discuss two sections of the Controller class. The first is the heart of the class,which is contained in the following code snippet:
// Create and execute an instance of the named servicetry {
// Create an instance of the fully qualified Service ClassClass cls = Class.forName(serviceName);
Servlet Fundamentals
PART I228
LISTING 13.1 Continued
![Page 248: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/248.jpg)
Service service = (Service)cls.newInstance();// Execute the Transactionservice.execute(request, response, context);}
This section of code acts as a Service factory. It parses the service parameter of the requestand creates the class dynamically by creating a new instance of the Service class using itsphysical name. It then calls the execute() method which, as you will see in the next section,is a method defined in the Service interface. This is where the business logic will exist.
The second section of the Controller that we need to examine is the forward() method. It isused to pass the results of the executed Service to a JSP for viewing. The key logic in the for-ward method can be found in the following code snippet:
try {ServletContext context = getServletContext();if ( !target.equals(“false”) ) {RequestDispatcher dispatcher =context.getRequestDispatcher(target);dispatcher.forward(request, response);}
}
In this section the Controller creates a RequestDispatcher object and calls its forward()method, passing it the request and response objects and the targeted JSP for viewing.
The Service InterfaceNow that we have defined the Controller, let’s define the Service interface that will act as theprototype of all services. For this interface you will have a single method, execute(), thataccepts the necessary parameters to receive and pass HTTP objects to and from the browser.The listing for the Service can be found in Listing 13.2.
LISTING 13.2 Service.java
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.ServletContext;
/**An interface that provides the base functionality for allServices.<p>
A Servlet Controller
CHAPTER 13
13
A S
ERV
LETC
ON
TRO
LLER229
LISTING 13.1 Continued
![Page 249: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/249.jpg)
To implement a <code>Service</code>, the <code>execute()</code>method is the only method that must be implemented.
**/public interface Service {
/**Single method to become a service.*@throws Exception if any exceptions need to be thrown backto the calling Controller.*/
public void execute(HttpServletRequest request,HttpServletResponse response,ServletContext context) throws Exception;}
As you can see, the Service interface contains a single method that takes anHttpServletRequest, HttpServletResponse, and a ServletContext. Now you can add a newService by simply implementing the Service’s execute() method.
A Sample ServiceTo see how easy this model is to extend, let’s add a sample Service. The source for this sampleService can be found in Listing 13.3.
LISTING 13.3 ExampleService.java
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import javax.servlet.ServletContext;
/**SearchService - This class provides an example of how to add aService. It must implement the Servlet interface.
*/public class ExampleService implements Service {
/**Empty constructor.*/
public ExampleService() {
Servlet Fundamentals
PART I230
LISTING 13.2 Continued
![Page 250: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/250.jpg)
}
/**This method is the implementation of the parents interface’sexecute() method. It contains the core functionality ofa Service.*/
public void execute(HttpServletRequest request,HttpServletResponse response,ServletContext context) throws Exception {// Do Something Hererequest.setAttribute(“example”, “Example Value”);
}}
The only thing you need to notice about this class is that it does implement the Service’sexecute() method. In this implementation it simply adds an attribute to the request with akey of example and a value of Example Value.
To see this Controller in action, you will need to compile the Controller.java,Service.java, and ExampleService.java files and move the resulting class files into the<SERVER_ROOT>/djs/WEB-INF/classes directory. After you have the Controller and its neces-sary support files you need to create a simple JSP that acts as the view. We have not yet cov-ered JSPs, but Listing 13.4 contains a simple JSP that outputs the request attribute example andits value.
LISTING 13.4 ExampleView.jsp
<HTML><HEAD><TITLE>Example View</TITLE></HEAD><BODY><H1>Example JSP View</H1>The value added to the request was <%= request.getAttribute(“example”) %></BODY></HTML>
A Servlet Controller
CHAPTER 13
13
A S
ERV
LETC
ON
TRO
LLER231
LISTING 13.3 Continued
![Page 251: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/251.jpg)
Now copy this JSP to the <SERVER_ROOT>/djs directory and open your browser to the follow-ing URL, broken here onto two lines:
http://localhost/djs/servlet/Controller?service=ExampleService&target=➥/ExampleView.jsp
You should see a screen similar to Figure 13.1.
Servlet Fundamentals
PART I232
FIGURE 13.1Output from our ExampleService.
SummaryThis chapter covered the Controller part of our server-side implementation of the MVC. Thisclass will be at the core of all of our case studies at the end of this text.
In the next chapter, we will begin our study of JavaServer Pages (JSPs), starting with anoverview of the JSP architecture.
![Page 252: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/252.jpg)
IN THIS PART14 JSP Overview and Architecture
15 JSP Implicit Objects
16 JSP Standard Actions
17 Using JavaBeans and JSP Scopes
18 Handling JSP Errors
19 Custom JSP Tag Libraries
JSP FundamentalsPART
II
![Page 253: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/253.jpg)
![Page 254: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/254.jpg)
CHAPTER
14JSP Overview and Architecture
IN THIS CHAPTER• What are JavaServer Pages? 236
• The Components of a JavaServer Page 237
![Page 255: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/255.jpg)
What are JavaServer Pages?JavaServer Pages, also known as JSPs, are a simple but powerful technology used to generatedynamic HTML on the server side. They are a direct extension of Java servlets and provide away to separate content generation from content presentation. The JSP engine is just anotherservlet that is mapped to the extension *.jsp. The following code contains a simple exampleof a JSP file:
<HTML><BODY>
<% out.println(“HELLO JSP WORLD”); %>
</BODY></HTML>
Its output would look similar to Figure 14.1.
JSP Fundamentals
PART II236
FIGURE 14.1Output of the JSP example.
You can see that this document looks like any other HTML document with some added tagscontaining Java code. The source code is stored in a file called HelloJSPWorld.jsp and copiedto the document directory of the Web server. When a request is made for this document, theserver recognizes the *.jsp extension and realizes that special handling is required. The first
![Page 256: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/256.jpg)
time the file is requested, it is compiled into a servlet object and stored in memory and the out-put is sent back to the requesting client. After the first request, the server checks to see whetherthe *.jsp file has changed. If it has not changed, then the server invokes the previously com-piled servlet object.
In this chapter and the next five chapters, we will be discussing how JSPs work and how to usethem. We will focus strictly on using JSPs as Views, as we discussed in Chapter 1, “WebApplications and the Model View Controller (MVC) Design Pattern.” Figure 14.2 shows thesteps of a JSP request graphically.
JSP Overview and Architecture
CHAPTER 14
14
JSP OV
ERV
IEWA
ND
AR
CH
ITECTU
RE
237
Compiled Servlet
Generated Servlet
JSP Page
2.
3.
Web Server
WebBrowser
1. Request
4. Response
3. The generated servlet is compiled and loaded.
4. The compiled servlet services the request and sends a response back to the client.
1. The client requests a JSP page.
2. The JSP engine compiles the JSP into a servlet.
FIGURE 14.2The steps of a JSP request.
A key thing to remember about JSPs is that they are just servlets that are createdfrom a combination of HTML text and Java source code. This means that they containall the functionality of a normal servlet.
NOTE
The Components of a JavaServer PageIn this section we cover the components that make up a JavaServer page. Each is discussed indetail in the following sections.
![Page 257: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/257.jpg)
DirectivesDirectives are JSP elements that provide global information about an entire JSP page. Anexample would be a directive that indicated the language to be used in compiling a JSP page.The syntax of a directive is as follows:
<%@ directive {attribute=”value”} %>
This states that, for this page directive, assign these values for these attributes. A directive cancontain n number of optional attribute/value pairs.
If we use our previous example for indicating the JSP language, the following line of codewould indicate that the JSP language to use would be Java:
<%@ page language=”java” %>
Three possible directives are currently defined by the JSP specification: page, include, andtaglib. Each one of these directives and their attributes, if applicable, are defined in the fol-lowing sections.
The page DirectiveThe page directive defines information that will be globally available for that JavaServer page.These page level settings will directly affect the compilation of the JSP. Table 14.1 defines theattributes for the page directive.
JSP Fundamentals
PART II238
Because the mandatory attributes are defaulted, you are not required to specify anypage directives.
NOTE
TABLE 14.1 The Attributes for the page Directive
Attribute Definition
language=”scriptingLanguage” This attribute tells the server what language will beused to compile the JSP file. Currently Java is theonly available language.
extends=”className” This attribute defines the parent class that the JSPgenerated servlet will extend from.
import=”importList” This attribute defines the list of packages that willbe available to this JSP. It will be a comma-sepa-rated list of package names.
![Page 258: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/258.jpg)
session=”true|false” This attribute determines whether the session datawill be available to this page. The default is true.
buffer=”none|size in kb” This attribute determines whether the output streamis buffered. The default value is 8KB.
autoFlush=”true|false” This attribute determines whether the output bufferwill be flushed automatically, or whether an excep-tion will be raised when the buffer is full. Thedefault is true, which states that the buffer shouldbe flushed automatically.
isThreadSafe=”true|false” This attribute tells the JSP engine that this page canservice more than one request at a time. By defaultthis value is true; if false, theSingleThreadModel is used.
info=”text” This attribute represents information about the JSPpage that can be accessed by the page’sServlet.getServletInfo() method.
errorPage=”error_url” This attribute represents the relative URL to the JSPpage that will handle exceptions.
isErrorPage=”true|false” This attribute states whether or not the JSP page isan errorPage. The default is false.
contentType=”ctinfo” This attribute represents the MIME type and char-acter set of the response.
The include DirectiveThe include directive is used to insert text and/or code at JSP translation time. The syntax ofthe include directive is as follows:
<%@ include file=”relativeURLspec” %>
The file that the file attribute points to can reference a normal text HTML file or it can refer-ence a JSP file, which will be evaluated at translation time.
JSP Overview and Architecture
CHAPTER 14
14
JSP OV
ERV
IEWA
ND
AR
CH
ITECTU
RE
239
TABLE 14.1 Continued
Attribute Definition
Currently the JSP 1.1 specification does not have a defined method for notifying theJSP engine that the included JSP file has changed.
NOTE
![Page 259: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/259.jpg)
The taglib DirectiveThe most recent version of the JSP specification defines a mechanism for extending the currentset of JSP tags. It does this by creating a custom set of tags called a tag library. That is whatthe taglib points to. The taglib directive declares that the page uses custom tags, uniquelynames the tag library defining them, and associates a tag prefix that will distinguish usage ofthose tags. The syntax of the taglib directive is as follows:
<%@ taglib uri=”tagLibraryURI” prefix=”tagPrefix” %>
The taglib attributes are described in Table 14.2.
TABLE 14.2 The Attributes for the taglib Directive
Attribute Definition
uri This attribute references a URI that uniquely names the set of custom tags.
prefix This attribute defines the prefix string used to distinguish a custom taginstance.
Standard ActionsJSP standard actions provide an abstraction that can be used to easily encapsulate commontasks. They typically create or act on objects, normally JavaBeans. The JSP technology pro-vides some standard actions. These actions are briefly defined in the following list; we’llexplore them in more detail in Chapter 16, “JSP Standard Actions”:
• <jsp:useBean> The <jsp:useBean> action associates an instance of a JavaBeandefined with a given scope and ID, using a newly declared scripting variable of the sameID.
• <jsp:setProperty> The <jsp:setProperty> action sets the value of a bean’sproperty.
• <jsp:getProperty> The <jsp:getProperty> action takes the value of the referencedbean instance’s property, converts it to a java.lang.String, and places it into theimplicit out object.
• <jsp:include> The <jsp:include> action provides a mechanism for including addi-tional static and dynamic resources in the current JSP page.
• <jsp:forward> The <jsp:forward> action enables the JSP engine to dispatch, at run-time, the current request to a static resource, servlet, or another JSP.
JSP Fundamentals
PART II240
![Page 260: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/260.jpg)
• <jsp:param> The <jsp:param> action is used to provide tag/value pairs of information,by including them as sub-attributes of the <jsp:include>, <jsp:forward>, and<jsp:plugin> actions.
• <jsp:plugin> The <jsp:plugin> action gives a JSP author the ability to generateHTML that contains the appropriate client browser–dependent constructs.
Implicit ObjectsWhen you write JSPs, you can use several implicit objects in JSP documents without declaringthem first. Table 14.3 lists the implicit objects provided by the JSP architecture. Each of theseimplicit objects has a class or interface type defined in a core Java Development Kit (JDK) orJava Servlet Development Kit (JSDK). We’ll discuss JSP’s implicit objects in greater detail inChapter 15, “JSP Implicit Objects.”
TABLE 14.3 The JSP Implicit Objects
ImplicitVariable Type Description Scope
application javax.servlet.Servlet Represents the servlet ApplicationContext context returned from a
call to getServletConfig().getContext()
config javax.servlet.Servlet Represents the Servlet PageConfig Config for this JSP
exception java.lang.Throwable Represents the uncaught PageThrowable that resulted from a call to the errorpage
out javax.servlet.jsp. Represents the JspWriter PageJspWriter object to the output stream
page java.lang.Object Represents the this Pageobject for this instance of the JSP
pageContext javax.servlet.jsp. Represents the page PagePageContext context for the JSP
request Protocol-dependent Represents the request Requestsubtype of either object that triggered the javax.servlet.Servlet requestRequest or javax.servlet.HttpServlet
Request
JSP Overview and Architecture
CHAPTER 14
14
JSP OV
ERV
IEWA
ND
AR
CH
ITECTU
RE
241
![Page 261: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/261.jpg)
response Protocol-dependent Represents the response Pagesubtype of either object that triggered the javax.servlet. requestServletResponse
or javax.servlet.HttpServletResponse
session javax.servlet. Represents the Sessionhttp.HttpSession session object, if any,
created for the client during an HTTP request
JSP ScriptingJSP scripting is a mechanism for embedding code fragments directly into an HTML page.Three scripting language elements are involved in JSP scripting. Each of these JSP scriptingelements has its appropriate location in the generated servlet. In this section we will look atthese elements and how together they will result in a complete servlet.
DeclarationsJSP declarations are used to declare variables and methods in the scripting language used in aJSP page. A JSP declaration should be a complete declarative statement.
JSP declarations are initialized when the JSP page is initialized. After the declarations havebeen initialized, they are available to other declarations, expressions, and scriptlets. The syntaxfor a JSP declaration is as follows:
<%! declaration %>
A sample variable declaration using this syntax is declared here:
<%! String name = new String(“BOB”); %>
A sample method declaration using the same syntax is declared as follows:
<%! public String getName() { return name; } %>
JSP Fundamentals
PART II242
TABLE 14.3 Continued
ImplicitVariable Type Description Scope
![Page 262: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/262.jpg)
To get a better understanding of declarations, let’s take the previous string declaration andactually use it to create a JSP document. The sample document would look similar to the fol-lowing code snippet:
<HTML><BODY>
<%! String name = new String(“BOB”); %>
</BODY></HTML>
When this document is initially requested, the JSP code is converted to servlet code and theprevious declaration is placed in the declaration section of the generated servlet. TheDeclarations section of the generated servlet would look similar to the following code snippet:
// begin [file=”D:\\Declarations.jsp”;from=(3,3);to=(3,37)]String name = new String(“BOB”); // end
ExpressionsJSP expressions are elements in a scripting language that are evaluated with the result beingconverted to a java.lang.String. After the string is converted, it is written to the current outJspWriter object.
JSP expressions are evaluated at HTTP request time, with the resulting string being inserted atthe expression’s referenced position in the .jsp file. If the resulting expression cannot be con-verted to a string then a translation time error will occur. If the conversion to a string cannot bedetected during translation, a ClassCastException will be thrown at request time. The syntaxof a JSP expression is as follows:
<%= expression %>
A code snippet containing a JSP expression is shown here:
Hello <B><%= getName() %></B>
To get a better understanding of expressions, let’s take this snippet and insert it into a simpleJSP document. The sample document would look similar to the following code snippet:
<HTML><BODY>
<%! String name = new String(“BOB”); %><%! public String getName() { return name; } %>
JSP Overview and Architecture
CHAPTER 14
14
JSP OV
ERV
IEWA
ND
AR
CH
ITECTU
RE
243
![Page 263: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/263.jpg)
Hello <B><%= getName() %></B>
</BODY></HTML>
When this document is initially requested, the JSP code is converted to servlet code and theprevious expression is resolved and placed in its referenced location of the generated servlet’s_jspService() method. The generated servlet would look similar to the following code snip-pet:
// beginout.write(“<HTML>\r\n<BODY>\r\n\r\n”);// end// beginout.write(“\r\n”);// end// beginout.write(“\r\n\r\nHello <B>”);// end// begin [file=”D:\\Expressions.jsp”;from=(6,12);to=(6,23)]out.print( getName() );// end// beginout.write(“</B>\r\n\r\n</BODY>\r\n</HTML>\r\n”);// end
ScriptletsScriptlets are what bring all the scripting elements together. They can contain any coding state-ments that are valid for the language referenced in the language directive. They are executed atrequest time and they can make use of declarations, expressions, and JavaBeans. The syntaxfor a scriptlet is as follows:
<% scriptlet source %>
During the initial request, the JSP scripting code is converted to servlet code and then com-piled and loaded into resident memory. The actual source code, which is found between script-let tags <% ... %>, is placed into the newly created servlet’s _jspService() method. See thefollowing sample JSP source:
<HTML><BODY>
<% out.println(“HELLO JSP WORLD”); %>
JSP Fundamentals
PART II244
![Page 264: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/264.jpg)
</BODY></HTML>
It has a very simple scriptlet section that will print HELLO JSP WORLD to the JspWriter implicitobject out. The actual servlet code, resulting from the initial request, would look similar to thefollowing code snippet:
public void _jspService(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
JspFactory _jspxFactory = null;PageContext pageContext = null;HttpSession session = null;ServletContext application = null;ServletConfig config = null;JspWriter out = null;Object page = this;String _value = null;
try {
if (_jspx_inited == false) {jspx_init();jspx_inited = true;
}jspxFactory = JspFactory.getDefaultFactory();response.setContentType(“text/html”);pageContext = _jspxFactory.getPageContext(this,request, response,“”, true, 8192, true);
application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();out = pageContext.getOut();
// beginout.write(“<HTML>\r\n<BODY>\r\n\r\n”);// end// begin [file=”D:\\HelloJsp.jsp”;from=(3,2);to=(3,35)]out.println(“HELLO JSP WORLD”); // end// beginout.write(“\r\n\r\n</BODY>\r\n</HTML>\r\n”);// end
JSP Overview and Architecture
CHAPTER 14
14
JSP OV
ERV
IEWA
ND
AR
CH
ITECTU
RE
245
![Page 265: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/265.jpg)
}catch (Exception ex) {
if (out.getBufferSize() != 0)out.clear();
pageContext.handlePageException(ex);}finally {
out.flush();jspxFactory.releasePageContext(pageContext);
}}
You don’t need to dig too deeply into this code, because it is generated for you. You just needto understand that it is being generated by the JSP engine and is the JSP equivalent to aservlet’s service() method. It is also important to know that the JSP engine creates a servletequivalent to the init() and destroy() methods.
SummaryIn this chapter we covered quite a bit of information. We also covered the basics of JSP and thecomponents of JSPs. You now should be able to create a JSP document and understand what ishappening behind the scenes during request time. You should also understand the process a JSPfile goes through when it is first requested.
In the next chapter we will discuss the implicit objects available in the JSP architecture.
JSP Fundamentals
PART II246
![Page 266: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/266.jpg)
CHAPTER
15JSP Implicit Objects
IN THIS CHAPTER• What are Implicit Objects? 248
• The request Object 249
• The response Object 250
• The pageContext Object 251
• The session Object 252
• The application Object 254
• The out Object 257
• The config Object 258
• The page Object 260
• The exception Object 260
![Page 267: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/267.jpg)
What are Implicit Objects?As a JSP author, you have access to certain objects that are available for use in JSP documentswithout being declared first. These objects are parsed by the JSP engine and inserted into thegenerated servlet as if you defined them yourself.
In reality the JSP engine recognizes the implicit object names and knows that they will bedeclared by, or passed into, the generated servlet. The following code is an example of a codesnippet containing a _jspService() method. As we continue with the rest of this chapter, wewill examine exactly where in this code each of the implicit objects is declared. We will alsolook at examples, where applicable, of how you can use each one of these objects.
public void _jspService(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
JspFactory _jspxFactory = null;PageContext pageContext = null;HttpSession session = null;ServletContext application = null;ServletConfig config = null;JspWriter out = null;Object page = this;String _value = null;
try {
if (_jspx_inited == false) {
_jspx_init();_jspx_inited = true;
}_jspxFactory = JspFactory.getDefaultFactory();response.setContentType(“text/html”);pageContext = _jspxFactory.getPageContext(this, request, response,“errorpage.jsp”, true, 8192, true);
application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();out = pageContext.getOut();
// beginout.write(“\r\n\r\n<html>\r\n <head>\r\n <title>Hello “ + “JSP</title>\r\n </head>\r\n <body>\r\n “);
JSP Fundamentals
PART II248
![Page 268: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/268.jpg)
// end// begin [file=”D:\\hello.jsp”;from=(7,6);to=(10,4)]
// Print a simple message in the client area.out.println(“<center><b>Hello!</b></center>”);
// end// beginout.write(“\r\n </body>\r\n</html>\r\n”);// end
}catch (Exception ex) {
if (out.getBufferSize() != 0)
out.clear();pageContext.handlePageException(ex);
}finally {
out.flush();_jspxFactory.releasePageContext(pageContext);
}}
JSP Implicit Objects
CHAPTER 15
15
JSP IMPLIC
ITO
BJEC
TS249
To run these examples, you will need to copy the JSP files from each of the followinglistings to the <SERVER_ROOT>/djs/ directory.
NOTE
The request ObjectThe implicit object request represents the javax.servlet.http.HttpServletRequest objectthat is passed into the generated _jspService() method. The HttpServletRequest interfacedefines an object that provides access to HTTP-protocol–specific header information sent bythe client. You can see how it is passed in the following code snippet:
public void _jspService(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
![Page 269: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/269.jpg)
One of the more common uses for the request object is to access request parameters. You cando this by calling the request object’s getParameter() method, which is inherited from itsparent javax.servlet.ServletRequest, with the parameter name you are looking for. It willreturn a string with the value matching the named parameter. An example of this can be foundin Listing 15.1.
LISTING 15.1 UseRequest.jsp
<%@ page errorPage=”errorpage.jsp” %>
<html><head><title>UseRequest</title>
</head><body><%
// Get the User’s Name from the requestout.println(“<b>Hello: “ + request.getParameter(“user”) + “</b>”);
%></body>
</html>
You can see that this JSP calls the request.getParameter() method passing in the parameteruser. This method looks for the key user in the parameter list and returns the value, if it isfound. Enter the following URL into your browser to see the results from this page:
http://localhost/djs/UseRequest.jsp?user=Bob
After loading this URL, you should see a screen similar to Figure 15.1.
The response ObjectThe JSP implicit object response represents the javax.servlet.http.HttpServletResponseobject, which defines an object that provides the JSP with the capability to manipulate HTTP-protocol–specific header information and return data to the client. The response object ispassed into the generated _jspService() method. You can see how it is passed in the follow-ing code snippet:
public void _jspService(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
The most common use for the response object is writing HTML output back to the clientbrowser. You would normally call the response.getWriter() method, but the JSP APIabstracts you from this by providing the implicit out object, which will be discussed in a latersection of this chapter.
JSP Fundamentals
PART II250
![Page 270: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/270.jpg)
FIGURE 15.1Output from UseRequest.jsp.
The pageContext ObjectThe pageContext object provides access to the namespaces associated with a JSP page. It alsoprovides accessors to several other JSP implicit objects.
An instance of an implementation-dependent pageContext is created by a JSP implementationclass at the beginning of the generated servlet’s _jspService() method. It is created throughan implementation-dependent JspFactory. An example of the pageContext object’s creationand its use in the creation of other implicit objects is shown in the following code snippet:
pageContext = _jspxFactory.getPageContext(this, request, response,“errorpage.jsp”, true, 8192, true);
application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();out = pageContext.getOut();
You can see by examining the previous code snippet that the pageContext is used often in thegenerated servlet. However it is not often used directly in a JavaServer page. The exception tothis is in the creation of custom tags, which we will examine in Chapter 19, “Custom JSP TagLibraries.”
JSP Implicit Objects
CHAPTER 15
15
JSP IMPLIC
ITO
BJEC
TS251
![Page 271: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/271.jpg)
The session ObjectThe implicit session object holds a reference to a javax.servlet.http.HttpSession object.The HttpSession object is used to store objects between client requests. It provides an almoststate-full HTTP interactivity. The session object is initialized by a call to thepageContext.getSession() method in the generated servlet. The code snippet that initializesthe session is as follows:
session = pageContext.getSession();
An example of using the implicit session object can be found in Listing 15.2.
LISTING 15.2 UseSession.jsp
<%@ page errorPage=”errorpage.jsp” %>
<html><head><title>UseSession</title>
</head><body><%// Try and get the current count from the sessionInteger count = (Integer)session.getAttribute(“COUNT”);
// If COUNT is not found, create it and add it to the sessionif ( count == null ) {
count = new Integer(1);session.setAttribute(“COUNT”, count);
}else {
count = new Integer(count.intValue() + 1);session.setAttribute(“COUNT”, count);
} out.println(“<b>Hello you have visited this site: “+ count + “ times.</b>”);
%></body>
</html>
JSP Fundamentals
PART II252
![Page 272: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/272.jpg)
You should now move this JSP to the <SERVER_ROOT>/djs/ directory and open your browser tothe following URL:
http://localhost/djs/UseSession.jsp
You should see a page similar to Figure 15.2.
JSP Implicit Objects
CHAPTER 15
15
JSP IMPLIC
ITO
BJEC
TS253
FIGURE 15.2Output from UseSession.jsp.
Now go ahead and click your reload button a few times. The count should increment withevery reload.
You should also note that the session object has session scope; therefore it will nothold the objects added to it after its expiration.
NOTE
![Page 273: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/273.jpg)
The application ObjectThe application object holds a reference to the javax.servlet.ServletContext retrievedfrom the servlet configuration. The following code snippet, from the JSP’s generated servlet,shows how the application object is initialized:
pageContext = _jspxFactory.getPageContext(this, request, response,“errorpage.jsp”, true, 8192, true);
application = pageContext.getServletContext();
You can see that the generated servlet simply gets a reference to the current ServletContextand stores it in the application object. The application object has application scope, whichmeans that it is available to all JSPs until the JSP engine is shut down.
The application object is most often used to access environment information. Some of themore common pieces of information accessed by the application object are objects that arestored in the ServletContext. These objects are stored there so that they will be available thewhole time the servlet engine is running.
The ServletContext is a great place to share objects between JSPs and servlets. In the follow-ing example, you use the application object to store and access our application’s specificinformation. You will do this by creating a JSP that creates a Properties object with the fol-lowing properties:
PROP1:VAL1PROP2:VAL2PROP3:VAL3
You can see that your property object contains three name:value pairs. Next, you will create aJSP that checks the application for a reference to the Properties object, by calling theapplication.getAttribute() method with a key that represents the object in theServletContext. If you do not find the referenced object, you will create it and store theobject in the ServletContext using the application.setAttribute() method. Now theProperties object is available to other JSPs and servlets. Listing 15.3 contains this JSP.
LISTING 15.3 StoreInApplication.jsp
<%@ page errorPage=”errorpage.jsp” %><%@ page import=”java.util.Properties, java.util.Enumeration” %><html><head><title>UseApplication</title>
</head><body>
JSP Fundamentals
PART II254
![Page 274: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/274.jpg)
<%
// Check the application for the shared propertiesProperties props = (Properties)application.getAttribute(“SPROPERTIES”);
if ( props == null ) {
// If the Properties were not in the application// load them and put them in the applicationprops = new Properties();
props.setProperty(“PROP1”, “VAL1”);props.setProperty(“PROP2”, “VAL2”);props.setProperty(“PROP3”, “VAL3”);
application.setAttribute(“SPROPERTIES”, props);}
%></body>
</html>
Now you need to create a servlet that will use the shared Properties object that is stored inthe ServletContext. Listing 15.4 contains this JSP.
LISTING 15.4 GetFromApplication.jsp
<%@ page errorPage=”errorpage.jsp” %><%@ page import=”java.util.Properties, java.util.Enumeration” %>
<html><head><title>Get From Application</title>
</head><body><%
// Check the application for the shared propertiesProperties props =(Properties)application.getAttribute(“PROPERTIES”);
if ( props == null ) {
JSP Implicit Objects
CHAPTER 15
15
JSP IMPLIC
ITO
BJEC
TS255
LISTING 15.3 Continued
![Page 275: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/275.jpg)
out.println(“Could not get the Properties from the application!”);}else {
// The properties were found in the application, iterate over themEnumeration enum = props.propertyNames();
while ( enum.hasMoreElements() ) {
String name = (String)enum.nextElement();out.println(“<B>” + name + “:</b>”+ props.getProperty(name) + “<br>”);
} }
%></body>
</html>
As you can see, the GetFromApplication.jsp first checks the application object for a refer-ence to the Properties. If it cannot find the object, it writes a message to the implicit outobject stating this. If it does find the Properties object, GetFromApplication.jsp iteratesover the object, printing out the name:value pairs.
Testing the JSPsTo test your JSPs, perform the following steps:
1. Copy all the files into the <SERVER_ROOT>/djs/ directory.
2. Open your browser to the following URL:
http://localhost/djs/StoreInApplication.jsp
JSP Fundamentals
PART II256
LISTING 15.4 Continued
When you open your browser during step 2, no output will be displayed in thebrowser.
NOTE
3. Then, open your browser to the following URL:
http://localhost/djs/GetFromApplication.jsp
When you open your browser in step 3, you should see a page similar to Figure 15.3.
![Page 276: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/276.jpg)
FIGURE 15.3Output from GetFromApplication.jsp.
The out ObjectThe implicit out object is a very simple object that represents a reference to a JspWriter,which is derived from a java.io.Writer. You can see how the out object is initialized in thefollowing code snippet that was pulled from a JSP’s generated servlet:
JspWriter out = null;Object page = this;String _value = null;
try {
if (_jspx_inited == false) {
_jspx_init();_jspx_inited = true;
}_jspxFactory = JspFactory.getDefaultFactory();response.setContentType(“text/html”);pageContext = _jspxFactory.getPageContext(this, request, response,“errorpage.jsp”, true, 8192, true);
JSP Implicit Objects
CHAPTER 15
15
JSP IMPLIC
ITO
BJEC
TS257
![Page 277: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/277.jpg)
application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();out = pageContext.getOut();
You have seen many examples of how the out object is used. It is used to write into the outputstream that is delivered back to the client. The most common use is to use the out.println()method, passing it HTML text that will be displayed in the client’s browser. Most of your out-put will be presented to the client in the out.println() method. Listing 15.5 contains anexample of how you use the implicit out object.
LISTING 15.5 UseOut.jsp
<%@ page errorPage=”errorpage.jsp” %>
<html><head><title>Use Out</title>
</head><body><%// Print a simple message using the implicit out object.out.println(“<center><b>Hello!</b></center>”);
%></body>
</html>
Copy this file to the <SERVER_ROOT>/djs/ directory and then open your browser to the follow-ing URL:
http://localhost/djs/UseOut.jsp
You should now see a page similar to Figure 15.4.
The config ObjectThe implicit config object represents the ServletConfig, which defines a servlet-engine–generated object that contains configuration information. The configuration information thatthis servlet will have access to is the ServletContext object, which describes the contextwithin which the generated servlet will be running. You can see how the config object is ini-tialized in the following code snippet:
ServletConfig config = null;JspWriter out = null;Object page = this;
JSP Fundamentals
PART II258
![Page 278: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/278.jpg)
String _value = null;
try {
if (_jspx_inited == false) {
_jspx_init();_jspx_inited = true;
}_jspxFactory = JspFactory.getDefaultFactory();response.setContentType(“text/html”);pageContext = _jspxFactory.getPageContext(this, request, response,“errorpage.jsp”, true, 8192, true);
application = pageContext.getServletContext();config = pageContext.getServletConfig();
Most often, you will not need to use the config object, because you will already have accessto the ServletContext through the implicit application object.
JSP Implicit Objects
CHAPTER 15
15
JSP IMPLIC
ITO
BJEC
TS259
FIGURE 15.4Output from UseOut.jsp.
![Page 279: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/279.jpg)
The page ObjectThe page object is just as it sounds, a reference to the current instance of the JSP. It is initial-ized to the actual this reference by the generated servlet. The actual code snippet that doesthis follows:
Object page = this;
You use the page object just as you would a this object, to reference the current instance ofyour generated servlet.
The exception ObjectThe implicit exception object only exists in a defined errorPage. It holds a reference to theuncaught exception that caused the error page to be invoked. You can find a complete descrip-tion of the errorPage mechanism, including use of the implicit exception object in Chapter18, “Handling JSP Errors.”
SummaryIn this chapter we covered the JSP implicit objects and how they are commonly used. We alsotalked about how these objects are created in the JSP’s generated servlet. You should now havea clear understanding of the implicit objects that are available to you and what they represent.
In the next chapter, we will cover using the JSP’s standard actions.
JSP Fundamentals
PART II260
![Page 280: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/280.jpg)
CHAPTER
16JSP Standard Actions
IN THIS CHAPTER• What Are Standard Actions? 262
• JavaBean Standard Actions 262
• Other Standard Actions 268
![Page 281: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/281.jpg)
JSP Fundamentals
PART II262
What Are Standard Actions?JSP standard actions are predefined tags that can be used to easily encapsulate commonactions. There are two types of JSP standard actions: those related to JavaBean functionalityand all other standard actions. Each group will be defined and used, where appropriate, in thefollowing sections.
JavaBean Standard ActionsThree standard actions are defined to help integrate JavaBeans into JSPs: <jsp:useBean>,<jsp:setProperty>, and <jsp:getProperty>.
The <jsp:useBean> Standard ActionThe first standard action is <jsp:useBean>. It associates an instance of a JavaBean definedwith a given scope and id using a newly declared scripting variable of the same id.
The <jsp:useBean> action is very flexible. Its exact semantics depend on the values of thegiven attributes. The basic action tries to find an existing object using the same id and scope.If it does not find an existing instance, it will attempt to create the object. It is also possible touse this action only to give a local name to an object defined elsewhere, as in another JSP pageor in a servlet. This can be done by using the type attribute, and by not providing the class orthe beanName attribute. The syntax of the <jsp:useBean> action is as follows:
<jsp:useBean id=”name”scope=”page|request|session|application”typeSpec>body
</jsp:useBean>
typeSpec ::=class=”className” |class=”className” type=”typeName” |type=”typeName” class=”className” |beanName=”beanName” type=”typeName” |type=”typeName” beanName=”beanName” |type=”typeName”
Table 16.1 contains the attributes of the <jsp:useBean> action.
TABLE 16.1 The Attributes for the <jsp:useBean> Action
Attribute Definition
id This attribute represents the identity of the instance of the object in thespecified scope. The name is case sensitive and must satisfy the currentscripting language’s variable naming conventions.
![Page 282: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/282.jpg)
TABLE 16.1 Continued
Attribute Definition
scope The scope attribute represents the life of the object. The scope options arepage, request, session, and application.
class The fully qualified classname that defines the implementation of theobject. The classname is case sensitive.
beanName This attribute references the name of the bean, as expected to be instanti-ated by the instantiate() method of the java.beans.Beans class.
type The type attribute specifies the type of scripting variable defined. If thisattribute is unspecified, then the value is the same as the value of theclass attribute.
The <jsp:setProperty> Standard ActionThe second standard action to help integrate JavaBeans into JSPs is <jsp:setProperty>. Itsets the value of a bean’s property. Its name attribute denotes an object that must already bedefined and in scope. The syntax for the <jsp:setProperty> action is as follows:
<jsp:setProperty name=”beanName” prop_expr />
In the preceding syntax, the name attribute represents the name of the bean whose property youare setting and prop_expr can be represented in the following syntax:
property=”*” |property=”propertyName” |property=”propertyName” param=”parameterName” |property=”propertyName” value=”propertyValue”
Table 16.2 contains the attributes and their descriptions for the <jsp:setProperty> action.
TABLE 16.2 The Attributes for the <jsp:setProperty> Action
Attribute Definition
name This attribute represents the name of the bean instance defined by a<jsp:useBean> action or some other action.
property This attribute represents the bean property for which you want to set avalue. If you set propertyName to an asterisk (*), then the action will iter-ate over the current ServletRequest parameters, matching parameternames and value types to property names and setter method types, and set-ting each matched property to the value of the matching parameter. If aparameter has an empty string for a value, the corresponding property isleft unmodified.
JSP Standard Actions
CHAPTER 16
16
JSPS
TAN
DA
RD
AC
TION
S263
![Page 283: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/283.jpg)
TABLE 16.2 Continued
Attribute Definition
param The param attribute represents the name of the request parameter whosevalue you want to set the named property to. A <jsp:setProperty> actioncannot have both param and value attributes referenced in the same action.
value The value attribute represents the value assigned to the named bean’sproperty.
The <jsp:getProperty> Standard ActionThe last standard action that references JavaBeans in JSPs is <jsp:getProperty>. It takes thevalue of the referenced bean instance’s property, converts it to a java.lang.String, and placesit into the implicit out object. The referenced bean instance must be defined and in scopebefore this action references it. The syntax for the <jsp:getProperty> action is as follows:
<jsp:getProperty name=”name” property=”propertyName” />
Table 16.3 contains the attributes and their descriptions for the <jsp:getProperty> action.
TABLE 16.3 The Attributes for the <jsp:getProperty> Action
Attribute Definition
name This attribute represents the name of the bean instance from which theproperty is obtained, defined by a <jsp:useBean> action or some otheraction.
property This attribute represents the bean property for which you want to get avalue.
A JSP Example Using JavaBeansIn this example, you’ll use a simple JavaBean that acts as a counter. It has a single int prop-erty, count, which holds the current number of times the bean’s property has been accessed. Italso contains the appropriate methods for getting and setting this property. Listing 16.1 con-tains the source code for the Counter bean.
LISTING 16.1 Counter.java
public class Counter {
// Initialize the bean on creationint count = 0;
JSP Fundamentals
PART II264
![Page 284: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/284.jpg)
LISTING 16.1 Continued
// Parameterless Constructorpublic Counter() {
}
// Property Getterpublic int getCount() {
// Increment the count property, with every requestcount++;
return this.count;}
// Property Setterpublic void setCount(int count) {
this.count = count;}
}
Now that you have defined your bean, let’s look at how to integrate it into a JSP. Listing 16.2contains the JSP that will use the Counter bean.
LISTING 16.2 BeanCounter.jsp
<HTML><HEAD><TITLE>JSP Bean Example</TITLE></HEAD>
<BODY>
<!-- Set the scripting language to java --><%@ page language=”java” %><%@ page import=”Counter” %>
<!-- Instantiate the Counter bean with an id of “counter” --><jsp:useBean id=”counter” scope=”session” class=”Counter” />
<!-- Set the bean’s count property to the value of --><!-- the request parameter “count”, using the --><!-- jsp:setProperty action. --><jsp:setProperty name=”counter” property=”count” param=”count” />
JSP Standard Actions
CHAPTER 16
16
JSPS
TAN
DA
RD
AC
TION
S265
![Page 285: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/285.jpg)
LISTING 16.2 Continued
<%
// write the current value of the property countout.println(“Count from scriptlet code : “+ counter.getCount() + “<BR>”);
%>
<!-- Get the bean’s count property, --><!-- using the jsp:getProperty action. -->Count from jsp:getProperty :<jsp:getProperty name=”counter” property=”count” /><BR>
</BODY></HTML>
In the BeanCounter.jsp page, you perform five actions that give examples of using beans in aJSP. You first tell the JSP engine that the scripting language you are using is Java, with the fol-lowing snippet:
<%@ page language=”java” %>
You then create an instance of the class Counter, with a scope of session, and assign it an idof counter. You do this using the standard action <jsp:useBean>. Now you can reference thisbean, by using the name counter, throughout the rest of your JSP. The code snippet that cre-ates the bean is as follows:
<jsp:useBean id=”counter” scope=”session” class=”Counter” />
The third action sets the bean’s count property to the value of the count parameter, if it existsin the request. The code snippet that performs this action is as follows:
<!-- Set the bean’s count property to the value of --><!-- the request parameter “count”, using the --><!-- jsp:setProperty action. --><jsp:setProperty name=”counter” property=”count” param=”count” />
In this snippet, you use the <jsp:setProperty> standard action to set the value of the countproperty. You do this by setting the name attribute to the name of the bean you want to refer-ence, the property attribute to the name of the property to be set, and the param attribute to thename of the request parameter you want to set the property to.
JSP Fundamentals
PART II266
![Page 286: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/286.jpg)
The final two actions you perform show how you can get the current value of a bean’s prop-erty. The first of these two examples uses a scriptlet. It simply accesses the bean by its refer-enced name counter and calls the getCount() method, just as any other Java code would. Thescriptlet snippet is listed here:
<%
// write the current value of the property countout.println(“Count from scriptlet code : “+ counter.getCount() + “<BR>”);
%>
The second example uses the <jsp:getProperty> standard action, which requires the name ofthe bean and the property to be accessed. The action takes the attribute, calls the appropriateaccessor, and embeds the results directly into the resulting HTML document, as shown in thefollowing:
<!-- Get the bean’s count property, --><!-- using the jsp:getProperty action. -->Count from jsp:getProperty :<jsp:getProperty name=”counter” property=”count” /><BR>
Notice that the second reference to the count property results in a value that is one greater thatthe first reference. This is because both methods of accessing the count property result in acall to the getCount() method, which increments the value of count. To see this in actioncompile the Counter class, move it to the <SERVER_ROOT>/djs/WEB-INF/classes directory,and copy the BeanCounter.jsp file to the <SERVER_ROOT>/djs/ directory. Now you shouldopen your browser to the following URL:
http://localhost/djs/BeanCounter.jsp
Another thing you might want to try is changing the value of the <jsp:useBean> action’sscope attribute. This will affect the life of the bean and the value of the count property in theprevious example. We will examine bean scope further in the Chapter 17, “Using JavaBeansand JSP Scopes.” The available options for the scope attribute are described in Table 16.4.
TABLE 16.4 The scope Values for the <jsp:useBean> Action
Value Definition
page Objects with page scope are accessible only within the page where theywere created. References to an object with page scope will be releasedwhen the response is sent back to the client or the request is forwarded toanother resource. Objects with page scope are stored in the pagecontext.
JSP Standard Actions
CHAPTER 16
16
JSPS
TAN
DA
RD
AC
TION
S267
![Page 287: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/287.jpg)
TABLE 16.4 Continued
Value Definition
request Objects with request scope are accessible only within pages processingthe same request in which the object was created. References to the objectwill be released after the request is processed completely. If the request isforwarded to a resource in the same runtime, the object is still in scope.References to objects with request scope are stored in the requestobject.
session Objects with session scope are accessible only within pages processingrequests that are in the same session as the one in which the bean was cre-ated. It is illegal to define an object with session scope within a page ifthat page’s page directive has the session attribute set equal to false.References to the session objects will be released after their associatedsessions end. Objects with session scope are stored in the session objectassociated with the page activation.
application Objects with application scope are accessible within pages processingrequests that are in the same application space as the page in which theywere created. References to the object will be released when the runtimeenvironment reclaims the ServletContext. Objects with applicationscope can be defined and reached within pages that are not session-aware.References to objects with application scope are stored in the application object associated with the page.
Other Standard ActionsThe remaining predefined standard actions include <jsp:param>, <jsp:include>,<jsp:forward>, and <jsp:plugin>. Each of these tags is described in detail in the followingsections.
The <jsp:param> Standard ActionThe <jsp:param> action is used to provide tag/value pairs of information, by including them assub-attributes of the <jsp:include>, <jsp:forward>, and the <jsp:plugin> actions. The syn-tax of the <jsp:param> action is as follows:
<jsp:param name=”paramName” value=”paramValue”/>
Table 16.5 contains the attributes and their descriptions for the <jsp:param> action.
JSP Fundamentals
PART II268
![Page 288: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/288.jpg)
TABLE 16.5 Attributes for the <jsp:param> Action
Attribute Definition
name This attribute represents the name of the parameter being referenced.
value This attribute represents the value of the named parameter.
The <jsp:include> Standard ActionThe <jsp:include> action provides a mechanism for including additional static and dynamicresources in the current JSP page. The syntax for this action is as follows:
<jsp:include page=”urlSpec” flush=”true” />
and
<jsp:include page=”urlSpec” flush=”true”><jsp:param ... />
</jsp:include>
The first syntax description does a request-time inclusion, whereas the second contains a list ofparam sub-elements that are used to argument the request for the purpose of inclusion. Table16.6 contains the attributes and their descriptions for the <jsp:include> action.
TABLE 16.6 The Attributes for the <jsp:include> Action
Attribute Definition
page This attribute represents the relative URL of the resource to be included.
flush This attribute represents a mandatory Boolean value stating whether or not thebuffer should be flushed. Currently, true is the only valid value for this attribute.
To further explain how the <jsp:include> works, we will create two JSPs. The first, which willbe the included JSP, will act as the header of the second JSP document. This JSP will search therequest for an employee’s name and title. Listing 16.3 contains the source for your first JSP.
LISTING 16.3 header.jsp
<%// Get the Employee’s Name from the requestout.println(“<b>Employee: </b>” + request.getParameter(“employee”));
// Get the Employee’s Title from the requestout.println(“<br><b>Title: </b>” + request.getParameter(“title”));
%>
JSP Standard Actions
CHAPTER 16
16
JSPS
TAN
DA
RD
AC
TION
S269
![Page 289: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/289.jpg)
The second JSP will include the header.jsp in the top row of its table and pass it theemployee’s name and title, using the <jsp:param> standard action. It will then include somestatic text indicating the employee’s current statistics. Listing 16.4 contains the source code foryour second JSP.
LISTING 16.4 EmployeeInfo.jsp
<%@ page errorPage=”errorpage.jsp” %><html><head><title>Employee Information</title>
</head><body><table width=”100%” cellspacing=”0”><tr><td><jsp:include page=”header.jsp” flush=”true”><jsp:param name=”employee” value=”Bob”/><jsp:param name=”title” value=”Engineer”/>
</jsp:include></td>
</tr><tr bgcolor=”lightgrey”><td>Years of Employment:
</td><td>7
</td></tr><tr><td>Supervisor:
</td><td>Joe
</td></tr><tr bgcolor=”lightgrey”><td>Salary:
</td><td>$93,000
</td></tr>
JSP Fundamentals
PART II270
![Page 290: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/290.jpg)
LISTING 16.4 Continued
<tr><td>Email:
</td><td>[email protected]
</td></tr>
</table></body>
</html>
To see the <jsp:include> in action, copy both of these JSPs to the <SERVER_ROOT>/djs/directory and open your browser to the following URL:
http://localhost/djs/EmployeeInfo.jsp
You will now see a page similar to Figure 16.1.
JSP Standard Actions
CHAPTER 16
16
JSPS
TAN
DA
RD
AC
TION
S271
FIGURE 16.1The output from EmployeeInfo.jsp.
![Page 291: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/291.jpg)
To see how this really works, let’s take a look at the generated servlet’s _jspService()
method, which is included in the following code snippet:
public void _jspService(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
JspFactory _jspxFactory = null;PageContext pageContext = null;HttpSession session = null;ServletContext application = null;ServletConfig config = null;JspWriter out = null;Object page = this;String _value = null;
try {
if (_jspx_inited == false) {
_jspx_init();_jspx_inited = true;
}_jspxFactory = JspFactory.getDefaultFactory();response.setContentType(“text/html”);pageContext = _jspxFactory.getPageContext(this, request, response,
“errorpage.jsp”, true, 8192, true);
application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();out = pageContext.getOut();
// beginout.write(“\r\n\r\n<html>\r\n <head>\r\n <title>Employee “ +“Information</title>\r\n </head>\r\n <body>\r\n “ +“<table width=\”100%\” cellpadding=\”0\”>\r\n <tr>\r\n” +“ <td>\r\n “);
// end// begin [file=”C:\\EmployeeInfo.jsp”;from=(10,10);to=(13,24)]{String _jspx_qStr = “”;out.flush();_jspx_qStr = _jspx_qStr + “?employee=” + “Bob”;_jspx_qStr = _jspx_qStr + “&title=” + “Engineer”;pageContext.include(“header.jsp” + _jspx_qStr);
JSP Fundamentals
PART II272
![Page 292: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/292.jpg)
}// end// beginout.write(“\r\n </td>\r\n </tr>\r\n” +“ <tr bgcolor=\”lightgrey\”>\r\n <td>\r\n “ +“ Years of Employment:\r\n </td>\r\n <td>\r\n “ +“ 7\r\n </td>\r\n </tr>\r\n </table>\r\n “ +“</body>\r\n</html>\r\n”);
// end
}catch (Exception ex) {
if (out.getBufferSize() != 0)
out.clear();pageContext.handlePageException(ex);
}finally {
out.flush();_jspxFactory.releasePageContext(pageContext);
}}
The include is actually taking place in the following code snippet from the _jspService()method mentioned earlier:
{String _jspx_qStr = “”;out.flush();_jspx_qStr = _jspx_qStr + “?employee=” + “Bob”;_jspx_qStr = _jspx_qStr + “&title=” + “Engineer”;pageContext.include(“header.jsp” + _jspx_qStr);
}
You can see that the string _jspx qStr is created and then the parameter list, which was cre-ated using the <jsp:param> standard action, is appended to it. This is what forms the querystring that will be passed to your included JSP. When the string is ready, it is passed to thepageContext.include() method with the name of the JSP to include. Now the included JSPcan parse the passed-in query string.
As you can see, the generated servlet does not directly contain the output from the includedJSP. This is because the output is included during request-time. This makes it possible for youto make changes to the included JSP without restarting the JSP engine.
JSP Standard Actions
CHAPTER 16
16
JSPS
TAN
DA
RD
AC
TION
S273
![Page 293: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/293.jpg)
To see this in action, open the included header.jsp and make some changes to it. Now reloadthe EmployeeInfo.jsp. Your changes should take effect immediately. This is the differencebetween the include directive and the <jsp:include> standard action. To propagate changesusing the include directive, you would have needed to restart the JSP engine. Using the<jsp:include> directive relieves you of this need.
The <jsp:forward> Standard ActionThe <jsp:forward> action enables the JSP engine to dispatch, at runtime, the current requestto a static resource, servlet, or another JSP. The appearance of this action effectively terminatesthe execution of the current page.
JSP Fundamentals
PART II274
A <jsp:forward> action can contain <jsp:param> sub-attributes. These sub-attributesprovide values for parameters in the request to be used for forwarding.
NOTE
The syntax of the <jsp:forward> action is as follows:
<jsp:forward page=”relativeURLspec” />
and
<jsp:forward page=relativeURLspec”><jsp:param .../>
</jsp:forward>
Table 16.7 contains the attribute and its description for the <jsp:forward> action.
TABLE 16.7 The Attribute for the <jsp:forward> Action
Attribute Definition
page This attribute represents the relative URL of the target of the forward.
The <jsp:forward> standard action is commonly used as a conditional in a JSP. In our example,you will get the company id from the request and, based on it, you will use the <jsp:forward>to go to the employee’s particular company page. Listing 16.5 contains the JSP that does this.
![Page 294: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/294.jpg)
LISTING 16.5 UseForward.jsp
<%@ page errorPage=”errorpage.jsp” %>
<html><head><title>Use JSP Forward</title>
</head><body><%
if ( (request.getParameter(“companyId”)).equals(“1”) ) {
%><jsp:forward page=”SamsHome.jsp”><jsp:param name=”employee” value=”Bob” /><jsp:param name=”title” value=”Senior Engineer” /></jsp:forward>
<% }else {%><jsp:forward page=”MCPHome.jsp”><jsp:param name=”employee” value=”Joe” /><jsp:param name=”title” value=”Senior Engineer” /></jsp:forward>
<%}
%></body>
</html>
As you can see, the UseForward.jsp simply checks the request for the company id and for-wards the user, along with a set of request parameters, to the appropriate company home page.Listings 16.6 and 16.7 contain the source of the company home pages.
LISTING 16.6 SamsHome.jsp
<table><tr><td><img src=”sams.gif”>
</td><td><%
JSP Standard Actions
CHAPTER 16
16
JSPS
TAN
DA
RD
AC
TION
S275
![Page 295: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/295.jpg)
LISTING 16.6 Continued
// Get the Employee’s Name from the requestout.println(“<b>Employee: </b>” + request.getParameter(“employee”));// Get the Employee’s Title from the requestout.println(“<br><b>Title: </b>” + request.getParameter(“title”));
%></td>
</tr></table>
LISTING 16.7 MCPHome.jsp
<table><tr><td><img src=”mcplogo.gif”>
</td><td><%// Get the Employee’s Name from the requestout.println(“<b>Employee: </b>” + request.getParameter(“employee”));// Get the Employee’s Title from the requestout.println(“<br><b>Title: </b>” + request.getParameter(“title”));
%></td>
</tr></table>
After you have copied the JSPs and the two image files, sams.gif and mcplogo.gif, into the<SERVER_ROOT>/djs/ directory, open your browser to the following URL:
http://localhost/djs/UseForward.jsp?companyId=1
You will see an image similar to Figure 16.2.
JSP Fundamentals
PART II276
![Page 296: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/296.jpg)
FIGURE 16.2The output from UseForward.jsp.
You should also go ahead and change the companyId request parameter to equal somethingother than 1. This will show you how the JSP forwards based on a conditional.
To see how the <jsp:forward> action is implemented, let’s take a look at the following codesnippet removed from the generated servlet’s _jspService() method:
// begin [file=”C:\\UseForward.jsp”;from=(7,6);to=(11,8)]
if ( (request.getParameter(“companyId”)).equals(“1”) ) {
// end// begin [file=”C:\\UseForward.jsp”;from=(12,10);to=(15,24)]if (true) {
out.clear();String _jspx_qfStr = “”;_jspx_qfStr = _jspx_qfStr + “?employee=” + “Bob”;_jspx_qfStr = _jspx_qfStr + “&title=” + “Senior Engineer”;pageContext.forward(“SamsHome.jsp” + _jspx_qfStr);return;
}
JSP Standard Actions
CHAPTER 16
16
JSPS
TAN
DA
RD
AC
TION
S277
![Page 297: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/297.jpg)
// end// beginout.write(“\r\n “);// end// begin [file=”C:\\UseForward.jsp”;from=(16,10);to=(19,8)]
}else {
// end// beginout.write(“\r\n “);// end// begin [file=”C:\\UseForward.jsp”;from=(20,10);to=(23,24)]if (true) {
out.clear();String _jspx_qfStr = “”;_jspx_qfStr = _jspx_qfStr + “?employee=” + “Joe”;_jspx_qfStr = _jspx_qfStr + “&title=” + “Senior Engineer”;pageContext.forward(“MCPHome.jsp” + _jspx_qfStr);return;
}// end// beginout.write(“\r\n “);// end// begin [file=”C:\\UseForward.jsp”;from=(24,10);to=(26,4)]
}
You can see that there is nothing really complicated about this code snippet. It simply decideswhich JSP to forward to, creates the query string, and calls the pageContext.forward()method with the name of the JSP and the query string.
The <jsp:plugin> Standard ActionThe <jsp:plugin> action enables a JSP author to generate HTML that contains the appropriateclient-browser independent constructs, for example, OBJECT or EMBED, that will result in thedownload of the Java plug-in and subsequent execution of the specified applet or JavaBeanscomponent.
The <jsp:plugin> tag is replaced by either an <object> or <embed> tag, as appropriate for therequesting user agent, and is written to the output stream of the response object. The attributesof the <jsp:plugin> action provide configuration data for the presentation of the element. Thesyntax of the <jsp:plugin> action is as follows:
JSP Fundamentals
PART II278
![Page 298: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/298.jpg)
<jsp:plugin type=”pluginType”code=”classFile”codebase=”relativeURLpath”>
<jsp:params>
</jsp:params></jsp:plugin>
Table 16.8 contains the attributes and their descriptions for the <jsp:plugin> action.
TABLE 16.8 The Attributes for the <jsp:plugin> Action
Attribute Definition
type This attribute represents the type of plug-in to include. An example of thiswould be an applet.
code This attribute represents the name of the class that will be executed by theplug-in.
codebase This attribute references the base or relative path of where the code attributecan be found.
SummaryThis chapter covered the JSP standard actions. You should feel comfortable with how they areimplemented and how you can use them.
In the next chapter we will cover the scope differences when using JavaBeans in a JSP.
JSP Standard Actions
CHAPTER 16
16
JSPS
TAN
DA
RD
AC
TION
S279
![Page 299: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/299.jpg)
![Page 300: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/300.jpg)
CHAPTER
17Using JavaBeans and JSPScopes
IN THIS CHAPTER• The Counter JavaBean 282
• page Scope 283
• request Scope 284
• session Scope 286
• application Scope 289
![Page 301: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/301.jpg)
The Counter JavaBeanAs discussed in Chapter 16, “JSP Standard Actions,” the <jsp:useBean> standard action pro-vides four different options for the scope attribute: page, request, session, and application.We will discuss each of these and give an example of how to use them in the following sec-tions.
For our examples, we will be using the Counter bean from Chapter 16, which acts as a simplecounter. It has a single int property, count, which holds the current number of times thebean’s property has been accessed. It also contains the appropriate methods for getting and set-ting this property. Listing 17.1 contains the source for this bean.
LISTING 17.1 Counter.java
import java.io.Serializable;public class Counter implements Serializable{// Initialize the bean on creationint count = 0;
// Parameterless Constructorpublic Counter() {
}
// Property Getterpublic int getCount() {
// Increment the count property, with every requestcount++;return this.count;
}
// Property Setterpublic void setCount(int count) {
this.count = count;}
}
To use this bean you will need to compile it and move the class file to your<SERVER_ROOT>/djs/WEB-INF/classes/ directory, if you have not already done so.
JSP Fundamentals
PART II282
![Page 302: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/302.jpg)
page ScopeBeans with page scope are accessible only within the page where they were created.References to an object with page scope will be released when the response is sent back to theclient or the request is forwarded to another resource. Objects with page scope are stored in thepageContext. A bean with page scope is most often used for single instance calculations ortransactions.
An example of using the Counter bean with page scope can be found in Listing 17.2.
LISTING 17.2 PageBean.jsp
<%@ page errorPage=”errorpage.jsp” %>
<!-- Instantiate the Counter bean with an id of “counter” --><jsp:useBean id=”counter” scope=”page” class=”Counter” />
<html><head><title>Page Bean Example</title>
</head><body><H3>Page Bean Example</H3><center><b>The current count for the counter bean is: </b><%=counter.getCount() %></center>
</body></html>
You can see that this JSP creates an instance of the Counter bean with an id of “counter”. Itthen prints the current value of the bean’s count property.
To test the page scope example, move the PageBean.jsp to the <SERVER_ROOT>/djs/ directoryand open your browser to the following URL:
http://localhost/djs/PageBean.jsp
You should see a page similar to Figure 17.1.
Go ahead and reload the page a few times. You will notice that the printed count is alwaysreset to 1. This is because each instance of the counter bean is new every time the page isloaded.
Using JavaBeans and JSP Scopes
CHAPTER 17
17
USIN
GJA
VAB
EAN
SA
ND
JSPS
CO
PES283
![Page 303: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/303.jpg)
FIGURE 17.1The output from PageBean.jsp.
request ScopeBeans with request scope are accessible only within pages processing the same request inwhich the object was created. References to the object will be released after the request isprocessed completely. If the request is forwarded to another resource in the same runtime thenthe object is still in scope. References to objects with request scope are stored in the requestobject. Objects that have request scope are most often used when you need to share informa-tion between resources that is only pertinent for the current request.
As an example of a bean with request scope, you’ll create an instance of the Counter beanand forward it to another resource. Listing 17.3 contains the JSP that creates your bean andforwards it to a second JSP.
LISTING 17.3 RequestBean1.jsp
<%@ page errorPage=”errorpage.jsp” %>
<!-- Instantiate the Counter bean with an id of “counter” --><jsp:useBean id=”counter” scope=”request” class=”Counter” />
JSP Fundamentals
PART II284
![Page 304: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/304.jpg)
<html><head><title>Request Bean Example</title>
</head><body><!-- call the counter’s setCount() method --><!-- so that the current value of the property --><!-- count is changed. -->
<%counter.setCount(10);
%>
<jsp:forward page=”RequestBean2.jsp” /></body>
</html>
The only thing you really need to notice about this JSP is the fact that the scope of the bean isset to request, and the counter.setCount() method is called with the value of 10. This call isto prove that the JSP to which the request is forwarded is receiving the same instance of thecounter bean. Listing 17.4 contains the source for the second JSP.
LISTING 17.4 RequestBean2.jsp
<%@ page errorPage=”errorpage.jsp” %>
<!-- Instantiate the Counter bean with an id of “counter” --><jsp:useBean id=”counter” scope=”request” class=”Counter” />
<html><head><title>Request Bean Example 2</title>
</head><body><H3>Request Bean Example 2</H3><center><b>The current count for the counter bean is: </b><%=counter.getCount() %></center>
</body></html>
As you examine the source of the second JSP, you will see that it gets a reference to thecounter bean from the request, and then prints the current value of the bean’s count property.
Using JavaBeans and JSP Scopes
CHAPTER 17
17
USIN
GJA
VAB
EAN
SA
ND
JSPS
CO
PES285
LISTING 17.3 Continued
![Page 305: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/305.jpg)
To see how it works, copy both of these JSPs to the <SERVER_ROOT>/djs/ directory and openyour browser to the following URL:
http://localhost/djs/RequestBean1.jsp
You will see a page similar to Figure 17.2.
JSP Fundamentals
PART II286
FIGURE 17.2The output from RequestBean1.jsp.
You can reload the page several times, but the result will always be the same. The second JSPwill print the current value of the count property as 11. This is because the instance of thebean only lasts as long as the request.
session ScopeBeans with session scope are accessible only within pages processing requests that are in thesame session as the one in which the bean was created. It is illegal to define an object withsession scope from within a page whose page directive has an attribute session=false.References to the session objects are released after their associated sessions expire. Objectswith session scope are stored in the session object associated with the page.
Beans that use session scope are most often used when there is a need to share informationbetween requests for a single client. A common application using bean scope is a shopping
![Page 306: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/306.jpg)
cart. For our example, you will use the Counter bean and two almost identical JSPs. Each JSPcreates an instance of your bean and prints out the current value of the count property. Thetwo JSPs can be found in Listings 17.5 and 17.6, respectively.
LISTING 17.5 SessionBean1.jsp
<%@ page errorPage=”errorpage.jsp” %>
<!-- Instantiate the Counter bean with an id of “counter” --><jsp:useBean id=”counter” scope=”session” class=”Counter” />
<html><head><title>Session Bean Example 1</title>
</head><body><H3>Session Bean Example 1</H3><center><b>The current count for the counter bean is: </b><%=counter.getCount() %></center>
</body></html>
LISTING 17.6 SessionBean2.jsp
<%@ page errorPage=”errorpage.jsp” %>
<!-- Instantiate the Counter bean with an id of “counter” --><jsp:useBean id=”counter” scope=”session” class=”Counter” />
<html><head><title>Session Bean Example 2</title>
</head><body><H3>Session Bean Example 2</H3><center><b>The current count for the counter bean is: </b><%=counter.getCount() %></center>
</body></html>
You can see that the only difference between these two JSPs is the values of the HTML<title> and <h3> tags.
Using JavaBeans and JSP Scopes
CHAPTER 17
17
USIN
GJA
VAB
EAN
SA
ND
JSPS
CO
PES287
![Page 307: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/307.jpg)
To see how a session bean works, copy both of these JSPs to the <SERVER_ROOT>/djs/ direc-tory and open your browser to the following URL:
http://localhost/djs/SessionBean1.jsp
You should see an image similar to Figure 17.3.
JSP Fundamentals
PART II288
FIGURE 17.3The output from SessionBean1.jsp.
Click your reload button several times. You should see the count increase each time the page isreloaded. Now use the same browser instance to open the following URL:
http://localhost/djs/SessionBean2.jsp
You will see the count increment from the last count from the first JSP. This is because thecounter bean is stored in the session of the client.
Now open a completely new instance of the browser and you will see that the value of thecount property is reset. This is because each instance of a client creates its own instance of theHttpSession, which is where the counter bean is stored.
![Page 308: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/308.jpg)
application ScopeBeans with application scope are accessible within pages processing requests that are in thesame application space as the page in which they were created. References to the object will bereleased when the runtime environment reclaims the ServletContext. More simply put, thismeans that until the JSP engine is restarted, the bean created with application scope will beavailable. Beans with application scope are best used when you need to share informationbetween JSPs and servlets for the life of your application.
To give an example of application scope, you will use two JSPs. The first will load theCounter bean using an id of “counter” and a scope of “application”. It will then print outthe current value of the counter bean, using the Counter.getCount() method. Listing 17.7contains the source for your first JSP.
LISTING 17.7 ApplicationBean1.jsp
<%@ page errorPage=”errorpage.jsp” %><!-- Instantiate the Counter bean with an id of “counter” --><jsp:useBean id=”counter” scope=”application” class=”Counter” /><html><head><title>Application Bean Example 1</title>
</head><body><H3>Application Bean Example 1</H3><center><b>The current count for the counter bean is: </b><%=counter.getCount() %></center>
</body></html>
The second JSP does exactly the same thing as the first. However, because both beans have anid of “counter” and “application” scope, the second JSP will find the bean and not have tocreate it. Listing 17.8 contains the source for your second JSP.
LISTING 17.8 ApplicationBean2.jsp
<%@ page errorPage=”errorpage.jsp” %><!-- Instantiate the Counter bean with an id of “counter” --><jsp:useBean id=”counter” scope=”application” class=”Counter” /><html><head><title>Application Bean Example 2</title>
</head>
Using JavaBeans and JSP Scopes
CHAPTER 17
17
USIN
GJA
VAB
EAN
SA
ND
JSPS
CO
PES289
![Page 309: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/309.jpg)
<body><H3>Application Bean Example 2</H3><center><b>The current count for the counter bean is: </b><%=counter.getCount() %></center>
</body></html>
Go ahead and copy both of these JSPs to the <SERVER_ROOT>/djs/ directory and open yourbrowser to the following URL:
http://localhost/djs/ApplicationBean1.jsp
Click the reload button a few times and watch the count go up. You will see a page similar toFigure 17.4.
JSP Fundamentals
PART II290
LISTING 17.8 Continued
FIGURE 17.4The output from ApplicationBean1.jsp.
Now open another browser window to the second JSP using the following URL:
http://localhost/djs/ApplicationBean2.jsp
![Page 310: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/310.jpg)
Click the reload button a few times and watch the count go up. You will see that each pageincrements the other page’s instance; both of these pages share the same instance of theCounter bean. They will share this instance until the JSP engine is shut down.
SummaryIn this chapter, we covered how JSP beans are scoped. You should feel comfortable with thedifferent types of JSP scope. You should also understand how the life of a JSP bean is deter-mined by its scope.
In the next chapter we will take a look at how you handle errors that occur in your JSPs.
Using JavaBeans and JSP Scopes
CHAPTER 17
17
USIN
GJA
VAB
EAN
SA
ND
JSPS
CO
PES291
![Page 311: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/311.jpg)
![Page 312: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/312.jpg)
CHAPTER
18Handling JSP Errors
IN THIS CHAPTER• JSP Translation-Time Errors 294
• JSP Request-Time Errors 294
![Page 313: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/313.jpg)
Errors can occur in a JSP in two different phases of its life. The first type of error, whichoccurs during the initial request, is known as a translation-time error. The second type of JSPerror occurs during subsequent requests and is know as a request-time error. These errors arediscussed in the following sections.
JSP Translation-Time ErrorsThe first type of JSP error occurs when a JavaServer Page is first requested and goes throughthe initial translation from a JSP source file into a corresponding servlet class file. These translation-time errors are usually the result of compilation failures. They are reported to therequesting client with an error status code 500 or Server Error and usually contain thereported compilation error. The JSP engine handles translation-time errors.
JSP Request-Time ErrorsThe second type of JSP error occurs during request time. These errors are runtime errors thatcan occur either in the body of the JSP page or in some other object that is called from thebody of the JSP page.
Request-time errors result in an exception being thrown. These exceptions can be caught andappropriately handled in the body of the calling JSP, which would be the end of the error.Those exceptions that are not caught result in the forwarding of the client request, includingthe uncaught exception, to the error page specified by the offending JSP. The following sec-tions describe, in detail, how to define and implement JSP error pages.
Creating a JSP Error PageTo create a JSP error page, you need to create a basic JavaServer Page and then tell the JSPengine that the page is an error page. You do this by setting its page attribute isErrorPage totrue. Listing 18.1 contains a sample error page.
LISTING 18.1 errorpage.jsp
<html>
<body text=”red”>
<%@ page isErrorPage=”true” %>
<!-- Use the implicit exception object, which holds a reference --><!-- to the thrown exception. -->
JSP Fundamentals
PART II294
![Page 314: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/314.jpg)
Error: <%= exception.getMessage() %> has been reported.
</body></html>
There are two lines of code you need to look at to understand just how easy it is to create aJSP error page. The first is the page directive line, which indicates that this JSP is an errorpage. This code snippet is
<%@ page isErrorPage=”true” %>
The second line of code designates where the thrown exception is being used. This line is
Error: <%= exception.getMessage() %> has been reported.
You will notice that this line uses the implicit exception object that is part of all JSP errorpages. The exception object holds the reference to the unhandled exception that was thrownin the offending JSP.
To gain a complete understanding of how the error page works, take a look at the servlet codethat is generated from the JSP error page. The following code snippet contains the_jspService() method generated from Listing 18.1:
Handling JSP Errors
CHAPTER 18
18
HA
ND
LING
JSPE
RR
OR
S295
LISTING 18.1 Continued
The generated code included in the examples will differ depending on the applica-tion server used.
NOTE
public void _jspService(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
JspFactory _jspxFactory = null;PageContext pageContext = null;HttpSession session = null;Throwable exception =(Throwable)request.getAttribute(“javax.servlet.jsp.jspException”);
ServletContext application = null;ServletConfig config = null;JspWriter out = null;Object page = this;
![Page 315: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/315.jpg)
String _value = null;
try {
if (_jspx_inited == false) {
_jspx_init();_jspx_inited = true;
}_jspxFactory = JspFactory.getDefaultFactory();response.setContentType(“text/html”);pageContext = _jspxFactory.getPageContext(this, request, response,
“”, true, 8192, true);
application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();out = pageContext.getOut();
// beginout.write(“<html>\r\n\r\n<body text=\”red\”>\r\n\r\n”);// end// beginout.write(“\r\n\r\n<!-- Use the implicit exception object, “ +out.write(“which holds a reference -->\r\n<!-- to the thrown “ +out.write(“exception. -->\r\n\r\nError: “);// end// begin [file=”D:\\errorpage.jsp”;from=(9,10);to=(9,34)]out.print( exception.getMessage() );// end// beginout.write(“ has been reported. \r\n\r\n</body>\r\n</html>\r\n”);// end
}catch (Exception ex) {
if (out.getBufferSize() != 0)out.clear();
pageContext.handlePageException(ex);}finally {
out.flush();_jspxFactory.releasePageContext(pageContext);
}}
JSP Fundamentals
PART II296
![Page 316: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/316.jpg)
You will notice that the _jspService() method looks much like any other generated JSP,except that it has the following lines:
Throwable exception =(Throwable)request.getAttribute(“javax.servlet.jsp.jspException”);
These two lines make it possible for the error page to access the implicit exception object. Itdoes this by getting the exception object from the request, using therequest.getAttribute() method with a key of javax.servlet.jsp.jspException. Nowyour JSP can do whatever it wants with the received exception. In the next section, we willexamine how the exception object gets placed into the request.
Using a JSP Error PageNow that you know how to create a JSP error page, let’s put one to use. It takes only one addi-tional attribute, in your page directive, to make your JSP aware of an error page. You simplyneed to add the errorPage attribute and set its value equal to the location of your JSP errorpage. The JSP in Listing 18.2 uses the error page you created in the previous section.
LISTING 18.2 testerror.jsp
<%@ page errorPage=”errorpage.jsp” %>
<%
if ( true ) {
// Just throw an exceptionthrow new Exception(“A JSP Exception”);
}
%>
You will notice in this listing that the first line of code sets the errorPage equal to errorpage.jsp, which is the name of your error page. The rest of the example is used to throwan exception that will not be caught. That is all there is to it. Copy both of these JSPs to the<SERVER_ROOT>/djs/ directory and open the testerror.jsp page in your browser. You willsee a page similar to Figure 18.1.
Handling JSP Errors
CHAPTER 18
18
HA
ND
LING
JSPE
RR
OR
S297
![Page 317: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/317.jpg)
FIGURE 18.1Output of the testerror.jsp example.
To see how this error is handled in the actual compiled code, take a look at the _jspService()method generated from the testerror.jsp example. The following code snippet contains thegenerated _jspService() method:
public void _jspService(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
JspFactory _jspxFactory = null;PageContext pageContext = null;HttpSession session = null;ServletContext application = null;ServletConfig config = null;JspWriter out = null;Object page = this;String _value = null;
try {
if (_jspx_inited == false) {
_jspx_init();
JSP Fundamentals
PART II298
![Page 318: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/318.jpg)
_jspx_inited = true;}_jspxFactory = JspFactory.getDefaultFactory();response.setContentType(“text/html”);
pageContext = _jspxFactory.getPageContext(this, request, response,“errorpage.jsp”, true, 8192, true);
application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();out = pageContext.getOut();
// beginout.write(“\r\n\r\n”);// end// begin [file=”D:\\testerror.jsp”;from=(2,2);to=(10,0)]
if ( true ) {
// Just throw an exceptionthrow new Exception(“A JSP Exception”);
}
// end// beginout.write(“\r\n”);// end
}catch (Exception ex) {
if (out.getBufferSize() != 0)
out.clear();pageContext.handlePageException(ex);
}finally {
out.flush();_jspxFactory.releasePageContext(pageContext);
}}
The first section of code you need to look at is the call to get the PageContext object from theJspFactory, using the getPageContext() method. This method obtains an instance of an
Handling JSP Errors
CHAPTER 18
18
HA
ND
LING
JSPE
RR
OR
S299
![Page 319: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/319.jpg)
implementation-dependent javax.servlet.jsp.PageContext abstract class for the callingservlet and currently pending request and response. You will also notice that one of its parame-ters is the name you specified as your error page. The following code snippet shows the call togetPageContext():
pageContext = _jspxFactory.getPageContext(this, request, response,“errorpage.jsp”, true, 8192, true);
Now this instance of the PageContext object knows which page to forward all uncaught errorsto. This is done in the following code snippet:
catch (Exception ex) {
if (out.getBufferSize() != 0)
out.clear();pageContext.handlePageException(ex);
}
You can see that this catch block catches all uncaught exceptions and passes them to thepageContext.handlePageException() method, which in turn places the exception into therequest and forwards it to the error page referenced during the creation of the PageContext.
SummaryIn this chapter we covered the types of errors that can occur in a JSP. You have also seen howyou can handle and respond to these errors, using a JSP error page.
In the next chapter, we will cover one of the more useful JSP topics: custom JSP tags.
JSP Fundamentals
PART II300
![Page 320: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/320.jpg)
CHAPTER
19Custom JSP Tag Libraries
IN THIS CHAPTER• JSP Custom Tags 302
• Deploying Tag Libraries 302
• Developing Custom JSP Tags Handlers 306
![Page 321: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/321.jpg)
JSP Fundamentals
PART II302
JSP Customs TagsJSP custom tags encapsulate functional and/or business logic that can be reused inside of aJavaServer Page. This gives you the ability to insert complex logic into a JSP without havingthe JSP code itself be overly complicated. This is a true use of object-oriented encapsulation.Some custom tag examples that we have already discussed are the JSP standard actions. Theyhave the same functionality as a custom tag. A code snippet with a custom tag follows:
<%@ taglib uri=”/djs” prefix=”djs” %>
<html><body>
<djs:hello />
</body></html>
This JSP contains two lines that you need to examine. The first is the line:
<%@ taglib uri=”/djs” prefix=”djs” %>
This is the taglib directive. It describes the tag library and must be included to reference anycustom tag library. We will cover the taglib directive in more detail in the next section.
The second thing you should notice is the tag itself. Our tag has a prefix of djs, which wasdefined by the taglib directive, and the tag itself is hello. When the JSP container encountersthis line of JSP text, it will execute the code associated with this tag. The code that will be exe-cuted is called a tag handler, which will also be covered in further detail in a later section.
Deploying Tag LibrariesBefore you can start using tag libraries, you must understand how they are deployed. JSP taglibraries are groups of JSP custom tags that have been packaged together for deployment. Assample grouping might be a set of tags that encapsulate database functionality. Four steps areinvolved in deploying a tag library:
1. Create a tag library descriptor.
2. Deploy the tag handlers to your Web application.
3. Add a taglib entry to your Web application’s web.xml file.
4. Add a taglib directive to your JSP that will be using the custom tag library.
Creating a Taglib DescriptorA tag library descriptor (tld) is just what it sounds like. It is an XML file that describes the taglibrary that you are trying to deploy.
![Page 322: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/322.jpg)
The following code snippet contains a simple tld with one tag defined named hello:
<?xml version=”1.0” encoding=”ISO-8859-1” ?><!DOCTYPE taglibPUBLIC “-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN”“http://java.sun.com/j2ee/dtds/web-jsptaglib_1_1.dtd”><!-- a tab library descriptor --><taglib><tlibversion>RC1</tlibversion><jspversion>1.1</jspversion><info>DJS Tag Library</info>
<tag><name>hello</name><tagclass>com.djs.HelloTag</tagclass><bodycontent>empty</bodycontent></tag></taglib>
The tld breaks down into three main sections. The first is the document description section.This section contains the xml version and the Document Type Definition (DTD) that definesthe document type of the tld. It will most often not change.
The second section, a child of the taglib entry, describes the tag library. The attributes definedin this section are optional. Some of the entries in this part of the document define the versionof the tag library, define JSP version used by the tag library, and describe general informationabout the tag library.
The last section is the most important. It is the tag section, also a child of the taglib entry.This section describes each defined tag and the handlers that are associated with it. Table 19.1defines the subelements available for the tag entry.
TABLE 19.1 Subelements Associated with the tag Entry
Subelement Definition
name The unique name of the tag
tagclass The tag handler class
teiclass The optional class used to describe extra information about a tag
Custom JSP Tag Libraries
CHAPTER 19
19
CU
STOM
JSP TA
GL
IBR
AR
IES303
This text will not define every attribute associated with the tag library descriptor. Thiswould be beyond the scope of this book. To find more information on tlds you canlook at the JSP specification.
NOTE
![Page 323: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/323.jpg)
bodycontent The type of content that is in the body of the tag: JSP, empty, ortagdependent
info optional tag-specific information
attribute Names an attribute or attributes to be passed to the tag handler
Each of the subelements mentioned in Table 19.1 will be further defined as we cover the actualdevelopment of some custom tags.
Deploying the Tag Handlers to Your Web ApplicationThe tag handlers are the actual code that is executed when a named tag is encountered in yourJSP. The tag handlers that we will define in a later section will be compiled into class files anddeployed to the Web application.
Tag handlers can be deployed in two ways. The first is just as straight class files with a tlddefining all of the tags and their handlers in the library. You would do this by moving the classfiles into the Web application’s class path. When deploying to Tomcat, using our djs Webapplication, you would move the class files into the <SERVER_ROOT>/webapps/djs/WEB-INF/classes directory. The tld would then need to be moved into a directory, preferablyin the Web application space that will be referenced in the web.xml.
The second way to deploy a group of tag handlers is in a jar file. When you choose this routeyou need to compile your tag handlers and jar them with their tld. The tld will need to beadded to the jar file at the top level in the /META-INF directory. The tld will also need to bestored in a file named taglib.tld. You should then move this jar file into the classpath of theWeb application; using our djs Web application, a common location would be in the<SERVER_ROOT>/webapps/djs/WEB-INF/lib directory.
Adding a taglib Entry to Your Web ApplicationAfter you have created your tld and deployed your tag handlers, you need to deploy thelibrary to your Web application. If you choose to deploy your tag library as straight class files,you will need to directly name your tld in the Web application’s web.xml file. An example ofthis is in the following code snippet:
<taglib><taglib-uri>/djs</taglib-uri><taglib-location> /WEB-INF/tlds/taglib.tld</taglib-location></taglib>
JSP Fundamentals
PART II304
TABLE 19.1 Continued
Subelement Definition
![Page 324: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/324.jpg)
In this example you define the tag library to have a URI of /djs using the taglib-uri subele-ment. In the second subelement you point the JSP container to the location of the tld, which isin the directory <SERVER_ROOT>/webapps/djs/WEB-INF/tlds/ and in a file namedtaglib.tld.
If you have chosen to deploy the tag handlers as a jar file then, assuming that your tld isinside the jar, you will need to replace the contents of the taglib-location subelement with areference pointing directly to the jar file. A code snippet that demonstrates this is listed next:
<taglib><taglib-uri>/djs</taglib-uri><taglib-location> /WEB-INF/lib/djs.jar</taglib-location></taglib>
Adding the taglib Directive to Your JSPNow that you have created the tld, deployed the tag handlers, and added the tld to your Webapplication it is time to make the final connection by adding the taglib directive to the actualJSP. The taglib directive has two purposes: It tells the JSP container the location of the tldand it names the prefix that will link the tags to the named tld. It does this with two attributes.
The first attribute is the uri. It refers to a URI that uniquely identifies the tag library. This URIreferences an attribute of a taglib entry of the Web application’s web.xml file. The previousexample taglib entry is listed in the following code snippet:
<taglib><taglib-uri>/djs</taglib-uri><taglib-location>/WEB-INF/tlds/taglib.tld</taglib-location></taglib>
To reference the above Web application’s taglib entry you would have to add the followingtaglib directive to your JSP:
<%@ taglib uri=”/djs” prefix=”djs” %>
Notice that the uri referenced in the JSP matches the taglib-uri referenced in the web.xmlfile. This tells the JSP container that this JSP references a tag library descriptor that is locatedin the directory <SERVER_ROOT>/webapps/djs/WEB-INF/tlds/ and the file containing thetaglib descriptor is taglib.tld.
The second attribute defines the prefix of the tag library. This prefix is used to uniquely iden-tify a given tag library from another tag library when parsing a JSP. In this example, the prefix attribute is djs; therefore a tag referencing the /djs tag library would always be beginwith djs:. The JSP container goes through the following steps when trying to resolve the loca-tion of tag library descriptor:
Custom JSP Tag Libraries
CHAPTER 19
19
CU
STOM
JSP TA
GL
IBR
AR
IES305
![Page 325: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/325.jpg)
1. It parses the JSP.
2. When the container encounters a custom tag, it checks for a matching prefix in theJSP’s list of taglib directives.
3. When it finds a match, it gets the defined uri.
4. After it has a URI, it then looks in the Web application’s web.xml file for a taglib entrywhere the taglib-uri and the JSP’s taglib uri match.
5. When it finds the matching URI, it gets the location of the tag library descriptor, whichis then used to map the appropriate tag handlers to the encountered tags.
Developing Custom JSP Tags HandlersNow that we have finally gotten through the unpleasantness of deployment, let’s actuallydevelop something that you can deploy. JSP custom tag handlers have a very simple hierarchy.They all implement the Tag interface, either directly or through inheritance. The way they dothis depends on their type. You can develop two types of custom tags, tag with bodies and tagswithout. This determines the implementation of tag handlers. Figure 19.1 shows the differentclasses and their hierarchy.
JSP Fundamentals
PART II306
<<Interface>>Tag
<<Interface>>BodyTag
BodyTagSupport
TagSupport
FIGURE 19.1The Custom Tag Class Hierarchy.
Tags Without BodiesThe first type of tag that we will discuss is a tag without a body. A tag with no body indicatesthat the text between the beginning and ending custom tag elements will not be evaluated bythe associated tag handler.
As we stated in the previous section, all tags handlers must implement the Tag interface, butthere are helper classes for each type of tag. These helpers implement all of the Tag interface
![Page 326: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/326.jpg)
methods requiring that the developer only implement the methods that apply to their specifictag. For a tag without a body the helper is TagSupport; therefore if you are developing a taghandler for a tag with no body, your handler needs to extend the TagSupport class. The meth-ods that are implemented by the TagSupport class are listed in Table 19.2.
TABLE 19.2 Methods Implemented by the TagSupport Class
Method Definition
setPageContext() Sets the PageContext associated with the current page.
setParent() Sets the reference to the parent Tag, if the current Tag is nested.
doStartTag() Called when the JSP container encounters the beginning of this tag.
doEndTag() Called when the JSP container encounters the ending of this tag.
release() Called by the container when the tag is finished processing. Itshould be used to reset all data members and free all allocatedresources. The release() method is guaranteed to be invoked onlyonce.
Before you can create your own bodiless tag, you need to understand the actions taken by theJSP container when it does encounter a tag without a body. After the container has identifiedthe tag handlers associated with the encountered tags, as described in the steps in the precedingsection “Adding the taglib Directive to Your JSP,” the JSP container continues with the fol-lowing steps. These steps apply only to tags that have no body and no attributes:
1. The setPageContext() method is called, setting the current page’s PageContext.
2. The setParent() method is called with a reference to the parent Tag object, if this is anested tag, or null if not.
3. The doStartTag() is then called. It will return either EVAL_BODY_INCLUDE or SKIP_BODY.If EVAL_BODY_INCLUDE is returned, the container should evaluate the body of the tag. IfSKIP_BODY is returned, the container will not evaluate the body.
4. The doEndTag() method is called when the closing tag element is encountered. It canreturn either of two values: EVAL_PAGE, which tells the container to continue evaluatingthe page, and SKIP_PAGE, which tells the container to stop evaluating the rest of the page.
5. The final step performed by the container is to call the release() method. This methodis used to reset class level attributes and to release any allocated resources.
A Sample Tag with No BodyNow that you have an understanding of how bodiless tags work, let’s create an example. Yourcustom tag, called the hello tag, when encountered will simply output the text Hello. The firststep you need to take is to create a class that extends the TagSupport class and add the appro-priate functionality to output your text message. Listing 19.1 contains the source for your tag.
Custom JSP Tag Libraries
CHAPTER 19
19
CU
STOM
JSP TA
GL
IBR
AR
IES307
![Page 327: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/327.jpg)
LISTING 19.1 HelloTag.java
package com.djs;
import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspTagException;import javax.servlet.jsp.tagext.TagSupport;
public class HelloTag extends TagSupport{
public void HelloTag() {
}
// Method called when the closing hello tag is encounteredpublic int doEndTag() throws JspException {
try {
// We use the pageContext to get a Writer// We then print the text string HellopageContext.getOut().print(“Hello”);
}catch (Exception e) {
throw new JspTagException(e.getMessage());}// We want to return SKIP_BODY because this Tag does not support// a Tag Bodyreturn SKIP_BODY;
}
public void release() {
// Call the parent’s release to release any resources// used by the parent tag.// This is just good practice for when you start creating// hierarchies of tags.super.release();
}}
As you look over this tag, you will see that it first extends the TagSupport class. This is thehelper class for tags without bodies. It provides default implementations for the methodsdefined in the Tag interface. The next thing you should notice is the two methods that are over-ridden from the TagSupport class: doEndTag() and release().
JSP Fundamentals
PART II308
![Page 328: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/328.jpg)
The first method that you override is the doEndTag() method. You implement this methodbecause you are not concerned with the content of the body. In the doEndTag() method thefirst thing you do is get a reference to a JspWriter that references the current stream beingused for client response. You then use the print() method to write the text Hello string to theresponse stream.
The next method you override is the release() method. This is where you would release all ofthe resources that you have allocated in the tag. For your purposes, because you did not allo-cate any resources, you will simply call the parent tag’s release method. This is just good prac-tice as you start to get into more complex tag hierarchies.
To see this tag in action you need to first compile the HelloTag.java file and move the classfile into the <SERVER_ROOT>/webapps/djs/WEB-INF/classes/com/djs/ directory.
You then need to create a tld that describes your tag library. Listing 19.2 contains the sourcefor your tag library descriptor.
LISTING 19.2 taglib.tld
<?xml version=”1.0” encoding=”ISO-8859-1” ?><!DOCTYPE taglib
PUBLIC “-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN”“http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd”>
<!-- a tag library descriptor -->
<taglib><tlibversion>1.0</tlibversion><jspversion>1.1</jspversion><shortname>djs</shortname><uri>/djs</uri><info>
Developing Java Servlets 2</info>
<tag><name>hello</name><tagclass>com.djs.HelloTag</tagclass><bodycontent>empty</bodycontent><info>Just Says Hello</info>
</tag>
</taglib>
You only need to examine two parts in this simple tld. The first is the <uri> entry, which is/djs for your library. This tells the container that this tag library should be referenced when aJSP’s taglib directive contains the same uri.
Custom JSP Tag Libraries
CHAPTER 19
19
CU
STOM
JSP TA
GL
IBR
AR
IES309
![Page 329: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/329.jpg)
The next section to examine is the <tag> section. It describes the name of the tag and its asso-ciated tag handler. It also says that the bodycontent for this tag is empty.
The next step is to copy this tld into a directory that can be referenced in the Web applica-tion’s deployment descriptor. For this example, create a directory<SERVER_ROOT>/webapps/djs/WEB-INF/tlds/ and copy the tld into it.
The final step to deploy your tag library is to add the following section to your application’sweb.xml file.
<taglib><taglib-uri>/djs</taglib-uri><taglib-location>/WEB-INF/tlds/taglib.tld</taglib-location>
</taglib>
Now you can see your new tag in action. Listing 19.3 contains the source for the JSP that willuse your Hello tag.
LISTING 19.3 Hello.jsp
<%@ taglib uri=”/djs” prefix=”djs” %>
<html><body>
<djs:hello /><br>
</body></html>
Now open your browser to the following URL:
http://localhost/djs/Hello.jsp
You should see an image similar to Figure 19.2.
JSP Fundamentals
PART II310
FIGURE 19.2The Hello Tag Page.
![Page 330: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/330.jpg)
Now whenever you add the text <djs:hello /> to your JSP, it will be replaced by the textHello.
Tags with BodiesNow that you have seen a custom tag without a body, let’s create a tag that uses a body. All taghandlers with bodies must implement the BodyTag interface. The BodyTag interface extends theTag interface by adding functionality to handle body content. It does this by adding three newmethods. Each one of these methods is described in Table 19.3.
TABLE 19.3 Methods Added by the BodyTag Interface
Method Definition
setBodyContent() Used by the container to set the current content of the tag’s body.
doInitBody() Executed once per invocation after the setBodyContent() methodand before the evaluation of the tag’s body.
doAfterBody() Called by the container after the body content has been evaluated.
Like tags without bodies, tags with bodies also have a helper class. Their helper isBodyTagSupport and it extends TagSupport and implements the BodyTag interface.
When the JSP container encounters a tag with a body it performs the following steps:
1. The setPageContext() method is called, setting the current page’s PageContext.
2. The setParent() method is called with a reference to the parent Tag object, if this is anested tag, or null if not.
3. The doStartTag() is then called. It will return either EVAL_BODY_INCLUDE or SKIP_BODY.If EVAL_BODY_INCLUDE is returned, the container should evaluate the body of the tag. IfSKIP_BODY is returned, the container will not evaluate the body.
4. The setBodyContext() is then called.
5. The doInitBody() is then called.
6. The doAfterBody() is then called repeatedly as long as it returns EVAL_BODY_TAG.
7. The doEndTag() method is called when the closing tag element is encountered. It canreturn either of two values: EVAL_PAGE, which tells the container to continue evaluatingthe page, or SKIP_PAGE, which tells the container to stop evaluating the rest of the page.
8. The final step performed by the container is to call the release() method. This methodis used to reset class level attributes and to release any allocated resources.
Custom JSP Tag Libraries
CHAPTER 19
19
CU
STOM
JSP TA
GL
IBR
AR
IES311
![Page 331: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/331.jpg)
A Sample Tag with a BodyLet’s create a tag with a body. You will use a tag much like your Hello tag. The difference isthat your BodyTag will print the text Hello and the content of the tag. Your new tag will benamed HelloBodyTag. Listing 19.4 contains the source for this tag.
LISTING 19.4 HelloBodyTag.java
package com.djs;
import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspTagException;import javax.servlet.jsp.tagext.BodyTagSupport;
public class HelloBodyTag extends BodyTagSupport {
public HelloBodyTag() {
}
// Method called when the closing hello tag is encounteredpublic int doEndTag() throws JspException {
try {
// Get the content of this tag’s bodyString name = bodyContent.getString();
// We use the pageContext to get a Writer// We then print the text string Hello + the content// of the tag’s body.pageContext.getOut().print(“Hello “ + name);
}catch (Exception e) {
throw new JspTagException(e.getMessage());}// return SKIP_BODY, because we will not evaluate the body again.return SKIP_BODY;
}
public void release() {
// Call the parent’s release to release any resources// used by the parent tag.// This is just good practice for when you start creating// hierarchies of tags.
JSP Fundamentals
PART II312
![Page 332: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/332.jpg)
super.release();}
}
As you look over this tag, you will see that it first extends the BodyTagSupport class. This isthe helper class for tags with bodies. It provides default implementations for the methodsdefined in the BodyTag interface.
The only difference from the HelloTag’s doEndTag() method is the following code snippet:
// Get the content of this tag’s bodyString name = bodyContent.getString();
// We use the pageContext to get a Writer// We then print the text string Hello + the content// of the tag’s body.pageContext.getOut().print(“Hello “ + name);
In the HelloBodyTag’s doEndTag() method you first get the String representation of the tag’sbody using the bodyContent.getString() method. After you have this String you get a refer-ence to a JspWriter that references the current stream being used for client response, as youdid in your HelloTag. You then use the print() method to write the text Hello string plus thetext value in the body of your HelloBodyTag to the response stream.
To see this tag in action you need to first compile the HelloBodyTag.java file and move theclass file into the <SERVER_ROOT>/webapps/djs/WEB-INF/classes/com/djs/ directory.
You then need to add the following code snippet to your tld:
<tag><name>helloBody</name><tagclass>com.djs.HelloBodyTag</tagclass><bodycontent>JSP</bodycontent><info>Just Says Hello to the Body</info>
</tag>
The most important thing to notice in the above snippet is the bodycontent for this tag. It isnow JSP instead of empty. This tells the container that the tag body can have content and thiscontent can be JSP code.
Now you can see your new body tag in action. Listing 19.5 contains the source for the JSP thatwill use your helloBody tag.
Custom JSP Tag Libraries
CHAPTER 19
19
CU
STOM
JSP TA
GL
IBR
AR
IES313
LISTING 19.4 Continued
![Page 333: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/333.jpg)
LISTING 19.5 HelloBody.jsp
<%@ taglib uri=”/djs” prefix=”djs” %>
<html><body>
<djs:helloBody>Bob</djs:helloBody>
</body>
</html>
Now open your browser to the following URL:
http://localhost/djs/HelloBody.jsp
You should see an image similar to Figure 19.3.
JSP Fundamentals
PART II314
FIGURE 19.3The HelloBody Tag Page.
Tags with AttributesThe last tag you will develop is a tag with attributes. With JSP custom tags you have the abilityto pass attributes to custom tags. You do this by adding an attribute list to the tag element. Anexample of this, using a modification of the original hello tag, is in the following code snip-pet:
<djs:helloAttribute name=”Bob”/>
The preceding snippet has only one attribute: name. When the JSP container encounters this tagit then checks its matching tag handler for a class-level attribute name. It uses introspection tofind this attribute and then calls its setXXX() method. All tags must have a matching setmethod for each attribute that can be included in the tag element’s attribute list. The matchingmethod for the above snippet would be the setName() method. To further examine how thisworks, let’s develop a tag with attributes.
![Page 334: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/334.jpg)
For your sample tag you will use your original hello tag and add the appropriate functionalityto handle a single name attribute. Listing 19.6 contains the source for your new tag.
LISTING 19.6 HelloAttributeTag.java
package com.djs;
import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspTagException;import javax.servlet.jsp.tagext.TagSupport;
public class HelloAttributeTag extends TagSupport {
private String name = new String();
public HelloAttributeTag() {
}
// Accessor to set the namepublic void setName(String name) {
this.name = name;}
// Method called when the closing hello tag is encounteredpublic int doEndTag() throws JspException {
try {
// We use the pageContext to get a Writer// We then print the text string HellopageContext.getOut().print(“Hello “ + name);
}catch (Exception e) {
throw new JspTagException(e.getMessage());}// We want to return SKIP_BODY because this Tag does not support// a Tag Bodyreturn SKIP_BODY;
}
public void release() {
// Call the parent’s release to release any resources
Custom JSP Tag Libraries
CHAPTER 19
19
CU
STOM
JSP TA
GL
IBR
AR
IES315
![Page 335: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/335.jpg)
// used by the parent tag.// This is just good practice for when you start creating// hierarchies of tags.super.release();
// Reset the name to an empty Stringname = new String();
}}
There are only a couple of new things to notice here. The first is the name attribute and thesetName() method. This is the attribute/method matching that is used to set attribute values aswe discussed earlier. The class level attribute name is prepended with set and the first letter ofthe attribute is capitalized to perform this matching.
To deploy this new tag you need to add an entry to the tld, compile the HelloAttributeTag,and move the class file to the <SERVER_ROOT>/webapps/djs/WEB-INF/classes/com/djs/directory. The code snippet that needs to be added to the tld follows:
<tag><name>helloAttribute</name><tagclass>com.djs.HelloAttributeTag</tagclass><bodycontent>JSP</bodycontent><info>Just Says Hello to the Body</info><attribute><name>name</name><required>true</required><rtexprvalue>true</rtexprvalue>
</attribute></tag>
The only real change to this tag element is the addition of the attribute element. In this ele-ment you state three things. You first name the attribute, which is name for this tag. You thenstate whether the attribute is required. This can be either true or false. The final addition tothe attribute element is the rtexprvalue element. This states whether the value of theattribute can be an evaluated expression. The options are true or false.
To see this tag in action, use the JSP found in Listing 19.7.
LISTING 19.7 HelloAttribute.jsp
<%@ taglib uri=”/djs” prefix=”djs” %>
<html><body>
JSP Fundamentals
PART II316
LISTING 19.6 Continued
![Page 336: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/336.jpg)
<djs:helloAttribute name=”Bob” /><br>
</body></html>
Copy this file to the <SERVER_ROOT>/webapps/djs/ directory and open your browser to thefollowing directory:
http://localhost/djs/HelloAttribute.jsp
You should see a page similar to Figure 19.4.
Custom JSP Tag Libraries
CHAPTER 19
19
CU
STOM
JSP TA
GL
IBR
AR
IES317
LISTING 19.7 Continued
FIGURE 19.4The HelloAttribute Tag Page.
SummaryIn this chapter you covered custom JSP tag libraries. We discussed the two types of taglibraries: tags without bodies and tags with bodies. We also looked at how attributes can bepassed to custom tags.
In Chapter 20, “Catalog Case Study,” we will begin our case studies. The next few chapterswill show you how to put together all the concepts we have covered so far.
![Page 337: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/337.jpg)
![Page 338: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/338.jpg)
IN THIS PART20 Catalog Case Study
21 An LDAP Web Client
22 A Stock Trader
23 Wireless Application Development Using WAP
24 WML/WMLScript Development
Servlet and JSP WebApplications
PART
III
![Page 339: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/339.jpg)
![Page 340: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/340.jpg)
CHAPTER
20Catalog Case Study
IN THIS CHAPTER• Catalog Requirements 322
• Models 322
• Views 328
• Controllers 338
• Using the Online Catalog 344
![Page 341: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/341.jpg)
Servlet and JSP Web Applications
PART III322
Catalog Requirements
You will need to create a Web application named catalog, following the steps inAppendix A, “Web Applications and Configuring the Servlet Engine.” Make sure youhave the classes ConnectionPool, Controller, and Service in your Web application’sclasspath.
NOTE
In this chapter you will put your newly found knowledge to practical use by creating a moviecatalog system. This system will be based on the server-side implementation of the MVC asdefined in Chapter 13 “A Servlet Controller.” The basic requirements are defined as follows:
• Movie Presentation—The catalog interface must give the user the ability to browse alist of movies by category.
• Movie Selection—When the user has found the movie they are looking for they shouldbe able to select the movie and have it added to the shopping cart. They can repeat thesetwo steps as many times as they would like until their order is complete.
• Order Processing Requirements—The order processing section of the catalog applica-tion comes into action when the user has selected all of the movies they want to order. Atthis point they require a method to submit the order for processing. After the order hasbeen submitted, it will then be transferred to the fulfillment department.
For this example, the submitted order will not actually be submitted to fulfillment. Itwill only be acknowledged with a thank you message.
NOTE
ModelsThis section of the requirements defines the database representation of the movie catalogapplication. Only one object in the application will be modeled in the database—the Titlestable. For our purposes you will not build an object representation of the database. We willsimply use SQL and iterate over ResultSets.
The Title object that will be represented in the database is the Movie object itself. Each of theMovie object’s attributes must be included in the table representation. Table 20.1 lists therequired elements needed to store a Movie object.
![Page 342: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/342.jpg)
TABLE 20.1 Required Attributes to Model a Movie
Attribute Type
title_id int
title_name String
price double
quantity int
category int
To make the Titles table available to your application you must set up an ODBC data sourcefollowing the same steps used in Chapter 7 “Servlets, JDBC, and Inter-ServletCommunications.” You will need to use catalog as the data source name and select the catalog.mdb file included in this chapter’s source code.
To complete your configuration of the database you will need to create a servlet that initializesthe ConnectionPool created in Chapter 7 with the appropriate setting for this application.
The source for the extension of the ConnectionPoolServlet is in Listing 20.1.
LISTING 20.1 CatalogConnectionPool
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
import ConnectionPool.ConnectionPool;public class CatalogConnectionPool extends HttpServlet {//Initialize global variablespublic void init(ServletConfig config)throws ServletException {super.init(config);// Instantiate the ConnectionPoolConnectionPool pool = new ConnectionPool();try {// Set the JDBC Driverpool.setDriver(“sun.jdbc.odbc.JdbcOdbcDriver”);pool.setURL(“jdbc:odbc:catalog”);pool.setSize(2);
// Set the Usernamepool.setUsername(“”);
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
323
![Page 343: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/343.jpg)
// Set the Passwordpool.setPassword(“”);
// Initialize the poolpool.initializePool();
// Once the pool is Initialized, add it to the// Global ServletContext. This makes it available// To other servlets using the same ServletContext.ServletContext context = getServletContext();context.setAttribute(“CATALOG_POOL”, pool);System.err.println(“ADDED CATALOG_POOL”);
}catch (Exception e) {System.err.println(e.getMessage());
}}
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {// Set the response content-typeresponse.setContentType(“text/html”);// get the Writer objectPrintWriter out = response.getWriter();out.println(“This Servlet does not service requests!”);out.close();}
public void destroy() {// Access the ServletContext using the getAttribute()// method, which returns a reference to the ConnectionPool.ServletContext context = getServletContext();ConnectionPool pool =(ConnectionPool)context.getAttribute(“CATALOG_POOL”);
if ( pool != null ) {// empty the poolpool.emptyPool();// Remove the Attribute from the ServletContextcontext.removeAttribute(“CATALOG_POOL”);
}else {
Servlet and JSP Web Applications
PART III324
LISTING 20.1 Continued
![Page 344: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/344.jpg)
System.err.println(“Could not get a reference to Pool!”);}
}}
The only changes from the ConnectionPoolServlet found in Chapter 7 are the name of theservlet, changing the URL to point to the catalog data source, and setting the number of con-nections to two. Make sure you also add the following code snippet to the catalog’s web.xmlfile:
<servlet><servlet-name>CatalogConnectionPool</servlet-name><servlet-class>CatalogConnectionPool</servlet-class><load-on-startup>1</load-on-startup></servlet>
This snippet preloads the CatalogConnectionPool when the Tomcat engine starts up.
Shopping CartThe only real object that you will create for this case study is a simple shopping cart that willhold the items the user has selected. The shopping cart will be represented by theShoppingCart class. Each user will get an instance of the ShoppingCart stored in their uniquesession. The source code for the ShoppingCart object is in Listing 20.2.
LISTING 20.2 ShoppingCart.java
import java.lang.String;import java.lang.Integer;import java.lang.Float;import java.util.Hashtable;import java.util.Enumeration;
public class ShoppingCart {protected Hashtable items = new Hashtable();public ShoppingCart() {
}
/**Add a new item to the shopping cart.*attributesitemId - the unique key associated with the item
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
325
LISTING 20.1 Continued
![Page 345: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/345.jpg)
desc - a text description of the itemprice - the unit price for this itemquantity - number of this item to insert into theshopping cart*/
public void addItem(String itemId,String desc,float price,int quantity) {
String[] item = {itemId, desc, Float.toString(price),Integer.toString(quantity)};if (items.containsKey(itemId)) {String[] tmpItem = (String[])items.get(itemId);int tmpQuant = Integer.parseInt(tmpItem[3]);quantity += tmpQuant;tmpItem[3] = Integer.toString(quantity);
}else {items.put(itemId, item);
}}
/**Remove an item from the shopping cart.*attributesitemId - the unique key associated with the item to beremoved*/
public void removeItem(String itemId) {if (items.containsKey(itemId)) {items.remove(itemId);
}}
/**Change the quantity of a specific item in the shopping cart.The item must have previously been added to perform thisfunction.*attributesitemId - unique key for the item to be updatedquantity - the new quantity to be stored in the shoppingcart*/
Servlet and JSP Web Applications
PART III326
LISTING 20.2 Continued
![Page 346: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/346.jpg)
public void updateQuantity(String itemId, int quantity) {if (items.contains(itemId)) {String[] tmpItem = (String[])items.get(itemId);tmpItem[3] = Integer.toString(quantity);
}}
/**Get an Enumeration to the list of items in the shopping cart.*/
public Enumeration getEnumeration() {return items.elements();}
/**Get the total cost of all of the items currently in theshopping cart.*/
public float getCost() {Enumeration enum = items.elements();String[] tmpItem;float totalCost = 0.00f;while (enum.hasMoreElements()) {tmpItem = (String[])enum.nextElement();totalCost += (Integer.parseInt(tmpItem[3]) *Float.parseFloat(tmpItem[2]));
}return totalCost;}
/**Get the total number of items currently in the shopping cart.*/
public int getNumOfItems() {Enumeration enum = items.elements();String[] tmpItem;int numOfItems = 0;while (enum.hasMoreElements()) {tmpItem = (String[])enum.nextElement();numOfItems += Integer.parseInt(tmpItem[3]);
}
return numOfItems;}
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
327
LISTING 20.2 Continued
![Page 347: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/347.jpg)
/**Get the total number of items currently in the shopping cart.*/
public void empty() {Enumeration enum = items.elements();String[] item;while (enum.hasMoreElements()) {item = (String[])enum.nextElement();removeItem((String)item[0]);
}}
}
As you can see, the ShoppingCart contains the basic functionality to add, remove, and displayits contents. We will look at it further as you use it in the application.
ViewsNow you need to define the interface that your users will interact with. From our requirementsdefined in the first section of this chapter you will need to create four views and an error page.
Catalog Layout Each of these pages, excluding the error page, will have the basic layout shown in Figure 20.1.
Servlet and JSP Web Applications
PART III328
LISTING 20.2 Continued
Title Bar
Client Area
Navigation
FIGURE 20.1The catalog view layout.
![Page 348: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/348.jpg)
The catalog view layout has three basic parts. The Title Bar shows a simple graphic of theSams logo and a hyperlinked image of a shopping cart. This will display a list of the shoppingcart’s contents when selected. This Title Bar will be at the top of all of your Views, and it willbe represented by the titlebar.jsp page. Figure 20.2 contains an image of the real contentsof the Title Bar.
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
329
FIGURE 20.2Contents of the Title Bar.
The source for the Title Bar is in Listing 20.3.
LISTING 20.3 titlebar.jsp
<table width=”100%” border=”0”><tr> <td><img src=”/catalog/images/sams.gif” width=”171” height=”66”></td><td><div align=”center”><a href=”/catalog/ListShoppingCart.jsp”><img src=”/catalog/images/shopping_cart.gif” border=”0”></a></div></td></tr></table><hr>
The next section of your catalog layout is the Navigation section, the way that users willbrowse your list of movies by category. It will be contained in the navigation.jsp page. Thisfile contains a list of hard-coded hyperlinks that execute the ListMovies() service method,which will be defined in the following sections, with the category ID and target of the MovieList view. Figure 20.3 shows an image of your Navigation.
![Page 349: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/349.jpg)
FIGURE 20.3The Navigation section.
The source for the Navigation part of your views is in Listing 20.4.
LISTING 20.4 navigation.jsp
<table width=”129” border=”0”><tr> <td><a href=”/catalog/servlet/Controller?service=ListMovies&catid=1&target=/➥ListMovies.jsp”>Action/Adventure</a></td></tr><tr> <td><a href=”/catalog/servlet/Controller?service=ListMovies&catid=2&target=/➥ListMovies.jsp”>Comedy</a></td>
Servlet and JSP Web Applications
PART III330
![Page 350: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/350.jpg)
</tr><tr> <td><a href=”/catalog/servlet/Controller?service=ListMovies&catid=3&target=/➥ListMovies.jsp”>Drama</a></td></tr><tr> <td><a href=”/catalog/servlet/Controller?service=ListMovies&catid=4&target=/➥ListMovies.jsp”>Children/Family</a></td></tr><tr> <td><a href=”/catalog/servlet/Controller?service=ListMovies&catid=5&target=/➥ListMovies.jsp”>Suspense/Thriller</a></td></tr><tr> <td><a href=”/catalog/servlet/Controller?service=ListMovies&catid=6&target=/➥ListMovies.jsp”>Sci-Fi/Horror</a></td></tr><tr> <td><a href=”/catalog/servlet/Controller?service=ListMovies&catid=7&target=/➥ListMovies.jsp”>Classics</a></td></tr><tr> <td>
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
331
LISTING 20.4 Continued
![Page 351: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/351.jpg)
<a href=”/catalog/servlet/Controller?service=ListMovies&catid=8&target=/➥ListMovies.jsp”>Westerns</a></td></tr><tr><td><hr></td></tr><tr><td><a href=”/catalog/index.jsp”>Home</a></td></tr><tr><td><a href=”/catalog/servlet/Controller?service=CheckOut&target=/CheckOut.jsp”>Check Out</a></td></tr><tr><td><a href=”/catalog/servlet/Controller?service=EmptyCart&target=/index.jsp”>Empty Cart</a></td></tr></table>
The final section of your catalog layout is the client area. This will change based on the viewthat is currently being represented. Each view is described in the following sections. All viewswill use JSP includes to incorporate the Title Bar and Navigation into their individual layouts.
Index ViewThe Index view will be represented by the file index.jsp. It will act as the home page for yourcatalog. An image of the Index view is in Figure 20.4.
Servlet and JSP Web Applications
PART III332
LISTING 20.4 Continued
![Page 352: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/352.jpg)
FIGURE 20.4The Index view.
The source for the Index view is in Listing 20.5.
LISTING 20.5 index.jsp
<html><head><title>Sams Movie Catalog</title></head>
<body bgcolor=”#FFFFFF”><table width=”100%” border=”0”><tr> <td colspan=”2”><jsp:include page=”titlebar.jsp” flush=”true” /></td></tr><tr> <td width=”75”><%@ include file=”navigation.jsp” %></td><td valign=”top” ><div align=”center”><b>Welcome to the Sams Movie Catalog</b></div></td></tr></table></body></html>
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
333
![Page 353: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/353.jpg)
Movie List ViewThe Movie List view will be represented by the file ListMovies.jsp. It will display themovies as they relate to the categories in your catalog. Figure 20.5 shows an image of theMovie List view.
Servlet and JSP Web Applications
PART III334
FIGURE 20.5The Movie List view.
The source for the Movie List view can be found in Listing 20.6.
LISTING 20.6 ListMovies.jsp
<%@ page import=”java.util.*” %><html><head><title>Movie List</title></head>
<body bgcolor=”#FFFFFF”><table width=”100%” border=”0”><tr> <td colspan=”2”><%@ include file=”titlebar.jsp” %></td></tr><tr>
![Page 354: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/354.jpg)
<td width=”75” valign=”top”><%@ include file=”navigation.jsp” %></td><td valign=”top”><table cellspacing=”0” cellpadding=”2” border=”0” width=”600”>
<%Object[] movies = (Object[])request.getAttribute(“movies”);for ( int x = 0; x < movies.length; x++ ) {HashMap movie = (HashMap)movies[x];out.println(“<tr><td>” + movie.get(“title_name”) + “</td>” + “<td>” + movie.get(“price”) + “</td>” +“<td>” + movie.get(“quantity”) + “<td><a href=/catalog/servlet/Controller?service=AddToCart” +“&title_id=” + movie.get(“title_id”) +“&target=/ListShoppingCart.jsp>Buy</a></td></tr>”);
}%>
</table></td></tr></table></body></html>
Shopping Cart ViewThe Shopping Cart view will be represented by the file ListShoppingCart.jsp. It will display the current contents of the shopping cart. An image of the Shopping Cart view is inFigure 20.6.
The source for the Shopping Cart view is in Listing 20.7.
LISTING 20.7 ListShoppingCart.jsp
<%@ page errorPage=”errorpage.jsp” %><%@ page import=”java.util.*” %>
<!-- Instantiate the Counter bean with an id of “counter” --><jsp:useBean id=”cart” scope=”session” class=”ShoppingCart” /><html><head><title>Shopping Cart Contents</title></head><body bgcolor=”#FFFFFF”><table width=”100%” border=”0”><tr>
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
335
LISTING 20.6 Continued
![Page 355: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/355.jpg)
<td colspan=”2”><%@ include file=”titlebar.jsp” %></td></tr><tr> <td width=”75” valign=”top”><%@ include file=”navigation.jsp” %></td><td valign=”top”><table align=”top” width=”600” cellspacing=”0” cellpadding=”2” border=”0”><caption><b>Shopping Cart Contents</b></caption><tr><th align=”left”>Description</th><th>Price</th><th>Quantity</th></tr>
<%Enumeration enum = cart.getEnumeration();String[] tmpItem;// Iterate over the cartwhile (enum.hasMoreElements()) {
tmpItem = (String[])enum.nextElement();%>
<tr><td><%=tmpItem[1] %></td><td align=”center”>$<%=tmpItem[2] %></td><td align=”center”><%=tmpItem[3] %></td></tr>
<%}%>
</table></body></html>
Check Out ViewThe Check Out view will be represented by the file CheckOut.jsp. It will empty the shoppingcart and respond with a thank you message. An image of the Check Out view is in Figure 20.7.
Servlet and JSP Web Applications
PART III336
LISTING 20.7 Continued
![Page 356: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/356.jpg)
FIGURE 20.6The Shopping Cart view.
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
337
FIGURE 20.7The Check Out view.
The source for the Check Out view is in Listing 20.8.
![Page 357: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/357.jpg)
LISTING 20.8 CheckOut.jsp
<html><head><title>Sams Movie Catalog</title><meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1”></head>
<body bgcolor=”#FFFFFF”><table width=”100%” border=”0”><tr> <td colspan=”2”><jsp:include page=”titlebar.jsp” flush=”true” /></td></tr><tr> <td width=”75”><%@ include file=”navigation.jsp” %></td><td valign=”top” ><div align=”center”><b>Thanks for shopping with Sams</b></div></td></tr></table></body></html>
ControllersYou now have an idea as to what the site will look like, so we will add the functionality tomake it work. The first steps in doing this are adding the necessary service classes that includethe business logic. You will be adding four services. Each of these classes will implement theService interface. The following sections describe each of these classes and where they fit intoyour Web application. As you look over these implementations of the Service interface, noticehow simple it is to add new functionality to the Web application.
The ListMovies ServiceThe most important part of the ListMovies class is its implementation of the Service.execute() method. This is where all of its major functionality exists. The execute()method starts its execution when a user selects a category from navigation.jsp, which listsall of the categories found in the catalog. When its execution starts it gets the category ID from the request and performs a select statement on the Titles table, returning a ResultSetcontaining a list of movies with the chosen category ID. When the ResultSet is returned it isconverted into an array of HashMaps and put back on the request to be iterated over by thenamed target, which in this case is the previously listed ListMovies.jsp. The source forListMovies is in Listing 20.9.
Servlet and JSP Web Applications
PART III338
![Page 358: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/358.jpg)
LISTING 20.9 ListMovies.java
import Service;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.ServletContext;
import java.sql.*;import java.util.*;
import ConnectionPool.*;public class ListMovies implements Service {public ListMovies() {
}
// Returns a Vector containing the column names found in the passed// in ResultSetprivate Vector getResultSetColumnNames(ResultSet rs)throws Exception {try {// Get a reference to the ResultSet’s meta dataResultSetMetaData md = rs.getMetaData();// Get the number of columns returned in the Result Setint count = md.getColumnCount();// Create a Vector to hold the Column NamesVector columnNames = new Vector(count);// Get all of the Column Namesfor ( int x = 0; x < count; x++ ) {
// The column name indexes begin at 1columnNames.addElement(md.getColumnName(x + 1));
}return columnNames;
}catch (SQLException sqlex) {throw new Exception(sqlex.getMessage());
}}
/*Parse the ResultSet returning an array of HashMaps
*/public Object[] parseResultSet(ResultSet rs) throws Exception {Vector results = new Vector();// Iterate over the ResultSetVector columnNames = getResultSetColumnNames(rs);if ( rs == null ) {
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
339
![Page 359: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/359.jpg)
throw new Exception(“ResultSet is null”);}
int count = 0;while ( rs.next() ) {HashMap row = new HashMap();for ( int x = 0; x < columnNames.size(); x++ ) {String rsColumn = (String)columnNames.elementAt(x);String rsValue = rs.getString(rsColumn);if ( rsValue == null ) {rsValue = new String(“”);
}
row.put(rsColumn, rsValue);}
results.add(row);}
// Return the resultreturn results.toArray();
}
/*implemented method from Service interface
*/public void execute(HttpServletRequest request,HttpServletResponse response,ServletContext context) throws Exception {// Get category_id from the requestString catid = request.getParameter(“catid”);// Get a database connection from CATALOG_POOLConnectionPool pool =(ConnectionPool)context.getAttribute(“CATALOG_POOL”);Connection con = pool.getConnection();try {if ( con != null ) {Statement statement = con.createStatement();// Get titles with matching category idStringBuffer query = new StringBuffer(“SELECT * FROM TITLES”);query.append(“ WHERE CATEGORY_ID = “ + catid);ResultSet rs =statement.executeQuery(query.toString());Object[] movies = parseResultSet(rs);// Add the resulting movies to the requestrequest.setAttribute(“movies”, movies);
Servlet and JSP Web Applications
PART III340
LISTING 20.9 Continued
![Page 360: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/360.jpg)
}}
finally {pool.releaseConnection(con);
}}
}
The AddToCart ServiceThe AddToCart class is also an implementation of the Service.execute() method. Its execute() method starts its execution when a user selects a movie from the ListMovies.jsp,which lists all of the movies found as a result of the ListMovies service. It gets the ID of theselected movie from the request and performs a select statement on the Titles table, returning aResultSet containing the movie’s attributes. It then adds these attributes to the ShoppingCartfound in the user’s HttpSession and forwards the process to the named target on the request,which in this case is the previously listed ListShoppingCart.jsp. The source for theAddToCart service is in Listing 20.10.
LISTING 20.10 AddToCart.java
import Service;import ShoppingCart;import ConnectionPool.*;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import javax.servlet.http.HttpServletResponse;import javax.servlet.ServletContext;
import java.sql.*;public class AddToCart implements Service {public AddToCart() {
}
/*implemented method from Service interface
*/public void execute(HttpServletRequest request,HttpServletResponse response,ServletContext context) throws Exception {
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
341
LISTING 20.9 Continued
![Page 361: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/361.jpg)
// Get category_id from the requestString title_id = request.getParameter(“title_id”);// Get a database connection from CATALOG_POOLConnectionPool pool =(ConnectionPool)context.getAttribute(“CATALOG_POOL”);Connection con = pool.getConnection();try {if ( con != null ) {Statement statement = con.createStatement();// Get the title info. from the databaseStringBuffer query = new StringBuffer(“SELECT * FROM TITLES”);query.append(“ WHERE TITLE_ID = “ + title_id);ResultSet rs =statement.executeQuery(query.toString());if ( rs.next() ) {String id = rs.getString(“title_id”);String desc = rs.getString(“title_name”);float price = rs.getFloat(“price”);// Check the HttpSession for an exist ShoppingCartHttpSession session = request.getSession();ShoppingCart cart =(ShoppingCart)session.getAttribute(“cart”);if ( cart == null ) {// if no ShoppingCart was found create one and add// to the HttpSessioncart = new ShoppingCart();session.setAttribute(“cart”, cart);
}// Add the selected item to the ShoppingCartcart.addItem(id, desc, price, 1);
}else {throw new Exception(“Could not find title!”);
}}
}finally {pool.releaseConnection(con);
}
}}
Servlet and JSP Web Applications
PART III342
LISTING 20.10 Continued
![Page 362: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/362.jpg)
The EmptyCart ServiceThe EmptyCart class, like all other services, is also an implementation of the Service.execute() method. Its execute() method starts its execution when a user selects the Empty Cart link from the navigation.jsp page. It then gets a reference to the user’sShoppingCart found in the HttpSession and calls the empty() method. The process is thenforwarded to the named target on the request, which in this case is the previously listedindex.jsp. The source for the EmptyCart service is in Listing 20.11.
LISTING 20.11 EmptyCart.java
import Service;import ShoppingCart;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import javax.servlet.ServletContext;
public class EmptyCart implements Service {public EmptyCart() {
}
/*implemented method from Service interface
*/public void execute(HttpServletRequest request,HttpServletResponse response,ServletContext context) throws Exception {// Check the HttpSession for an exist ShoppingCartHttpSession session = request.getSession();ShoppingCart cart =(ShoppingCart)session.getAttribute(“cart”);if ( cart != null ) {// If there was an existing cart empty itcart.empty();
}}
}
The CheckOut ServiceThe CheckOut service acts exactly like the EmptyCart service, except the result is forwarded tothe CheckOut.jsp page. This is where you would complete the process by sending the results
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
343
![Page 363: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/363.jpg)
through some sort of fulfillment process. The source for the CheckOut service is in Listing 20.12.
LISTING 20.12 CheckOut.java
import Service;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import javax.servlet.ServletContext;
public class CheckOut implements Service {public CheckOut() {
}
/*implemented method from Service interface
*/public void execute(HttpServletRequest request,HttpServletResponse response,ServletContext context) throws Exception {// Check the HttpSession for an exist ShoppingCartHttpSession session = request.getSession();ShoppingCart cart = (ShoppingCart)session.getAttribute(“cart”);if ( cart != null ) {// If there was an existing cart empty itcart.empty();
}}
}
Using the Online CatalogIn this section you will use the Catalog Web application. This is where you will see how pow-erful a server-side implementation of the MVC is. Make sure you have completed the follow-ing steps:
1. Create the Catalog Web application.
2. Set up the CatalogConnectionPool as described in the previous sections, including mak-ing sure the ConnectionPool package is in your classpath.
3. Move all JSPs to the <SERVER_ROOT>/webapps/catalog/ directory.
Servlet and JSP Web Applications
PART III344
![Page 364: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/364.jpg)
4. Make sure that the Service and Controller classes are in your classpath.
5. Compile all of the service implementations and moved the class files to the<SERVER_ROOT>/webapps/catalog/WEB-INF/classes/ directory.
After you have started the Tomcat server, open your browser to the following URL:
http://localhost/catalog/index.jsp
You should see the catalog’s home page, shown earlier in the chapter in Figure 20.4.
Next you should choose a category from the left side of the page. Selecting the Comedy cate-gory gives the results shown in Figure 20.5.
Now click the Buy link a few times to add movies to your shopping cart and select theShoppingCart image. You should see an image similar to Figure 20.6.
To complete your transaction, select the Check Out link. This will empty your current cart anddisplay a thank you message. Figure 20.7 shows a completed transaction.
SummaryThis chapter gave an example of how you can leverage your server-side implementation of theMVC, as described in Chapter 13.
In the next chapter we will cover another case study using our server-side MVC to build a Webclient into an LDAP server.
Catalog Case Study
CHAPTER 20
20
CA
TALO
GC
ASE
STU
DY
345
![Page 365: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/365.jpg)
![Page 366: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/366.jpg)
CHAPTER
21An LDAP Web Client
IN THIS CHAPTER• Directory Requirements 348
• Models 348
• Views 349
• Controllers 356
• Using the LDAP Application 360
![Page 367: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/367.jpg)
Servlet and JSP Web Applications
PART III348
Directory Requirements
To follow the examples in this chapter, you will need to create a Web applicationnamed ldap, following the steps in Appendix A, “Web Applications and Configuringthe Servlet Engine.” Make sure you have the classes Controller and Service in yourWeb application’s classpath. You will also need to have, from Chapter 11, “Servletsand LDAP,” the classes LDAPObject and LDAPManager in your Web application’s class-path.
NOTE
In this chapter you will again create an online directory service. This system will be based onthe server-side implementation of the MVC as defined in Chapter 13, “A Servlet Controller.” Itwill be a front end to a Lightweight Directory Access Protocol (LDAP) server. The basicrequirements are defined as follows:
• Directory—The LDAP application must enable the user to list the current directory ofthe LDAP People object.
• Insert—The LDAP application must enable the user to enter a new People object.
• Delete—The LDAP application must enable the user to select a People object from thedirectory to remove from the server.
ModelsThe only model that you will describe is a subset of the People object as defined by the LDAPserver. This object will be managed by your LDAPObject from Chapter 11. Table 21.1 lists theelements needed to represent a People object.
TABLE 21.1 Required Attributes to Model a People Object
Attribute Type
uid String
sn String
givenName String
mail String
telephoneNumber String
dn String
In addition to the LDAPObject you will use the LDAPManager, also from Chapter 11, to commu-nicate with your LDAP server.
![Page 368: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/368.jpg)
ViewsNow you need to define the interface that your users will interact with. From the requirementsdefined in the first section of this chapter, you will need to create three Views.
The Directory Layout Each of these pages, excluding the error page, will have the basic layout found in Figure 21.1.
An LDAP Web Client
CHAPTER 12
21
AN
LDA
P WEB
CLIEN
T349
Title Bar
Client Area
Navigation
FIGURE 21.1The Directory View Layout.
There are three basic parts to the directory layout. Starting from the top you have the TitleBar. This is where you will have a simple graphic. This Title Bar will be at the top of allyour Views. It will be represented by the titlebar.jsp page. Figure 21.2 contains an image ofthe real contents of the Title Bar.
FIGURE 21.2The Title Bar.
![Page 369: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/369.jpg)
The source for the Title Bar is in Listing 21.1.
LISTING 21.1 titlebar.jsp
<table width=”100%” border=”0”><tr> <td><img src=”/ldap/images/sams.gif” width=”171” height=”66”></td>
</table><hr>
The next section of your online directory layout is the Navigation section. It is how you willchoose the actions that you will perform. The navigation.jsp page will contain the JSP func-tionality to build the Navigation portion of your ldap application. This file contains a list ofhard-coded hyperlinks that execute the LDAPDirectory and LDAPInsert services, which will bedefined in the following sections. Figure 21.3 contains an image of the Navigation section ofthe layout.
Servlet and JSP Web Applications
PART III350
FIGURE 21.3The Navigation section.
The source for the Navigation part of your Views is in Listing 21.2.
LISTING 21.2 navigation.jsp
<table width=”129” border=”0”><tr> <td><a href=”/ldap/servlet/Controller?service=LDAPDirectory&target=/
➥directory.jsp”>
![Page 370: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/370.jpg)
Directory</a></td>
</tr><tr> <td><a href=”/ldap/insert.jsp”>Add</a></td>
</tr><td><hr>
</td></tr><tr><td><a href=”/ldap/index.jsp”>Home</a></td>
</tr></table>
The final section of your online directory layout is the client area. This will change based onthe view that is currently being represented. The views are described in the following sections.All of your views will use JSP includes to incorporate the Title Bar and Navigation intotheir individual layouts.
Index ViewThe Index View will be represented by the file index.jsp. It will act as the home page foryour ldap application. An image of the Index View is in Figure 21.4.
An LDAP Web Client
CHAPTER 12
21
AN
LDA
P WEB
CLIEN
T351
LISTING 21.2 Continued
FIGURE 21.4The Index View.
The source for the Index View is in Listing 21.3.
![Page 371: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/371.jpg)
LISTING 21.3 index.jsp
<html><head><title>Sams Online Directory</title></head>
<body bgcolor=”#FFFFFF”><table width=”100%” border=”0”><tr> <td colspan=”2”><jsp:include page=”titlebar.jsp” flush=”true” />
</td></tr><tr> <td width=”75”><%@ include file=”navigation.jsp” %></td><td valign=”top” ><div align=”center”><b>Welcome to the Sams Online Directory</b>
</div></td>
</tr></table></body></html>
Directory ViewThe Directory View will be represented by the file directory.jsp. It will display the currentcontents of the directory server. An image of the Directory View is in Figure 21.5.
The source for the Directory View is in Listing 21.4.
LISTING 21.4 directory.jsp
<%@ page import=”LDAPObject” %><%@ page import=”java.util.*” %>
<jsp:useBean id=”directory” scope=”request” class=”java.util.Vector” />
<html><head><title>Sams Online Directory</title></head>
<body bgcolor=”#FFFFFF”><table width=”100%” border=”0”><tr>
Servlet and JSP Web Applications
PART III352
![Page 372: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/372.jpg)
<td colspan=”2”><jsp:include page=”titlebar.jsp” flush=”true” />
</td></tr><tr> <td valign=”top”width=”75”><%@ include file=”navigation.jsp” %>
</td><td><table width=”500”><tr align=”left”><th>Last Name</th><th>First Name</th><th>Email</th><th>Phone</th>
</tr>
<%Iterator iter = directory.iterator();while (iter.hasNext()) {
LDAPObject lobj = (LDAPObject)iter.next();
out.println(“<tr>”);out.println(“<td>” + lobj.getAttribute(“sn”) +“</td>”);
out.println(“<td>” + lobj.getAttribute(“givenName”) +“</td>”);
out.println(“<td>” + lobj.getAttribute(“mail”) +“</td>”);
out.println(“<td>” + lobj.getAttribute(“telephoneNumber”) +“</td>”);
out.println(“<td><a href=\”/ldap/servlet/Controller?”+ “service=LDAPDelete”+ “&dn=” + lobj.getDn() + “&target=/index.jsp\”” +“>Delete</a></td>”);
out.println(“</tr>”);}
%></table>
</td></tr>
</table></body></html>
An LDAP Web Client
CHAPTER 12
21
AN
LDA
P WEB
CLIEN
T353
LISTING 21.4 Continued
![Page 373: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/373.jpg)
FIGURE 21.5The Directory View.
Add ViewThe next JSP that we will look at serves as the View for our LDAPInsert service. It contains anHTML form that queries the user for the attributes associated with a People object. Figure21.6 shows an image of the Add View.
Listing 21.5 gives the source for the Add View.
LISTING 21.5 insert.jsp
<html><head><title>Sams Online Directory</title>
</head>
<body bgcolor=”#FFFFFF”><table width=”100%” border=”0”><tr> <td colspan=”2”><jsp:include page=”titlebar.jsp” flush=”true” />
</td>
Servlet and JSP Web Applications
PART III354
![Page 374: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/374.jpg)
</tr><tr> <td valign=”top” width=”75”><%@ include file=”navigation.jsp” %>
</td><td valign=”top” ><form method=”post”action=”/ldap/servlet/Controller?service=LDAPInsert”><input type=”hidden” name=”target” value=”/index.jsp”><table width=”75%” border=”0”><tr><td>User Id</td><td><input type=”text” name=”uid”>
</td></tr><tr><td>First Name</td><td><input type=”text” name=”givenName”>
</td></tr><tr><td>Last Name</td><td><input type=”text” name=”sn”></td>
</tr><tr><td>Email</td><td><input type=”text” name=”mail”></td>
</tr><tr><td>Telephone</td><td><input type=”text” name=”tn”></td>
</tr><tr><td> </td><td><input type=”Submit” name=”Submit”></td>
</tr></table></form></td>
</tr></table></body></html>
An LDAP Web Client
CHAPTER 12
21
AN
LDA
P WEB
CLIEN
T355
LISTING 21.5 Continued
![Page 375: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/375.jpg)
FIGURE 21.6The Add View.
ControllersNow that you have an idea as to what the site is going to look like, let’s add the functionalityto actually make it work. Your first steps in doing this are adding the necessary Service classesthat include your business logic. You will add three services. Each of these classes will imple-ment the Service interface. The following sections describe each of these classes and wherethey fit into your Web application.
The LDAPDirectory ServiceThe LDAPDirectory class, like all other service classes in your server-side model, implementsthe Service interface. The implemented execute() method is where all of its major function-ality exists. It starts its execution when a user selects the Directory link in thenavigation.jsp. When its execution starts it uses the LDAPManager to perform a wildcardsearch for all People objects in the virtuas.com domain. The resulting LDAPObjects are thenadded to the request object and forwarded to the named target, which in this case is the previ-ously listed directory.jsp. The source for LDAPDirectory is in Listing 21.6.
Servlet and JSP Web Applications
PART III356
![Page 376: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/376.jpg)
LISTING 21.6 LDAPDirectory.java
import java.util.*;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.ServletContext;
import LDAPManager;
public class LDAPDirectory implements Service {
/** Creates new LDAPDirectory */public LDAPDirectory() {
}
/*** Single method to become a service.** @throws Exception if any exceptions need to be thrown back* to the calling Controller.*/public void execute(HttpServletRequest request,HttpServletResponse
response,ServletContext context) throws Exception {
// define what results we want from the searchString[] returnAtts = {“sn”,
“givenName”,“mail”,“telephoneNumber”};
// create a wildcard search filterString filter = “uid=*”;
// create and initialize an LDAPManagerLDAPManager lm = new LDAPManager();lm.setSearchBase(“ou=People,o=virtuas.com”);
// perform the searchVector results = null;
// Get a list of All Personsresults = lm.search(returnAtts, filter);request.setAttribute(“directory”, results);
} }
An LDAP Web Client
CHAPTER 12
21
AN
LDA
P WEB
CLIEN
T357
![Page 377: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/377.jpg)
The LDAPInsert ServiceThe LDAP class is also an implementation of the Service interface. Its execute() method startsits execution when a user selects the Add link from the navigation.jsp page and submits thecompleted form on the insert.jsp page. It then gets the required attributes to create a newPeople object and calls the LDAPManager.add() method with a HashMap filled with theretrieved attributes. The source for the LDAPInsert service is in Listing 21.7.
LISTING 21.7 LDAPInsert.java
import java.util.*;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.ServletContext;
import LDAPManager;
public class LDAPInsert implements Service {
public LDAPInsert() {
}
/*** Single method to become a service.** @throws Exception if any exceptions need to be thrown back* to the calling Controller.*/public void execute(HttpServletRequest request,
HttpServletResponse response,ServletContext context) throws Exception {
String[] objectClass = {“top”,“person”,“organizationalPerson”,“inetOrgPerson”};
// Get the uid off of the requestString uid = request.getParameter(“uid”);
// Get the sn off of the requestString sn = request.getParameter(“sn”);
Servlet and JSP Web Applications
PART III358
![Page 378: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/378.jpg)
// Get the givenName off of the requestString givenName = request.getParameter(“givenName”);
// Get the mail off of the requestString mail = request.getParameter(“mail”);
// Get the tn off of the requestString tn = request.getParameter(“tn”);
// Create the UIDString dn = “uid=” + uid + “,ou=People,o=virtuas.com”;
// Build the HashMap of Attribute to addHashMap atts = new HashMap();atts.put(“cn”, givenName + “ “ + sn);atts.put(“sn”, sn);atts.put(“givenName”, givenName);atts.put(“uid”, uid);atts.put(“mail”, mail);atts.put(“telephoneNumber”, tn);
// create and initialize an LDAPManagerLDAPManager lm = new LDAPManager();
// Add the Person to the directorylm.add(dn, atts, objectClass);
}}
The LDAPDelete ServiceThe LDAPDelete class is also an implementation of the Service interface. Its execute()method starts its execution when a user selects the Delete link after a LDAPDirectory servicehas forwarded search results to the directory.jsp page. It then gets the dn from the requestand passes it to the LDAPManager.remove() method, which removes the named People objectfrom the LDAP server. Listing 21.8 gives the source for the LDAPDelete service.
LISTING 21.8 LDAPDelete.java
import java.util.*;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
An LDAP Web Client
CHAPTER 12
21
AN
LDA
P WEB
CLIEN
T359
LISTING 21.7 Continued
![Page 379: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/379.jpg)
import javax.servlet.ServletContext;
import LDAPManager;
public class LDAPDelete implements Service {
/** Creates new LDAPDelete */public LDAPDelete() {
}
/*** Single method to become a service.** @throws Exception if any exceptions need to be thrown back* to the calling Controller.*/public void execute(HttpServletRequest request,
HttpServletResponse response,ServletContext context) throws Exception {
// Get the dn off of the requestString dn = request.getParameter(“dn”);
// create and initialize an LDAPManagerLDAPManager lm = new LDAPManager();
// Remove the Person from the Serverlm.remove(dn);
}}
Using the LDAP ApplicationNext you will use the ldap Web application. Make sure you have completed the followingsteps:
1. Created the ldap web application
2. Made sure that the Netscape Directory Server is configured according to Chapter 11
3. Moved all JSPs to the <SERVER_ROOT>/webapps/ldap/ directory
Servlet and JSP Web Applications
PART III360
LISTING 21.8 Continued
![Page 380: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/380.jpg)
4. Made sure that the Service, Controller, LDAPObject, and LDAPManager classes are inyour classpath
5. Compiled all of the service implementations and moved the class files to the<SERVER_ROOT>/webapps/ldap/WEB-INF/classes/ directory
After you have started the Tomcat server, open your browser to the following URL:
http://localhost/ldap/index.jsp
You should see the ldap home page (refer to Figure 21.4).
Select the Directory link. (Refer to Figure 21.5, which shows the results.)
Click the Delete link beside one of the listings on the directory.jsp page. You will be redi-rected to the index.jsp page. To see the results of the Delete select the Directory link again.The user you selected should no longer be listed.
The final action you will perform is adding a People object. To do this, select the Add link andfill in the form shown. After this is complete click the Submit Query button to insert the user.Now select the Directory link once more and you should see your newly added entry.
SummaryThis chapter gave another example of how you can leverage your server-side implementationof the MVC, by implementing a Web front end to an LDAP server.
In the next chapter, you will work through another case study using your server-side MVC tobuild a simple online stock trading application.
An LDAP Web Client
CHAPTER 12
21
AN
LDA
P WEB
CLIEN
T361
![Page 381: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/381.jpg)
![Page 382: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/382.jpg)
CHAPTER
22A Stock Trader
IN THIS CHAPTER• Trader Requirements 364
• Models 364
• Views 367
• Controllers 375
• Using the Trader Application 382
![Page 383: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/383.jpg)
Servlet and JSP Web Applications
PART III364
Trader Requirements
You will need to create a Web application named Trader, following the steps inAppendix A, “Web Applications and Configuring the Servlet Engine,” and make sureyou have the classes ConnectionPool, Controller, and Service in your Web applica-tion’s classpath.
NOTE
In this chapter you are again going to put your newly found knowledge to practical use by cre-ating a simplified stock trading system. This system will be based on the server-side imple-mentation of the MVC as defined in Chapter 13 “A Servlet Controller.” The basic requirementsare defined as follows:
• Get a Quote—The trader application must allow a user to enter a stock symbol andreceive corresponding last trade, bid, and ask prices.
• Sell a Stock—The trader application must give the user the ability to enter a stock sym-bol and an asking price for selling a stock.
• Buy a Stock—The trader application must give the user the ability to enter a stock sym-bol and a bid price for buying a stock.
For this example, we will not keep up with anything except the last committed trans-action, nor will we have user accounts. All stock will be traded with integer pricingonly. This example is just to show how easy it is to extend an application using theMVC.
NOTE
ModelsThis section of the requirements defines the database representation of the trader application.Only one object in the application will be modeled in the database—the stocks table. For ourpurposes we will not build an object representation of the database. We will simply use SQLand iterate over ResultSets.
The stocks object that will be represented in the database is the stock object itself. Each of thestock object’s attributes must be included in the table representation. Table 22.1 lists therequired elements needed to store a stock object.
![Page 384: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/384.jpg)
TABLE 22.1 Required Attributes to Model a Stock
Attribute Type
symbol String
price int
bid int
ask int
To make the stocks table available to your application, you must set up an ODBC data sourcefollowing the same steps used in Chapter 7 “Servlets, JDBC, and Inter-ServletCommunications.” You will need to use trader as the data source name and select thetrader.mdb file included in this chapter’s source code.
To complete your configuration of the database you will need to create a servlet that initializesthe ConnectionPool created in Chapter 7 with the appropriate setting for this application.
The source for the extension of the ConnectionPoolServlet is in Listing 22.1.
LISTING 22.1 TraderConnectionPool
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;
import ConnectionPool.ConnectionPool;
public class TraderConnectionPool extends HttpServlet {
//Initialize global variablespublic void init(ServletConfig config)throws ServletException {
super.init(config);
// Instantiate the ConnectionPoolConnectionPool pool = new ConnectionPool();
try {
// Set the JDBC Driverpool.setDriver(“sun.jdbc.odbc.JdbcOdbcDriver”);pool.setURL(“jdbc:odbc:trader”);pool.setSize(2);
A Stock Trader
CHAPTER 22
22
A S
TOC
KT
RA
DER
365
![Page 385: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/385.jpg)
// Set the Usernamepool.setUsername(“”);// Set the Passwordpool.setPassword(“”);
// Initialize the poolpool.initializePool();
// Once the pool is Initialized, add it to the// Global ServletContext. This makes it available// To other servlets using the same ServletContext.ServletContext context = getServletContext();context.setAttribute(“TRADER_POOL”, pool);System.err.println(“ADDED TRADER_POOL”);
}catch (Exception e) {
System.err.println(e.getMessage());}
}
//Process the HTTP Get requestpublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
// Set the response content-typeresponse.setContentType(“text/html”);// get the Writer objectPrintWriter out = response.getWriter();out.println(“This Servlet does not service requests!”);out.close();
}
public void destroy() {
// Access the ServletContext using the getAttribute()// method, which returns a reference to the ConnectionPool.ServletContext context = getServletContext();ConnectionPool pool =
(ConnectionPool)context.getAttribute(“TRADER_POOL”);
Servlet and JSP Web Applications
PART III366
LISTING 22.1 Continued
![Page 386: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/386.jpg)
if ( pool != null ) {
// empty the poolpool.emptyPool();// Remove the Attribute from the ServletContextcontext.removeAttribute(“TRADER_POOL”);
}else {
System.err.println(“Could not get a reference to Pool!”);}
}}
The only change from the ConnectionPoolServlet found in Chapter 7 is the name of theservlet. The URL has been changed to point to the trader data source, and the number of con-nections has been set to two. Make sure you also add the following code snippet to the trader’sweb.xml file:
<servlet><servlet-name>TraderConnectionPool</servlet-name><servlet-class>TraderConnectionPool</servlet-class><load-on-startup>1</load-on-startup></servlet>
This snippet preloads the TraderConnectionPool when the Tomcat engine starts up.
ViewsNow you need to define the interface with which your users will interact. From the require-ments defined in the first section of this chapter, you will need to create four views and anerror page.
Trader LayoutEach of these pages, excluding the error page, will have the basic layout shown in Figure 22.1.
As you can see, the trader layout has three basic parts. Starting from the top is the Title Bar,where you see a simple graphic of the Sams logo plus an HTML stock quote form, which willdisplay the latest pricing for an entered stock symbol. This Title Bar will be at the top of all ofyour Views and will be represented by the titlebar.jsp page. Figure 22.2 shows an image ofthe real contents of the Title Bar.
A Stock Trader
CHAPTER 22
22
A S
TOC
KT
RA
DER
367
LISTING 22.1 Continued
![Page 387: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/387.jpg)
FIGURE 22.1The Trader View Layout.
Servlet and JSP Web Applications
PART III368
Title Bar
Client Area
Navigation
FIGURE 22.2The Title Bar.
The source for the Title Bar is in Listing 22.2.
LISTING 22.2 titlebar.jsp
<table width=”100%” border=”0”><tr> <td><img src=”/trader/images/sams.gif” width=”171” height=”66”></td><td align=”center”><form name=”GetQuote” action=”/trader/servlet/Controller”
method=”post”><input type=”text” name=”symbol” size=”5” maxlength=”5”><input type=”submit” name=”Get Quote” value=”Get Quote”><input type=”hidden” value=”GetQuote” name=”service”>
![Page 388: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/388.jpg)
<input type=”hidden” value=”/getquote.jsp” name=”target”></form>
</td></table><hr>
The next section of your trader layout is the Navigation section. It is how users will choose theactions that they will perform. The navigation.jsp page contains the JSP functionality tobuild the Navigation portion of your trader application. This file contains a list of hard-codedhyperlinks that execute the Buy and Sell services, which will be defined in the following sec-tions. Figure 22.3 shows an image of the Navigation.
A Stock Trader
CHAPTER 22
22
A S
TOC
KT
RA
DER
369
LISTING 22.2 Continued
FIGURE 22.3The Navigation.
The source for the Navigation part of your Views is in Listing 22.3.
LISTING 22.3 navigation.jsp
<table width=”129” border=”0”><tr> <td><a href=”/trader/tradeform.jsp”>Buy</a></td>
</tr><tr> <td><a href=”/trader/tradeform.jsp”>Sell</a></td>
</tr><tr><td><hr>
</td></tr>
![Page 389: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/389.jpg)
<tr><td><a href=”/trader/index.jsp”>Home</a></td>
</tr></table>
The final section of the trader layout is the client area. This will change based on the view thatis currently being represented. Each view is described in the following sections. All of yourviews will use JSP includes to incorporate the Title Bar and Navigation into their individuallayouts.
Index ViewThe Index View will be represented by the file index.jsp. It will act as the home page foryour Trader application. An image of the Index View is in Figure 22.4.
Servlet and JSP Web Applications
PART III370
LISTING 22.3 Continued
FIGURE 22.4The Index View.
The source for the Index View is in Listing 22.4.
![Page 390: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/390.jpg)
LISTING 22.4 index.jsp
<html><head><title>Sams Online Stock Trader</title></head>
<body bgcolor=”#FFFFFF”><table width=”100%” border=”0”><tr> <td colspan=”2”><jsp:include page=”titlebar.jsp” flush=”true” /></td>
</tr><tr> <td width=”75”><%@ include file=”navigation.jsp” %></td><td valign=”top” ><div align=”center”>
<b>Welcome to the Sams Online Stock Trader</b></div>
</td></tr>
</table></body></html>
Get Quote ViewThe Get Quote View will be represented by the file getquote.jsp. It will display the receivedstock’s last trading, bid, and ask prices. An image of the Get Quote View is in Figure 22.5.
The source for the Get Quote View is in Listing 22.5.
LISTING 22.5 getquote.jsp
<html><head><title>Sams Online Stock Trader</title></head>
<body bgcolor=”#FFFFFF”><table width=”100%” border=”0”><tr> <td colspan=”2”><jsp:include page=”titlebar.jsp” flush=”true” /></td>
</tr><tr>
A Stock Trader
CHAPTER 22
22
A S
TOC
KT
RA
DER
371
![Page 391: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/391.jpg)
<td width=”75”><%@ include file=”navigation.jsp” %></td><td valign=”top” ><div align=”left”><table border=”1” cellpadding=”0” cellspacing=”2” width=”500”>
<tr><th>Symbol</th><th>Price</th><th>Bid</th><th>Ask</th>
</tr><tr>
<td><div align=”center”><%=request.getAttribute(“symbol”) %></div></td><td><div align=”center”><%=request.getAttribute(“price”) %></div></td><td><div align=”center”><%=request.getAttribute(“bid”) %></div></td><td><div align=”center”><%=request.getAttribute(“ask”) %></div></td>
</tr></table></div></td>
</tr></table></body></html>
Buy/Sell ViewThe next JSP that we will look at serves as the view for both the Buy and Sell services. It con-tains an HTML form that lets you choose to either buy or sell a stock and specify what priceyou are bidding or asking. The choice you make to either buy or sell will determine which ser-vice you execute. An image of the Buy/Sell View is in Figure 22.6.
The source for the Buy/Sell View is in Listing 22.6.
Servlet and JSP Web Applications
PART III372
LISTING 22.5 Continued
![Page 392: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/392.jpg)
FIGURE 22.5The Get Quote View.
A Stock Trader
CHAPTER 22
22
A S
TOC
KT
RA
DER
373
FIGURE 22.6The Buy/Sell View.
![Page 393: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/393.jpg)
LISTING 22.6 tradeform.jsp
<html><head><title>Sams Online Stock Trader</title></head>
<body bgcolor=”#FFFFFF”><table width=”100%” border=”0”>
<tr> <td colspan=”2”><jsp:include page=”titlebar.jsp”
flush=”true” /></td></tr><tr>
<td width=”75”><%@ include file=”navigation.jsp” %></td><td valign=”top” ><div align=”center”><b>Trade Form</b>
<form name=”Trade” action=”/trader/servlet/Controller”method=”post”><table border=”0” cellpadding=”0” cellspacing=”2”
width=”400”><tr>
<th align=”left” colspan=3>Enter Stock Order</th></tr><tr>
<td>Symbol</td><td><input type=”text” name=”symbol” size=”5”></td><td>Buy:<input type=”radio” value=”Buy” name=”service”
➥checked></td></tr><tr>
<td>Price</td><td><input type=”text” name=”price” size=”5”></td><td>Sell:<input type=”radio” value=”Sell”
name=”service”></td></tr><tr align=”center”>
<td><input type=”submit” name=”submit”></td></tr></table><input type=”hidden” value=”/index.jsp” name=”target”>
</form></div>
</td></tr>
Servlet and JSP Web Applications
PART III374
![Page 394: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/394.jpg)
</table></body></html>
ControllersNow that you have an idea as to what the site will look like, let’s add the functionality to actu-ally make it work. Your first steps in doing this are going to be adding the necessary Serviceclasses that include your business logic. You will be adding three services. Each of these ofthese Service classes will implement the Service interface. The following sections describeeach of these classes and where they fit into your Web application.
The GetQuote ServiceThe GetQuote class, like all other service classes in your server-side model, implements theService interface. The implemented execute() method is where all of its major functionalityexists. It starts its execution when a user selects and enters a stock symbol into the form in thetitlebar.jsp and clicks the Get Quote button. When its execution starts, it gets the stocksymbol from the request and performs a select statement on the stocks table, returning aResultSet containing the attributes associated with the stock with the matching symbol. Thestock attributes are then added to the request object and forwarded to the named target, whichin this case is the previously listed getquote.jsp. The source for GetQuote is found in Listing22.7.
LISTING 22.7 GetQuote.java
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.ServletContext;
import java.sql.*;
import Service;import ConnectionPool.ConnectionPool;
public class GetQuote implements Service {
public GetQuote() {
}
A Stock Trader
CHAPTER 22
22
A S
TOC
KT
RA
DER
375
LISTING 22.6 Continued
![Page 395: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/395.jpg)
/*implemented method from Service interface*/public void execute(HttpServletRequest request,
HttpServletResponse response,ServletContext context) throws Exception {
// Get the symbol from the requestString symbol = request.getParameter(“symbol”);
if ( symbol == null ) {
thrownew Exception(“You must enter a stock symbol to query.”);
}
// Get a database connection from TRADER_POOLConnectionPool pool =
(ConnectionPool)context.getAttribute(“TRADER_POOL”);Connection con = pool.getConnection();
try {
if ( con != null ) {
// Get the stock information from the databaseStatement statement = con.createStatement();
StringBuffer query =new StringBuffer(“SELECT * FROM STOCKS”);
query.append(“ WHERE SYMBOL = \’” + symbol + “\’”);
System.err.println(“Executing : “ + query.toString());
ResultSet rs =statement.executeQuery(query.toString());
System.err.println(“Executed : “ + query.toString());
if ( rs.next() ) {
// Add the stock attribute to the requestrequest.setAttribute(“symbol”,
rs.getString(“symbol”));
Servlet and JSP Web Applications
PART III376
LISTING 22.7 Continued
![Page 396: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/396.jpg)
request.setAttribute(“price”, rs.getString(“price”));request.setAttribute(“bid”, rs.getString(“bid”));request.setAttribute(“ask”, rs.getString(“ask”));
}}
}finally {
// release the database connection back into the poolpool.releaseConnection(con);
}}
}
The Buy ServiceThe Buy class is also an implementation of the Service interface. Its execute() method startsits execution when a user selects the Buy radio button and fills in symbol and price informa-tion from the tradeform.jsp page. It then gets the symbol and price from the request and per-forms a select statement on the stocks table, returning a ResultSet containing the stock’sattributes. It then checks for an existing ask price that is either less than or equal to the submit-ted bid price. If there is a satisfying ask price, the current price is set to the bid price and theask price is reset to 0. Otherwise the new bid is updated. The source for the Buy service is inListing 22.8.
LISTING 22.8 Buy.java
import java.sql.*;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.ServletContext;
import Service;import ConnectionPool.ConnectionPool;
public class Buy implements Service {
public Buy() {
}
A Stock Trader
CHAPTER 22
22
A S
TOC
KT
RA
DER
377
LISTING 22.7 Continued
![Page 397: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/397.jpg)
/*implemented method from Service interface*/public void execute(HttpServletRequest request,
HttpServletResponse response,ServletContext context) throws Exception {
// Get the symbol from the requestString symbol = request.getParameter(“symbol”);
if ( symbol == null ) {
thrownew Exception(“You must enter a stock symbol to purchase.”);
}
// Get the price from the requestString price = request.getParameter(“price”);
if ( price == null ) {
thrownew Exception(“You must enter a stock price to purchase.”);
}
// Get a database connection from TRADER_POOLConnectionPool pool =
(ConnectionPool)context.getAttribute(“TRADER_POOL”);Connection con = pool.getConnection();
try {
if ( con != null ) {
Statement statement = con.createStatement();
// Get the stocks attributesStringBuffer query =
new StringBuffer(“SELECT ASK FROM STOCKS”);query.append(“ WHERE SYMBOL = \’” + symbol + “\’”);
ResultSet rs =statement.executeQuery(query.toString());
Servlet and JSP Web Applications
PART III378
LISTING 22.8 Continued
![Page 398: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/398.jpg)
if ( rs.next() ) {
int ask = rs.getInt(“ask”);
int bid = ((new Integer(price)).intValue());
rs.close();
StringBuffer update = new StringBuffer(“UPDATE STOCKS”);
// Check to see if there is an// open ASK satisfying our BIDif ( bid >= ask && ask != 0 ) {
// if there is, then set the// price to the bid price// and reset the ask to 0update.append(“ SET PRICE = “ + price);update.append(“, ASK = 0”);update.append(“ WHERE SYMBOL = ‘“ + symbol + “‘“);
}else {
// if there is no match set the bid price // to the offered priceupdate.append(“ SET BID = “ + price);update.append(“ WHERE SYMBOL = ‘“ + symbol + “‘“);
}System.err.println(“Executing : “ +
update.toString());
statement.executeUpdate(update.toString());}
}}finally {
pool.releaseConnection(con);}
}}
A Stock Trader
CHAPTER 22
22
A S
TOC
KT
RA
DER
379
LISTING 22.8 Continued
![Page 399: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/399.jpg)
The Sell ServiceThe Sell class is also an implementation of the Service interface. Its execute() method startsits execution when a user selects the Sell radio button and fills in symbol and price informationfrom the tradeform.jsp page. It then gets the symbol and price from the request and performsa select statement on the stocks table, returning a ResultSet containing the stock’s attributes.It then checks for an existing bid price that is either greater than or equal to the submitted Askprice. If there is a satisfying bid price, the current price is set to the submitted ask price and thebid price is reset to 0. Otherwise the new ask is updated. The source for the Sell service isfound in Listing 22.9.
LISTING 22.9 Sell.java
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.ServletContext;
import Service;import java.sql.*;import ConnectionPool.ConnectionPool;
public class Sell implements Service {
public Sell() {
}
/*implemented method from Service interface*/public void execute(HttpServletRequest request,
HttpServletResponse response,ServletContext context) throws Exception {
// Get the symbol from the requestString symbol = request.getParameter(“symbol”);
if ( symbol == null ) {
thrownew Exception(“You must enter a stock symbol to purchase.”);
➥}
Servlet and JSP Web Applications
PART III380
![Page 400: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/400.jpg)
// Get the price from the requestString price = request.getParameter(“price”);
if ( price == null ) {
throw new Exception(“You must enter a stock price to purchase.”);
}
// Get a database connection from TRADER_POOLConnectionPool pool =
(ConnectionPool)context.getAttribute(“TRADER_POOL”);Connection con = pool.getConnection();
try {
if ( con != null ) {
// Check to see if there is an // open BID satisfying our ASKStatement statement = con.createStatement();
StringBuffer query = new StringBuffer(“SELECT BID FROM STOCKS”);
query.append(“ WHERE SYMBOL = \’” + symbol + “\’”);
// Get the stocks attributesResultSet rs =
statement.executeQuery(query.toString());
if ( rs.next() ) {
int bid = rs.getInt(“bid”);
int ask = ((new Integer(price)).intValue());
rs.close();
StringBuffer update = new StringBuffer(“UPDATE STOCKS”);
// Check to see if there is // an open BID satisfying our ASKif ( bid >= ask && ask != 0 ) {
A Stock Trader
CHAPTER 22
22
A S
TOC
KT
RA
DER
381
LISTING 22.9 Continued
![Page 401: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/401.jpg)
// if there is, then set the price // to the bid price// and reset the ask to 0update.append(“ SET PRICE = “ + price);update.append(“, BID = 0”);update.append(“ WHERE SYMBOL = ‘“ + symbol + “‘“);
}else {
// if there is no match set the ask // price to the offered priceupdate.append(“ SET ASK = “ + price);update.append(“ WHERE SYMBOL = ‘“ + symbol + “‘“);
}statement.executeUpdate(update.toString());
}}
}finally {
pool.releaseConnection(con);}
}}
Using the Trader ApplicationIn this section you are will use the Trader Web application. Make sure you have completed thefollowing steps:
1. Create the Trader Web application.
2. Set up the TraderConnectionPool as described in the previous sections, including mak-ing sure the ConnectionPool package is in your classpath.
3. Move all JSPs to the <SERVER_ROOT>/webapps/trader/ directory.
4. Make sure that the Service and Controller classes are in you classpath.
5. Compile all of the service implementations and move the class files to the<SERVER_ROOT>/webapps/trader/WEB-INF/classes/ directory.
After you have started the Tomcat server, open your browser to the following URL:
http://localhost/trader/index.jsp
You should see the Trader home page (refer to Figure 22.4).
Servlet and JSP Web Applications
PART III382
LISTING 22.9 Continued
![Page 402: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/402.jpg)
Next you should enter a symbol into the Get Quote form. For this limited application there arecurrently only four stocks to choose from—YHOO, SUNW, AMZN, and MSFT. Figure 22.5shows the result of entering YHOO.
Now click the Buy link and enter YHOO in the Symbol field, select the Buy button, and enter aprice greater than the Ask price returned from the GetQuote service. You will be redirected tothe index.jsp page. Now get the updated quote for YHOO using the same process as you didbefore. You should see a page reflecting a new price and the Ask price should be 0.
To use the Sell service, make sure there is a Bid for the stock you want to buy and enter a Sellprice that is lower.
SummaryIn this chapter we covered a very simple stock trading application that further validates howyou can leverage your server-side implementation of the MVC. At this point you should feelcomfortable with how you can combine servlets and JSPs using the MVC. You should alsohave a good understanding of the power and flexibility of a server-side implementation of theMVC.
A Stock Trader
CHAPTER 22
22
A S
TOC
KT
RA
DER
383
![Page 403: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/403.jpg)
![Page 404: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/404.jpg)
CHAPTER
23Wireless ApplicationDevelopment Using WAPby Bryan Morgan
IN THIS CHAPTER• WAP History: Past, Present, and Future 386
• Why WAP? 389
• WAP Architecture 391
• Emulators, Browsers, and Developer Tools 392
• Suggested Resources 395
![Page 405: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/405.jpg)
Servlet and JSP Web Applications
PART III386
This chapter and Chapter 24, “WML/WMLScript Development,” introduce you to wirelessapplication development using Java servlets and the Wireless Application Protocol (WAP).WAP is the product of the efforts of the WAP Forum (http://www.wapforum.org), an industryconsortium founded by Nokia, Ericsson, Unwired Planet, and Motorola. (Unwired Planet’sname was changed to Phone.com in 1999 and was changed yet again to Openwave after themerger of Phone.com and Software.com in 2000.) According to the WAP Forum, the goals ofWAP are
• Independent wireless network standard
• Open to all
• Proposed to the appropriate standards bodies
• Scalable across transport options
• Scalable across device types
• Extensible over time to new networks and transports
WAP content was originally designed to be accessed from wireless phones, but WAP browsersare now available for Palm-sized devices, pagers, and even standard desktop computers. Thischapter presents the components of the Wireless Application Protocol and the variety ofbrowsers and development tools that are available to the Java servlets developer. Chapter 24,will step through the development of a dynamic wireless application using Java servlets andWAP.
WAP History: Past, Present, and FutureFor such a young technology, WAP has truly had a turbulent history to date. If you will bedeveloping for mobile devices, it is important first to understand the brief history of WAP andits direction in the coming years.
The Past: Handheld Device Markup Language (HDML)In 1995, Unwired Planet introduced the Handheld Device Markup Language, or HDML, in anattempt to jump-start the market for wireless data access. HDML was essentially a subset ofHTML and it was a minor success.
Unfortunately, HDML had a couple of things going against it from the start. First, it was a pro-prietary language promoted by one company and supported only by that company’s browserproduct. Second, no lower-level protocols were defined to support security, interfacing to avariety of networks, or optimization for wireless devices’ tiny screens and low bandwidth. Outof this initial effort, WAP was born.
![Page 406: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/406.jpg)
Present: WAP Hits the StreetThe year 2000 will be viewed as the birth of the Wireless Internet. Some of the largest compa-nies on the planet are the telecommunications operators (such as NTT, AT&T, Verizon, BritishTelecom, and Deutsche Telekom) and they are eagerly looking to generate new revenuestreams to offset the leveling of revenues from voice communications.
As soon as WAP presented itself and the phones hit the market, massive marketing campaignsensued. The end result was an expectation in users’ minds that they would somehow pick up aphone and access Web content much as they were used to doing from their desktop computers.Given the tiny screens and poor data input capabilities of mobile phones, it was only naturalthat this expectation quickly fell on its face! The inevitable response to the hype heaped uponWAP was a backlash from the technology media, the stock market, and anyone who felt likecommenting.
Wireless Application Development Using WAP
CHAPTER 23
23
WIR
ELESSA
PPLICA
TION
DEV
ELOPM
ENT
387
Lessons Learned from the WAP BacklashFor software developers, one lesson learned from WAP’s initial foray into the marketis to concentrate on delivering valuable information quickly to your end user—bethat a stock quote, a weather report, or an address-book lookup. Snippets of infor-mation are perfectly fine for the mobile user; in fact, that is all that most mobileusers want. In situations where you believe that more information might be neces-sary, include an extra “More Information” link instead of trying to force-feed it allonto a tiny screen.
Another limitation to always keep in mind is the difficulty of data input, particularlyon a mobile phone’s keypad. When possible, always pre-populate text fields with“default” possibilities. If you will be developing a wireless information portal, build astandard Web front end that enables users to preset their preferences from the desk-top (such as their ZIP code for weather retrieval and movie times, their mailingaddress, favorite stock ticker symbols, and so on). Then, after logging in to your por-tal, their selections will be readily available without forcing users to repeatedly enterthe same information daily.
The Future: WAP 1.2 and BeyondAlthough it hasn’t achieved the original lofty projections, WAP has seen excellent market pen-etration and usage, particularly in Europe. It hasn’t had the success of its messaging cousin, theShort Message Service (SMS), which has taken Europe by storm, but WAP is still a popularwireless data service on that continent. (SMS is a feature of PCS phones that enables users toreceive and sometimes transmit short text messages using their wireless phone.)
![Page 407: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/407.jpg)
WAP has been somewhat overshadowed by a competitive technology, i-Mode, developed andsupported by NTT DoCoMo in Japan. i-Mode uses an HTML derivative (Compact HTML, orcHTML) for content display and runs on a packet-based network. At the time of this writing,DoCoMo claims 18,000,000 subscribers and is beginning to make inroads elsewhere across theworld. (For more information, visit http://www.nttdocomo.com/i/index.html.)
One technology to watch in the near future is XHTML (an XML-compliant version of HTML).Discussions have occurred between the WAP Forum and DoCoMo to transition both i-Modeand WAP to XHTML so that both technologies share a common markup language. With amove to a complete XML-based architecture, all content for a site could actually be stored inXML. Using a combination of XHTML, XSL, and RSS (all XML technologies), this baselinecontent could be “retrofitted” to any number of devices based on the profile of the accessingdevice. The World Wide Web Consortium (W3C) is currently working on this concept (formore information, visit http://www.w3c.org).
WAP 1.2–compliant phones will appear on the market in 2001. Among other things, WAP 1.2defines a Push framework (for the “push” of data to users based on predefined conditions) andthe Wireless Telephony Applications Interface (WTAI). Wireless push applications are some-what controversial because the initial primary use could be for the push of advertising mes-sages to mobile devices. How these messages will be targeted and how mobile consumers canchoose to filter them are of great interest to privacy advocates and to industry organizationssuch as the Wireless Advertising Association (WAA). The WTA Interface allowsWML/WMLScript applications to actually interact with the telephony-related functionality of amobile phone and a wireless network. For instance, WTA will
• Allow numbers to be dialed through the selection of a hyperlink
• Provide for programmatic access to a phone’s address book
• Send DTMF Tones programmatically
WTA capabilities will be included with WAP 1.2-compliant phones.
Servlet and JSP Web Applications
PART III388
Wireless TerminologyYou might find it helpful to familiarize yourself with this glossary of commonly usedwireless terms:
• Bearer Service—A telecommunications service that allows transmission of userinformation signals between user-network interfaces.
• Gateway—In a communications network, a network node equipped for interfac-ing with another network that uses different protocols.
![Page 408: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/408.jpg)
Why WAP?WAP was designed from the ground up to deliver content and applications to mobile deviceswith small screens, a variety of data input capabilities, and low communications bandwidth run-ning on a variety of network transports (including GSM, TDMA, CDMA, and CDPD). This sec-tion will present the various considerations that were taken into account when designing WAP.This discussion will hopefully clarify why a separate wireless standard was needed as opposedto simply reusing the venerable HTTP—HTML—TCP/IP technologies of the wired world.
Screen Size ConsiderationsOne feature that will always separate mobile devices from their larger wired desktop counter-parts is the actual size of the devices. Size is a premium consideration: the smaller, the better.Faced with this reality, most mobile device screens are tiny—a PalmOS device features a lofty160×160 pixel screen! Larger screen sizes also require additional battery power—a drivingconstraint in the design of mobile devices.
WAP, and specifically its markup language WML, were designed to ease the pain of a smallscreen. (If you’ve looked at the HTML specification, it’s clear that many advanced featureswould never work on a tiny screen.) WML delivers content in a single document composed ofmultiple “cards.” The purpose of this is that a single trip to the server could return multiple
Wireless Application Development Using WAP
CHAPTER 23
23
WIR
ELESSA
PPLICA
TION
DEV
ELOPM
ENT
389
• GPRS—General Packet Radio Service. A packet-based wireless communicationservice that promises data rates from 56–114Kbps and continuous connection tothe Internet for mobile phone and computer users.
• 3G—The next generation of wireless technology beyond PCS. The WorldAdministrative Radio Conference assigned 230 MHz of spectrum at 2GHz formultimedia 3G networks. These networks must be able to transmit wireless dataat 144Kbps at mobile user speeds, 384Kbps at pedestrian user speeds, and2Mbps in fixed locations.
• GSM—Global System for Mobile Communication. A digital mobile telephonesystem that is widely used in Europe and other parts of the world. GSM uses avariation of timed-division multiple access (TDMA).
• CDMA—Code Division Multiple Access. A spread spectrum air interface technol-ogy used in some digital cellular, personal communications services, and otherwireless networks.
• CDPD—Cellular Digital Packet Data. Also referred to as Wireless IP. A method ofsending and receiving information through mobile devices that uses theAdvanced Mobile Phone System (AMPS) and enables information to be trans-mitted on idle cellular voice channels.
![Page 409: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/409.jpg)
screens of information to a user. Lengthy documents can be divided into smaller bite-sizedpieces, which eases the display constraint. Also, links and extended logic (using the client-sidescripting language, WMLScript) enable the user to traverse through a tree of information with-out requiring constant trips back to a server. WAP also defines a unique image format, theWireless Bitmap or WBMP, which is essentially a one-pixel-depth compressed bitmap forgraphic display on constrained devices.
Network ConsiderationsUnlike the World Wide Web, WAP was designed to support a variety of networks and trans-ports, not just TCP/IP. As mentioned in the following section, “Bandwidth Considerations,”WAP can be delivered using a variety of bearers, including SMS and Circuit-Switched Data.(The bearer is a telecommunications service that enables transmission of user information sig-nals between user-network interfaces.) Because nearly all wireless networks are not yet packet-based, it was important to design a technology that transparently supported a wide variety ofunderlying networking protocols. WAP does this through the Wireless Datagram Protocol, orWDP. WDP is the interface to the wireless network’s bearer service, which can be a variety oftechnologies including SMS, CSD, CDMA, and UDP. WDP also provides support for errorcorrection, which comes in very handy given the “messy” connections often prevalent on wire-less networks.
Bandwidth ConsiderationsWhereas HTTP assumes a constant TCP/IP connection, WAP’s Wireless Transaction Protocol,or WTP, does not. In fact, TCP itself was deemed to be too burdensome for use on IP-basedwireless networks. On IP-based network connections (such as connections obtained from apacket-based network such as GPRS and CDPD), UDP (the User Datagram Protocol) is usedin conjunction with IP for information delivery. Bandwidth constraints are also addressedthrough data compression. A WML file stored on a server (or WML output from server-sidetechnologies such as Java servlets) is compressed into a WMLC file using a WAP Gateway thatsits between the server and the communications network. A WAP gateway has two primaryresponsibilities:
1. Act as an intermediary between the “back-end” TCP/IP network and the wireless net-work.
2. Encode textual WML/WMLScript content obtained from an HTTP server into a com-pressed binary format for delivery to the mobile device.
WAP gateways can also perform additional tasks. A few gateways on the market will actuallygrab HTML content and attempt to intelligently convert the content to WML on-the-fly.Several other gateways include HTTP and Java servlet scripting engines in the product directly.
Servlet and JSP Web Applications
PART III390
![Page 410: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/410.jpg)
WAP ArchitectureThe Wireless Application Protocol architecture consists of a series of software layers designedto mimic the International Standards Organization (ISO) Open Systems Interconnection (OSI)network model. If you are familiar with this model, you know that it defines seven independentlayers that can be used to architect a computer network. These seven layers are
• Physical Layer
• Data Link Layer
• Network Layer
• Transport Layer
• Session Layer
• Presentation Layer
• Application Layer
In an OSI-approved network, each of these layers operates independently of the other layers sothat any one layer can be replaced without disrupting the functionality of the network.
The WAP Protocol Stack is designed as a series of layers as well. These layers are
• Bearers—Typical bearers include communications technologies such as SMS, CDPD,and CDMA.
• Wireless Datagram Protocol (WDP)—Defines how information is passed across thenetwork.
• Wireless Transport Layer Security (WTLS)—Provides security and authentication ser-vices based on SSL encryption.
• Wireless Transaction Protocol (WTP)—Provides facilities for performing both reliableand non-reliable transactions; WTP supports unreliable one-way requests, reliable one-way requests, and reliable two-way requests. The typical transaction request to an HTTPserver is of the “reliable two-way” variety. Sending a simple text message with no verifi-cation would be an example of a reliable one-way request.
Wireless Application Development Using WAP
CHAPTER 23
23
WIR
ELESSA
PPLICA
TION
DEV
ELOPM
ENT
391
For a good list of WAP gateway products, visit the WirelessDevNet WAP Channel athttp://www.wirelessdevnet.com/channels/wap/.
NOTE
![Page 411: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/411.jpg)
• Wireless Session Layer (WSP)—Provides for two types of services, a connection modeand a connectionless mode. The connection-oriented session includes the capability tosuspend and resume a transmission should a connection become intermittent; WSPexchanges data with a server using a compressed, binary data format.
• Wireless Application Environment (WAE)—Consists of four components: a micro-browser, WML, WMLScript, and WTA (mentioned earlier in this chapter).
Emulators, Browsers, and Developer ToolsBecause WAP does not use HTML and because WAP device displays can come in all shapesand sizes, it is important that you gain access to as many emulators as possible to test yourapplication. This section will present a number of leading developer tools and emulators (bothonline and offline). We will also discuss WAP/servlet support available in popular applicationserver products.
Keep in mind that although your application might run fine on device emulators, you shouldalways be sure to test your application thoroughly on real devices before deploying! Individualdevices are notorious for not quite implementing the WAP standard perfectly. In addition, mostdevelopers cite WAP gateway problems as the number one hindrance to the successful deliveryand deployment of a WAP application.
Online EmulatorsThe simplest way to begin looking at WAP sites (and to test your own) is to make use of one ofthe available online WAP emulators. YoSpace (http://www.yospace.com) makes a range of desk-top emulators and development tools as well as a Java applet for use by portals. WirelessDevNet.com showcases the YoSpace WAP emulator product at http://www.wirelessdevnet.com/channels/wap/emulator/ for public use, as shown in Figure 23.1. Another online emulator forpublic use is available from Gelon.net. Visit http://www.gelon.net (see Figure 23.2) and selectfrom a wide range of WAP emulators.
WinWAP BrowserThe WinWAP browser is a useful Windows-based WAP browser available from Slobtrot inSweden. To download a demo copy of the browser, visit http://www.winwap.org. Thisbrowser is very useful as a desktop application because it functions like a standard Webbrowser (see Figure 23.3).
Servlet and JSP Web Applications
PART III392
![Page 412: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/412.jpg)
FIGURE 23.1The YoSpace Emulator.
Wireless Application Development Using WAP
CHAPTER 23
23
WIR
ELESSA
PPLICA
TION
DEV
ELOPM
ENT
393
FIGURE 23.2The Gelon.net Emulator.
![Page 413: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/413.jpg)
FIGURE 23.3The WinWAP Browser.
Note that this browser attempts to emulate the “look-and-feel” of standard Web browsers; in noway will it emulate what your users will see on their devices. WinWAP is a useful tool for“surfing” the wireless Web from your desktop, but be sure to test your site on other emulatorsas well. For the remainder of this chapter and the next, we will use WinWAP to demonstrateexamples.
Emulators and Developer ToolsFull-fledged development toolkits are available from leading wireless companies such asMotorola, Openwave (formerly Phone.com), and Nokia. These toolkits include several usefulemulators along with powerful editing environments and documentation. Figure 23.4 shows theOpenwave UP.SDK tool.
PDA WAP BrowsersIf you are interested in accessing WAP content from your PalmOS device, you are in luck!Currently, several companies have developed WML browsers for the Palm ComputingPlatform. Of course, to actually use the browsers, you will need a network connection (eitherwired or wireless). For more information on browsing from your PalmOS device, check outthese tools: WAPMan Color (http://www.edgematrix.com), the Neomar WAP Browser(http://www.neomar.com), and the 4thPass KBrowser (http://www.4thpass.com).
Servlet and JSP Web Applications
PART III394
![Page 414: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/414.jpg)
FIGURE 23.4The Openwave UP.SDK WAP Toolkit.
Application ServersMany popular application server products now include support for both Java servlets and WAP.These include BEA WebLogic (http://www.beasys.com), Allaire’s JRun(http://www.allaire.com), and the open source Enhydra Java/XML application server(http://www.enhydra.org). Some of these products include special server classes to generateWML output whereas others use an XML “foundation” to distribute content to a variety ofdevices (HTML, WML, XHTML, and so forth).
Suggested ResourcesA list of leading technical resources for the wireless application developer follows. Most ofthese sites also have extensive links directories, so spending a few minutes perusing these siteswill provide you with an excellent introduction to the wireless world.
• Wireless Developer Network (http://www.wirelessdevnet.com)—Online portal fordevelopers and IT professionals interested in mobile computing and wireless communi-cations
• Cellmania (http://www.cellmania.com)—Large directory of WAP sites, tutorials, andarticles on the wireless world
• WMLScript.com (http://www.wmlscript.com)—Developer site devoted toWML/WMLScript programming
• Wireless Week (http://www.wirelessweek.com)—Leading industry trade magazine
• AllNetDevices (http://www.allnetdevices.com)—News and commentary on hand-held, mobile, and wireless devices
• Gelon.net (http://www.gelon.net)—WAP search engine and online emulator
Wireless Application Development Using WAP
CHAPTER 23
23
WIR
ELESSA
PPLICA
TION
DEV
ELOPM
ENT
395
![Page 415: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/415.jpg)
• WAP Forum (http://www.wapforum.org)—Home of the WAP Forum industry organi-zation
• AnywhereYouGo.com (http://www.anywhereyougo.com)—Another industry portal forsoftware developers interested in wireless technologies
SummaryThe Wireless Application Protocol enables developers to distribute information to mobileemployees and consumers through a wide range of devices. The design of the protocol enablesit to change gracefully as networks and devices will mature in the coming years.
A variety of developer tools and emulators are available for download. We suggest that youdownload several and evaluate them before beginning the next chapter, which will discussWAP’s markup language (WML) and client-side scripting language (WMLScript).
Servlet and JSP Web Applications
PART III396
![Page 416: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/416.jpg)
CHAPTER
24WML/WMLScript Developmentby Bryan Morgan
IN THIS CHAPTER• The Wireless Markup Language (WML) 398
• A WML Example 401
• WMLScript 405
• Wireless Application Developing UsingServlets 412
![Page 417: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/417.jpg)
Servlet and JSP Web Applications
PART III398
Chapter 23, “Wireless Application Development Using WAP,” introduced the brave new worldof wireless development using the Wireless Application Protocol (WAP) and its client-sidetechnologies WML and WMLScript. This chapter will take a detailed look at WML andWMLScript and will conclude with a discussion of wireless application development usingservlets. Although the process might sound daunting, you will find that it is very straightfor-ward and not much different from developing traditional Web applications using Java servlets.Both Web and wireless servlets applications output markup in text format in response to anHTTP request. What differs is the form of the markup and the display and processing capabili-ties of the client devices.
The Wireless Markup Language (WML)WML is the markup language used by WAP for information display and form input. WML isan XML-based (eXtensible Markup Language) language with a schema that is defined in theDocument Type Definition (DTD) located at:
http://www.wapforum.org/DTD/wml_1.1.xml
For those not familiar with XML, the language differs from a markup language such as HTMLin that anyone can create their own set of custom tags and attributes (known as a schema) to, inessence, define a brand new language! The structure of this new language (that is, theorder/taxonomy in which the language elements interact) is stored in a Document TypeDefinition file, or DTD. The DTD previously mentioned defines version 1.1 of the WirelessMarkup Language. Because a valid XML document must comply exactly with the rulesdefined in a DTD, XML documents (and technologies such as WML) are very rigid. Therefore,you can be reasonably sure that if a WML file is verified and compliant, it will run the sameway everywhere (barring browser bugs). Chapter 10, “Servlets and XML,” briefly describedthe structure and symmetry of a valid XML file.
WML Language BasicsA valid WML file begins with a header (which states the XML version being used and theappropriate WML DTD) and contains one body beginning and ending with a <wml></wml> tagpair. One body can contain multiple cards (known as a deck). Although only one card can beshown at a time on a single device, variables can be maintained across cards. For example, theoutput of one card’s text field could be used as the input to another card’s text field. As youmight have guessed, a card is defined within the <card></card> tag pair.
The Inevitable “Hello World!”It had to come sooner or later: the inevitable “Hello World!” application, or in this case, WMLCard (see Listing 24.1).
![Page 418: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/418.jpg)
LISTING 24.1 The helloworld WML Card
<?xml version=”1.0”?><!DOCTYPE wml PUBLIC “-//WAPFORUM//DTD WML 1.1//EN”➥ “http://www.wapforum.org/DTD/wml_1.1.xml”>
<wml><card id=”helloworld” title=”Hello World”><p>
Hello World!</p></card>
</wml>
The code in Listing 24.1 reveals a few WML basics. Lines 1 and 2 are clearly the WMLheader; this code will remain unchanged for all valid WML 1.1 files. The WML body beginswith the <wml> tag and dives immediately into our first card (named “helloworld”). Note thetwo attributes of the <card> tag: id and title. id is used to specify a unique ID for a cardwithin a single deck; the title attribute is optionally displayed to the user in the browser titlebar, depending on which browser is being used. The <p></p> tag pair is used to bracket a paragraph of text, just as the <p></p> tag pair is used in HTML. It is also important to re-emphasize, before continuing further, that XML is a case-sensitive language.
Text Formatting TagsAs you might expect, WML provides the full complement of text formatting tags (for linebreaks, italics, bold text, and so forth) as well as an anchor tag for hyperlinking to other cardsor documents. The following code snippets give brief examples for the usage of some of themore popular WML tags to perform common programming tasks. For a complete descriptionof all WML tags, see Appendix F, “WML Tag Reference.”
This snippet illustrates the use of the <b></b>, <i></i>, <u></u>, and <big></big> tags toformat text display:
<b>This is bold text!</b><i>This is italic text!</i><u>This is underlined text!</u><big>This is BIG text!</big>
Listing 24.1 demonstrated the use of the <p></p> tag pair to delineate a paragraph of text. Thefollowing snippet illustrates the use of the <br></br> tag pair:
<b>This is bold text!</b><br/><i>This is italic text!</i><br/><u>This is underlined text!</u><br/><big>This is BIG text!</big><br/>
WML/WMLScript Development
CHAPTER 24
24
WM
L/W
MLS
CR
IPTD
EVELO
PMEN
T
399
![Page 419: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/419.jpg)
AnchorsWML, like its distant cousin HTML, is built around the concept of hyperlinking to enablerapid access to information. HTML programmers are no doubt familiar with the <a></a>anchor tag pair and will be pleased to find that WML supports a similar mechanism.Navigation is supported in WML by the <a></a> and <anchor></anchor> tags. The <a></a>tag pair is analogous to its HTML counterpart in that it is useful for jumping to another cardwithin the current deck or an external URL:
<a href=”http://www.cellmania.com/”>Cellmania</a>
The <anchor></anchor> tag pair supports the same functionality but also offers addi-tional capabilities. An <anchor></anchor> tag can contain one of several “action” ele-ments: <go>, <prev>, or <refresh>. The <go></go> element, by default, performs exactlythe same as the previous <a></a> tag example. The <prev> tag specifies a link to returnto the card loaded just previously, and the <refresh> tag is used to refresh a value of aWML variable.
User InputWML also provides support for text entry (the <input> element) and list selection (the<select> and <option> elements). This code snippet demonstrates a simple text input elementthat stores a value in the zipcode variable:
Zip Code: <input type=”text” name=”zipcode”>
This code snippet demonstrates the use of a select list to present a set of options to a user:
<select name=”state” title=”State:”><option value=”AZ”>AZ</option><option value=”AL”>AL</option><option value=”AK”>AK</option>
</select>
EventsWML supports the concept of events through the <onevent> element. An event can be eithertriggered by a user (such as selecting an item on a list) or by an application (such as a timer as
Servlet and JSP Web Applications
PART III400
Note the use of the <br/> tag at the end of each line to produce a line break. Insteadof supplying a <br></br> empty tag pair, XML allows you to simply place a / (forwardslash) character after the opening tag to signify an empty tag. This will work with anyvalid XML tag.
NOTE
![Page 420: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/420.jpg)
described in the next section). Events can be handled by being bound to a task (such as <go> or<option>). <onevent> accepts one simple attribute: type. Different elements accept differentevent types. The following list illustrates the event types handled in WML by the <card> and<select> elements:
• <card>—onenterforward, onenterbackward, ontimer
• <select>—onpick
The next section introduces the use of the ontimer event when using timer elements.
TimersOne interesting element introduced in WML is the <timer></timer> tag. Timers built into acard allow that card to be displayed for a set amount of time before transferring focus toanother target URL. This is very useful to force the display of a splash screen or advertisementto your users. The timer tag syntax is as follows:
<timer value=”25”/>
The value parameter specifies a time in tenths of a second. For example, the timer listed in thepreceding syntax would display for 2.5 seconds. A timer is used with the ontimer event in a<card> tag to specify a URL to transfer to when the timer goes off (see Listing 24.2).
VariablesNote that both the input and select elements include a name attribute. Because multiple cardscan be stored within a single deck (to eliminate round trips to the server), it is important thatglobal data be able to be shared across cards. To do this, WML introduces the concept of avariable that can either be defined implicitly or explicitly. In the two snippets above, the vari-ables zipcode and state are implicitly defined and could be accessed using the $ operator. Forexample, to output the contents of the zipcode variable, the following code could be used:
<p>Zip Code: $(zipcode)
</p>
Variables can also be accessed through WMLScript, as we will see later in this chapter. Nowthat the WML basics have been introduced, it is time to undertake a larger example to be testedin a series of WAP emulators.
A WML ExampleIn this section, you’ll develop a fairly simple example using multiple cards within a decknamed WMLExample.wml. The code in Listing 24.2 illustrates some of the basic concepts dis-cussed in this chapter: multiple cards, anchors, variables, and lists.
WML/WMLScript Development
CHAPTER 24
24
WM
L/W
MLS
CR
IPTD
EVELO
PMEN
T
401
![Page 421: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/421.jpg)
LISTING 24.2 WMLExample.wml
<?xml version=”1.0”?><!DOCTYPE wml PUBLIC “-//WAPFORUM//DTD WML 1.1//EN” “http://➥www.wapforum.org/DTD/wml_1.1.xml”>
<wml><card id=”welcome” title=”Servlets Book”>
<p>Welcome to the WML example! Select from one of these tests:<br/><br/><a href=”#setvar”>Setvar Test</a><br/><a href=”#input”>Input Test</a><br/><a href=”#select”>List Test</a><br/><a href=”#previous”>Prev Test</a><br/><a href=”#timer”>Timer Test</a><br/></p>
</card><card id=”setvar” title=”Setvar Test”>
<onevent type=”onenterforward”><refresh>
<setvar name=”output” value=”WAP Is Cool!”/></refresh>
</onevent><p>$output</p>
</card><card id=”input” title=”Input Test”>
<p>Enter text here:<input name=”inputBox”/></p><do type=”accept”>
<go href=”#input_output”/></do>
</card><card id=”select” title=”Select Test”>
<p>Select an option:<select name=”selectList”>
<option value=”Option1”>Option1</option><option value=”Option2”>Option2</option><option value=”Option3”>Option3</option><option value=”Option4”>Option4</option><option value=”Option5”>Option5</option>
</select>
Servlet and JSP Web Applications
PART III402
![Page 422: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/422.jpg)
LISTING 24.2 Continued
<do type=”accept”><go href=”#select_output”/>
</do></p>
</card><card id=”previous” title=”Prev Test”>
<p>Select the Previous button to go back.<do type=”prev”>
<prev/></do></p>
</card><card id=”timer” title=”Timer Test” ontimer=”#timer_output”>
<timer value=”25”/><p>Sponsored by Sams Publishing!</p>
</card>
<!-- “Helper” cards -->
<card id=”input_output” title=”Input Output”><p>
You entered: $inputBox</p></card><card id=”select_output” title=”Select Output”><p>
You entered: $selectList</p></card><card id=”timer_output” title=”Timer Output”><p>
You viewed the advertisement!<do type=”accept” label=”Home”>
<go href=”#welcome”/></do>
</p></card>
</wml>
WML/WMLScript Development
CHAPTER 24
24
WM
L/W
MLS
CR
IPTD
EVELO
PMEN
T
403
![Page 423: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/423.jpg)
The example in Listing 24.2 creates five sample cards to demonstrate the basic elements dis-cussed in this chapter. Running the example in an emulator will produce the results seen inFigures 24.1–24.6.
Servlet and JSP Web Applications
PART III404
FIGURE 24.1The WMLExample.wml Welcome Card.
FIGURE 24.2The setvar Card.
FIGURE 24.3The input Card.
![Page 424: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/424.jpg)
24
WM
L/W
MLS
CR
IPTD
EVELO
PMEN
T
WML/WMLScript Development
CHAPTER 24405
FIGURE 24.4The select Card.
FIGURE 24.5The previous Card.
FIGURE 24.6The timer Card.
WML works well for displaying information to the user, but any programming logic must beaccessed through a <go> or <a> link to a server, that is, unless you use WMLScript. The nextsection introduces client-side programming with WAP’s WMLScript programming language.
WMLScriptThe Wireless Application Protocol defines a client-scripting environment and programminglanguage based on ECMAScript. If you are familiar with client-side JavaScript programming,you are well on your way to learning WMLScript. WMLScript is a client-only scripting
![Page 425: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/425.jpg)
platform used in combination with WML to provide client-side procedural logic. Like WML,WMLScript is compiled through a WAP gateway into binary form to provide intelligence tomobile clients. This section will be used to present the WMLScript language and its libraries; itconcludes with an example illustrating the use of WMLScript to perform client-side validation.
Calling WMLScript from WMLFor a WMLScript function to be called from WML, the function must be declared within itssource file using the extern keyword. The syntax for calling a function is as follows:
sourcefile.wmls#functionname(arguments)
WML calls the WMLScript function through a hyperlink such as the <a></a> anchor tag or the<go></go> action tag. For example, a fictional WMLScript function call could be triggeredfrom an anchor tag such as:
<a href=”sourcefile.wmls#functionname(arguments)”>Click Here!</a>
Language BasicsWMLScript uses virtually the same syntax as JavaScript. Some of the basic language rulesinclude
• All statements must end with a semicolon (;)
• Variables are declared using the var keyword (for example, var counter=0;)
• Multiline comments are surrounded by /* */; single-line comments begin with //
• The language is case sensitive
• All WMLScript code must live inside a function
• The language is comprised of six standard libraries: Lang, Float, String, URL,WMLBrowser, and Dialogs
• No run-time or compile-time type checking is done
• The language supports five internal data types: Boolean, Integer, Floating-point,String, and Invalid
WMLScript functions feature the following syntax:
function new_function(parameters){
code body}
To return a value from a function, use the return keyword.
Servlet and JSP Web Applications
PART III406
![Page 426: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/426.jpg)
OperatorsWMLScript defines a complete set of operators that are very similar to languages such as Cand Java. These operators are as follows:
• Assignment Operators—=, +=, -=, *=, /=, div=, %=, &=, |=, ^=, <<=, >>=, and >>>=.
• Arithmetic Operators—+, -, *, /, div, and %.
• Bitwise Operators—<<, >>, >>>, &, ^, |, and ~.
• Logical Operators—&&, ||, and !.
• Equality Testing Operators—==, !=, >, >=, <, and <=.
The comma operator is used to perform multiple computations or evaluations within a singlestatement. This operator might seem a bit odd because the value of a statement is the value ofthe left operand. In other words, in this statement
x = y=0, z+5;
the net result is that y will be set equal to zero and x will be set equal to z+5. Basically, use ofthe comma operator enables you to eliminate one or more lines of code, but at the risk of codeobfuscation. It is generally recommended that the comma operator be avoided.
The final operator, typeof, is used to evaluate a variable’s data type. The output of the typeofoperator is an integer value correlating to one of the following data types: Integer (0), Float(1), String (2), Boolean (3), and Invalid (4).
StatementsLike all high-level programming languages, WMLScript includes complete capabilities forcontrolling the flow of code. These capabilities include conditional statements, loops, andbreaks.
The simplest conditional statement is the if statement. If the situation calls for it, the elseclause is also provided. If the conditional statements are more than one line in length, braces({}) should surround them:
if (some_condition){
statement1;statement2;
}else{
other_statement1;other_statement2;
}
WML/WMLScript Development
CHAPTER 24
24
WM
L/W
MLS
CR
IPTD
EVELO
PMEN
T
407
![Page 427: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/427.jpg)
WMLScript also provides looping capabilities using the for and while statements. The follow-ing code counts from 1–100 in WMLScript and updates the contents of a variable as the loopincrements:
function increment_variable(strVariableName){
var intCounter;for (intCounter = 1; intCounter <= 100; intCounter++){
WMLBrowser.setVar(strVariableName, String.toString(intCounter));}
}
Notice that this function demonstrates the use of two of the WMLScript Standard Libraries:String and WMLBrowser. These libraries will be introduced later in this chapter.
A while loop executes a block of statements until some condition becomes true. Its syntax isas follows:
while (some_condition){
statements;}
The break and continue statements are provided to control flow inside a loop. As you mightexpect, encountering a break statement causes a loop to immediately exit. A continue state-ment simply causes a loop to continue by jumping back to the loop beginning.
The Standard LibrariesAlthough WMLScript is a capable programming language for client-side scripting environ-ments, it is even more powerful because of the definition and inclusion of six standard librarieswith every validated WAP browser. These libraries are
• Lang—This library contains a set of functions that are closely related to the WMLScriptlanguage core. Included in this library are functions for data-type manipulation, absolutevalue calculations, and random number generation.
• Float—The Float library is optional and is only supported on those clients with float-ing-point capabilities. Typical functions provided by this library include sqrt(),round(), and pow().
• String—The String library contains a set of functions for performing string operations.Some functions included in this library are length(), charAt(), find(), replace(), andtrim().
Servlet and JSP Web Applications
PART III408
![Page 428: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/428.jpg)
• URL—This library contains a set of functions for handling both absolute and relativeURLs. Typical functions include getPath(), getReferer(), and getHost().
• WMLBrowser—This library contains functions by which WMLScript can access the asso-ciated WML context. These functions must not have any side effects and must returninvalid in cases where the system does not support WMLBrowser and where the inter-preter is not invoked by the WML Browser. Commonly used functions in this libraryinclude go(), prev(), next(), getCurrentCard(), and refresh().
• Dialogs—This library contains a set of typical user interface functions includingprompt(), confirm(), and alert().
In the following example, we will make use of some of the capabilities of the standardlibraries. For a complete listing of the libraries, see Appendix G, “WML Script LanguageReference.”
WMLScript ExampleListing 24.3 defines three functions in a file named WMLScriptExample.wmls. These functionsare: setvar(), getString(), and getLength(). As you can see, these functions make use ofthe WMLBrowser and String standard libraries to access the helper functions in these libraries.Each of the functions takes a variable, sets it in the browser, and then returns focus to thebrowser.
LISTING 24.3 WMLScriptExample.wmls
/** This function simply sets a variable and transfers* focus to the setvar_output card*/
function setVar(){
var output = “Hi There!”;
//Now set the variable in the browser environmentWMLBrowser.setVar(“txtOutput”, output);
//Now transfer focus to the setvar_output cardWMLBrowser.go(“#setvar_output”);
}
/** This function accepts a string and returns it to another card*/
WML/WMLScript Development
CHAPTER 24
24
WM
L/W
MLS
CR
IPTD
EVELO
PMEN
T
409
![Page 429: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/429.jpg)
LISTING 24.3 Continued
function getString(var str){
//Set the variable in the browser environmentWMLBrowser.setVar(“txtInput”, str);
//Now transfer focus to the length_output cardWMLBrowser.go(“#input_output”);
}
/** This function accepts a string and returns its length*/function getLength(var str){
var len = String.length(str);
//Now set the variable in the browser environmentWMLBrowser.setVar(“strLength”, len);
//Now transfer focus to the length_output cardWMLBrowser.go(“#length_output”);
}
Listing 24.4 represents the source code for WMLScriptExample.wml—the WML file used toexecute the functions defined in Listing 24.3.
LISTING 24.4 WMLScriptExample.wml
<?xml version=”1.0”?><!DOCTYPE wml PUBLIC “-//WAPFORUM//DTD WML 1.1//EN” “http://➥www.wapforum.org/DTD/wml_1.1.xml”>
<wml><card id=”welcome” title=”WMLScript Example”>
<p>Welcome to the WMLScript example! Select from
➥one of these tests:<br/><br/><a href=”WMLScriptExample.wmls#setVar()”>Setvar Test</a><br/><a href=”#input”>Input Test</a><br/><a href=”#length”>Length Test</a><br/></p>
</card>
Servlet and JSP Web Applications
PART III410
![Page 430: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/430.jpg)
LISTING 24.4 Continued
<p>Enter text here:<input name=”inputBox”/></p><do type=”accept”>
<go href=”WMLScriptExample.wmls#getString(‘$(var:inputBox)’)”/></do>
</card>
<card id=”length” title=”Length Test”><p>Enter text here:<input name=”inputBox2”/></p><do type=”accept”>
<go href=”WMLScriptExample.wmls#getLength(‘$(var:inputBox2)’)”/></do>
</card>
<card id=”setvar_output” title=”setVar Test”><p>Variable = $txtOutput</p>
</card>
<card id=”input_output” title=”Output Test”><p>You entered: $txtInput</p>
</card>
<card id=”length_output” title=”Length Test”><p>Length = $strLength</p>
</card></wml>
As you can see, the WML file defines three starter scenarios that each call a WML function.The WMLScript functions set variables and return focus back to one of the three output cardsfor displaying information to the user.
WML/WMLScript Development
CHAPTER 24
24
WM
L/W
MLS
CR
IPTD
EVELO
PMEN
T
411
![Page 431: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/431.jpg)
Wireless Application Developing Using ServletsThis section will address the topic of dynamic wireless application development using Javaservlets. As mentioned earlier, not much separates WAP/servlet development from the standardHTML/servlet development techniques presented throughout the rest of this book. As you willsee in this section, it is as simple as setting a few new MIME types on your Web server andyou’re off and running! Several more advanced techniques enable servlet applications to simul-taneously support multiple client types, and these techniques will also be discussed.
Servlet and JSP Web Applications
PART III412
For more information on wireless Java servlet development, visit the following URLs:
Go Wireless (XML Magazine):http://www.xmlmag.com/upload/free/features/xml/2000/03sum00/mf10300/
➥mf10300-1.asp
Building Servlets To Output WML Content (AnywhereYouGo.com): http://www.anywhereyougo.com/ayg/ayg/Article.po?id=10743
NOTE
Configuring Server MIME TypesIf you’re going to serve up WML and WMLScript files from your Web server, you need tonotify your Web server of this by setting the appropriate MIME types. The file and MIMEtypes you should be aware of when supporting WAP are
• .wml—text/vnd.wap.xml
• .wbmp—image/vnd.wap.wbmp
• .wmls—text/vnd.wap.wmlscript
• .wmlc—application/vnd.wap.wmlscriptc
• .wmlsc—application/vnd.wap.wmlc
If you are using the popular Apache Web server (http://www.apache.org), these MIME typescan be added by editing the server’s .htaccess file. For example, to add support for the .wmlfile type, add the following line to .htaccess:
AddType text/vnd.wap.wml .wml
If you are using the popular Microsoft Internet Information Server(http://www.microsoft.com/iis/), modifying the server is done through a graphical userinterface. Within the Internet Service Manager application, select the Web server you wouldlike to modify, and then select the Properties menu option. From the Properties dialog box,
![Page 432: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/432.jpg)
select the HTTP Headers tab, and then select the Add button within the Custom HTTP Headersbox. Add the appropriate MIME types to IIS using this option.
If you are using another HTTP server product, consult your product’s documentation to learnhow to add support for additional MIME types.
A Quick “Hello World!” WML ServletTo reiterate, WML/WMLScript content is output from Java servlets in the exact same manneras HTML content (using the java.io.PrintWriter class). Listing 24.5 shows a simple “HelloWorld!” servlet that outputs WML content to a WAP browser.
LISTING 24.5 The HelloWorld! Servlet
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response){response.setContentType(“text/vnd.wap.wml”);PrintWriter out = response.getWriter();
out.println(“<?xml version=\”1.0\”?>”);out.println(“<!DOCTYPE wml PUBLIC \”-//WAPFORUM//DTD WML 1.1//EN\” “+
“\”http://www.wapforum.org/DTD/wml_1.1.xml\”>”);out.println(“<wml>”);out.println(“<card title = \”HelloWorld\”>”);out.println(“<p>Hello World!</p>”);out.println(“</card>”);out.println(“</wml>”);
}}
This simple servlet does two things:
1. It sets the MIME type being output by calling theHttpServletResponse.setContentType() method.
2. It outputs a simple WML card displaying the text “Hello World!”
WML/WMLScript Development
CHAPTER 24
24
WM
L/W
MLS
CR
IPTD
EVELO
PMEN
T
413
![Page 433: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/433.jpg)
Using this basic functionality, it is possible to construct dynamic Java servlets that generateWML content based on JDBC database queries or other typical programming tasks. What hap-pens, though, when your boss asks you to develop one common set of code that supports bothdesktop (for example, HTML) users and mobile (for example, WAP) users? This will be thetopic of the following two sections.
Multiple Device SupportAs you might imagine, supporting a completely different code base for HTML and WML con-tent would become unmanageable quickly on any moderate-to-large-sized project. In order to“force” all users to enter through a central servlet, it is useful to first detect the browser typeand then redirect the user to the appropriate content. This way, all users enter your server appli-cation through one servlet and WML/HTML output code within that servlet can access thesame core set of helper methods and classes. (In fact, only the text output methods will differ!)User agents can be detected using thejavax.servlet.http.HttpServletRequest.getHeader() method to retrieve theHTTP_USER_AGENT CGI Environment Variable. The following line of code does just that:
String userAgent = request.getHeader(“User-Agent”);
This is a rather tedious approach but enterprise developers should be able to narrow down thelist of potential accessors somewhat. For an up-to-date list of WAP user agent values, visithttp://allnetdevices.com/faq/useragents.php3.
Maintaining a Site in XMLA common approach in use today by wireless application developers is to store the site contentand data in XML format. XML documents can be transformed into any number of formatsusing an XML technology known as eXtensible Stylesheet Language Transformation, or XSLT.WML is particularly suited to this sort of transformation because it is itself based on XML,making the transformation very clean and straightforward. If you are familiar with object-oriented programming concepts, you will recognize the concepts of data hiding and encapsulation—two concepts enthusiastically supported by XML and XSLT.
The actual formatting of the body to be displayed to the user (for example, WML or HTML) isstored in an XML file. The data stored within that formatted body is stored within a separateXML file and united with the formatting XML using an XML parser. Some HTML clients(such as Microsoft Internet Explorer 5.0 and later releases) support XML/XSLT in the client;therefore no further work will be required. At the current time, WAP browsers do not embedXML parsers, so processing will need to be completed on the server by a Java servlet and aJava XML parser framework such as that provided by the Apache Cocoon project(http://xml.apache.org/cocoon/).
Servlet and JSP Web Applications
PART III414
![Page 434: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/434.jpg)
SummaryChapters 23 and 24 have presented the Wireless Application Protocol and its associated pro-gramming languages: WML and WMLScript. Combining WML and WMLScript with anadvanced server-side technology such as Java servlets supports the development of industrial-strength dynamic wireless applications for a variety of devices.
WML/WMLScript Development
CHAPTER 24
24
WM
L/W
MLS
CR
IPTD
EVELO
PMEN
T
415
![Page 435: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/435.jpg)
![Page 436: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/436.jpg)
IN THIS PARTA Web Applications and Configuring the Servlet
Engine
B The javax.servlet Package
C The javax.servlet.http Package
D The javax.servlet.jsp Package
E The javax.servlet.jsp.tagext Package
F WML (The Wireless Markup Language)
G WMLScript
AppendixesPART
IV
![Page 437: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/437.jpg)
![Page 438: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/438.jpg)
APPENDIX
AWeb Applications andConfiguring the Servlet Engine
IN THIS APPENDIX• Web Applications 420
• Web Archive (WAR) Files 422
• Servlet Requirements 422
• Apache Tomcat 422
![Page 439: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/439.jpg)
Web ApplicationsThe release of the Java Servlet Specification 2.2 introduced the concept of a Web application.According to this specification a Web application is a collection of servlets, HTML pages,classes, and other resources that can be bundled and run on multiple containers from multiplevendors. In this book you create the Web application directory structure and create a new appli-cation entry in the server.xml file. (Because you develop your examples as you progressthrough the book, you don’t deploy the examples into a Web ARchive (WAR) file; however wedo discuss WAR files.) The following is a list of items that can exist in a Web application:
• Servlets
• JavaServer Pages
• Utility classes
• Static documents including HTML and images
• Client-side classes
• Meta information that describes the Web application
The ServletContext in Relation to the Web ApplicationEach Web application belongs to one and only one ServletContext. This mapping is con-trolled by the servlet container, and guarantees that no two applications will have clashes whenstoring objects in the ServletContext.
The Directory StructureThe container that holds the Web application is the directory structure in which it exists. Thefirst step in creating a Web application is to create this structure. Table A.1 contains sampledirectories you will need. Each one of these directories should be created from the<SERVER_ROOT> of the servlet container.
TABLE A.1 The Web Application Directories Structure
Directory Description
/applicationname This is the root directory of the Web applica-tion. This is where we will be installing all ofour JSPs and HTML files.
Appendixes
PART IV420
![Page 440: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/440.jpg)
TABLE A.1 Continued
Directory Description
/applicationname/WEB-INF This directory contains all resources related tothe application that are not in the documentroot of the application. You must note that theWEB-INF directory is not part of the publicdocument tree of the application. No file con-tained in this directory can be served directlyto a client.
/applicationname/WEB-INF/classes This directory is where servlet and utilityclasses are located.
The applicationname we use throughout this book is djs; therefore you need to substitute djsfor applicationname in the previously described directory structure.
Web Application Deployment DescriptorsThe Web application deployment descriptor describes configuration and deployment informa-tion for the entire Web application. The Web application descriptor is an XML file namedweb.xml, located in the /<SERVER_ROOT>/applicationname/WEB-INF/ directory. For our appli-cation the location of the web.xml file is in the /<SERVER_ROOT>/djs/WEB-INF/ directory. Theinformation that is contained in the deployment descriptor includes the following elements:
• ServletContext init parameters
• Localized content
• Session configuration
• Servlet/JSP definitions
• Servlet/JSP mappings
• Mime type mappings
• Welcome file list
• Error pages
• Security
The XML descriptor elements that we focus on are mainly servlet specific. The following codesnippet contains an example of a Web application deployment descriptor:
<web-app><display-name>A Basic Application</display-name><session-timeout>30</session-timeout>
Web Applications and Configuring the Servlet Engine
APPENDIX A421
A WEB
APPLICA
TION
SA
ND
THE
SERV
LETE
NG
INE
![Page 441: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/441.jpg)
<servlet><servlet-name>BasicServlet</servlet-name><servlet-class>BasicServlet</servlet-class><load-on-startup>1</load-on-startup><init-param><param-name>name</param-name><param-value>value</param-value>
</init-param></servlet>
</web-app>
Web Archive (WAR) FilesWeb applications can be packaged into a Web ARchive (WAR) file using Java’s standardarchiving tool jar. The only difference would be its extension. For this text we could packageall our examples into a file called djs.war. However, as stated earlier, we don’t package themas a WAR because we develop the examples as we progress through the book.
Servlet RequirementsTo begin a development effort using Java servlets, you will need to decide what tools you willuse to both write and run your servlets.
You will need only a minimal set of tools to actually write Java servlets. The two most impor-tant requirements are the Java Development Kit (JDK), and the Java Servlet Development Kit(JSDK), also on version 2.2. Both of these development kits can be downloaded from theJavaSoft home page at http://www.javasoft.com at no cost.
You will also need the Tomcat server, which we will discuss in the next section.
Apache TomcatTomcat is the flagship product of The Apache Software Foundation’s Jakarta Project. It isintended to be a reference implementation of Sun’s Java Servlet SDK 2.2 and JavaServer Pages1.1 specifications.
Installing the Tomcat ServerThe first thing you need to do is get a copy of Tomcat from the Jakarta Project’s Web site. Youcan find the necessary links at the http://jakarta.apache.org/ site. Figure A.1 shows theJakarta Project’s home page.
Appendixes
PART IV422
![Page 442: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/442.jpg)
FIGURE A.1The Jakarta Project’s home page.
You can choose to download either class files or source code.
When you have the file, decompress it to a local drive. For this text I am installing it to driveC:, therefore my <SERVER_ROOT> directory is C:\jakarta-tomcat-3.2\. If you have a laterversion of Tomcat, your <SERVER_ROOT> could be different.
The next step is putting your JDK into the Tomcat’s classpath. You do this by editing the<SERVER_ROOT>/bin/tomcat.bat file and setting the JAVA_HOME environment variable to thelocation of your JDK installation. For my installation I have added the following line to thetomcat.bat file:
set JAVA_HOME=C:\java\jdk1.2.2\
Make sure this line is added before any references to JAVA_HOME.
To test your installation, start the Tomcat server by executing the startup.bat file and openyour browser to the following URL, substituting your server name:
http://server_name:8080/
You should now see a screen similar to Figure A.2.
Web Applications and Configuring the Servlet Engine
APPENDIX A423
A WEB
APPLICA
TION
SA
ND
THE
SERV
LETE
NG
INE
![Page 443: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/443.jpg)
FIGURE A.2The Tomcat default page.
The next step is to verify the installation of your JDK. You do this by executing one of the JSPexamples provided with the Tomcat server. To execute a sample JSP, start from the page shownin Figure A.2 and choose JSP Examples. You should see a screen similar to Figure A.3.
Now choose the JSP example Date and select the Execute link. If everything was installedproperly you should see a page similar to Figure A.4 (with a different date, of course).
If you do not see this page, you need to make sure the location of your JDK matches the loca-tion specified by the JAVA_HOME variable in the tomcat.bat file.
Adding the DJS Web ApplicationThe final step in setting up the djs Web application, which is also our final step in setting up theTomcat server, is to create a new Web application entry in the<SERVER_ROOT>/conf/server.xml file. This is the configuration file for the servlet containers.To add the new entry, add the following section of text at the end of the <ContextManager> tags:
<Context path=”/djs” docBase=”webapps/djs”defaultSessionTimeOut=”30” isWARExpanded=”true”isWARValidated=”false” isInvokerEnabled=”true”isWorkDirPersistent=”false”></Context>
Appendixes
PART IV424
![Page 444: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/444.jpg)
FIGURE A.3The JSP Examples page.
Web Applications and Configuring the Servlet Engine
APPENDIX A425
A WEB
APPLICA
TION
SA
ND
THE
SERV
LETE
NG
INE
FIGURE A.4The JSP Date page.
![Page 445: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/445.jpg)
This entry tells the servlet containers that we have a new Web application and it is located inthe <SERVER_ROOT>/djs/ directory with a document base of webapps/djs/.
You should also change the port Tomcat is listening to for HTTP requests. You do this bychanging the port value to 80 in the following entry of the same<SERVER_ROOT>/conf/server.xml file:
<Connector className=”org.apache.tomcat.service.SimpleTcpConnector”><Parameter name=”handler”
➥ value=”org.apache.tomcat.service.http.HttpConnectionHandler”/><Parameter name=”port” value=”80”/>
</Connector>
Now we need to add the application’s directories as follows:
<SERVER_ROOT>/webapps/djs/<SERVER_ROOT>/webapps/djs/images<SERVER_ROOT>/webapps/djs/WEB-INF
Building and Installing the BasicServletTo test your newly created Web application we will build and install the BasicServlet fromChapter 3, “Servlet Basics.” You need to complete two steps to run your newly created servlet.The first step is to compile the servlet code. The second is to install the servlet into your Webapplication.
To compile the servlet, make sure the servlet SDK is on your CLASSPATH. You can find theJSDK classes in the C:\jakarta-tomcat\lib\servlet.jar file.
After the servlet has been compiled, you need to copy the class file to the appropriate directoryin the Web application and restart the Tomcat server. This directory should be the following forTomcat:
<SERVER_ROOT>/webapps/djs/WEB-INF/classes
These directories should be used throughout the book. Now open your browser to the follow-ing URL:
http://localhost/djs/servlet/BasicServlet
Appendixes
PART IV426
You should not be required to restart the Tomcat server with the change or additionof a servlet, but if your changes are not reflected when you reload your servlet, goahead and stop and restart the server.
NOTE
![Page 446: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/446.jpg)
You should now see a page similar to Figure A.5.
Web Applications and Configuring the Servlet Engine
APPENDIX A427
A WEB
APPLICA
TION
SA
ND
THE
SERV
LETE
NG
INE
FIGURE A.5Output from the BasicServlet.
SummaryIn this appendix we discussed Web applications and how they are built. We covered how to setup the Tomcat server, and we compiled and built the BasicServlet from Chapter 3.
![Page 447: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/447.jpg)
![Page 448: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/448.jpg)
APPENDIX
BThe javax.servlet Package
IN THIS APPENDIX• The javax.servlet Interfaces 430
• Classes 448
• Exceptions 456
![Page 449: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/449.jpg)
Appendixes
PART IV430
The javax.servlet package is at the core of all servlet development. It contains the genericinterfaces, classes, and exceptions that are implemented and extended by all servlets. FigureB.1 illustrates the javax.servlet object model.
java.lang.Throwable
javax.servlet.ServletException
<<Interface>>java.io.Serializable
java.lang.Exception
javax.servlet.UnavailableException
java.lang.Object
javax.servlet.GenericServlet
java.io.OutputStreamjava.io.InputStream
javax.servlet.ServletInputStream javax.servlet.ServletOutputStream
<<Interface>>javax.servlet.RequestDispatcher
<<Interface>>javax.servlet.Servlet
<<Interface>>javax.servlet.ServletConfig
<<Interface>>javax.servlet.ServletContext
<<Interface>>javax.servlet.ServletRequest
<<Interface>>javax.servlet.ServletResponse
<<Interface>>javax.servlet.SingleThreadModel
FIGURE B.1The javax.servlet object model.
The javax.servlet InterfacesInterfaces of the javax.servlet package include RequestDispatcher, Servlet,ServletConfig, ServletContext, ServletRequest, ServletResponse, andSingleThreadModel. Each is described in the following sections, along with its methods.
![Page 450: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/450.jpg)
The RequestDispatcher Interfacepublic interface RequestDispatcher
The RequestDispatcher interface defines an object that can serve as a wrapper around anotherresource on the server. It is most often used to forward requests to other server resources. Itdefines two methods.
The forward() Methodpublic void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException
The forward() method is used to forward a request from one servlet to another. It allows thefirst servlet to perform some initial tasks on the request before forwarding it to anotherresource on the server. forward() returns no value.
forward() has two parameters:
• ServletRequest
• ServletResponse
It throws these exceptions:
• ServletException
• java.io.IOException
The include() Methodpublic void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException
The include() method is used to merge content from another server resource in the responseof the final servlet. include() returns no value.
include() has two parameters:
• ServletRequest
• ServletResponse
It throws these exceptions:
• ServletException
• java.io.IOException
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
431
![Page 451: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/451.jpg)
The Servlet Interfacepublic abstract interface Servlet
The Servlet interface is implemented by all servlets either through direct implementation orinheritance. It defines five methods, including the three life cycle methods, to be implementedby all servlets.
The init() Methodpublic void init(ServletConfig config)throws ServletException
The init() method, the first life cycle method, marks the beginning of a servlet’s life. It iscalled only when the servlet is first loaded, and it must execute successfully before the servletcan service requests. The init() method should contain all initialization code for the servlet. Itreturns no value.
init() has one parameter:
• ServletConfig
It throws this exception:
• ServletException
The getServletConfig() Methodpublic ServletConfig getServletConfig()
The getServletConfig() method returns the servlet’s ServletConfig object, which containsthe servlet’s startup configuration and initialization parameters. getServletConfig() has noparameters and throws no exceptions.
It returns this value:
• ServletConfig
The service() Methodpublic void service(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException
The service() method defines the servlet’s entry point for servicing requests. It can be exe-cuted only after the servlet’s init() method has executed successfully. The service() methodis the life cycle method executed for every incoming request. It returns no value.
Appendixes
PART IV432
![Page 452: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/452.jpg)
service() has two parameters:
• ServletRequest
• ServletResponse
It throws these exceptions:
• ServletException
• java.io.IOException
The getServletInfo() Methodpublic java.lang.String getServletInfo()
The getServletInfo() method provides the servlet user with information about the servletitself. You will usually include copyright or versioning information. getServletInfo() has noparameters and throws no exceptions.
It returns this value:
• String
The destroy() Methodpublic void destroy()
The destroy() method is the life cycle method that marks the end of a servlet’s life. It is exe-cuted only once, when the servlet is removed from the service. You should place all of yourclean-up functionality in this method. destroy() has no parameters, returns no value, andthrows no exceptions.
The ServletConfig InterfaceThe ServletConfig interface defines an object generated by a servlet engine and passes con-figuration information to a servlet during startup. It contains name/value pairs of initializationparameters for the servlet. It also contains a reference to the ServletContext object, describedin the next section. The ServletConfig interface defines four methods for accessing this infor-mation.
The getServletContext() Methodpublic ServletContext getServletContext()
The getServletContext() method returns a reference to the current ServletContext object.getServletContext() has no parameters and throws no exceptions.
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
433
![Page 453: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/453.jpg)
It returns this value:
• ServletContext
The getServletName() Methodpublic java.lang.String getServletName()
The getServletName() method returns the registered servlet’s name. getServletName() hasno parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getInitParameter() Methodpublic java.lang.String getInitParameter(java.lang.String)
The getInitParameter() method returns a string containing the value of the initializationparameter’s name/value pair referenced by the passed-in string representing the name.getInitParameter() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.String
The getInitParameterNames() Methodpublic java.util.Enumeration getInitParameterNames()
The getInitParameterNames() method returns an enumeration of strings representing all ofthe initialization parameters’ names. getInitParameterNames() takes no parameters andthrows no exceptions.
It returns this value:
• java.util.Enumeration
The ServletContext Interfacepublic interface ServletContext
The ServletContext interface defines an object to be created by a servlet engine that containsinformation about the servlet’s environment. This interface provides several methods to accessthis information.
Appendixes
PART IV434
![Page 454: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/454.jpg)
The getContext() Methodpublic ServletContext getContext(java.lang.String uripath)
The getContext() method returns a reference to a ServletContext object belonging a partic-ular URI path. getContext() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• ServletContext
The getInitParameter() Methodpublic java.lang.String getInitParameter(java.lang.String name)
The getInitParameter() method returns the value for the named context parameter.getInitParameter() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.String
The getInitParameterNames() Methodpublic Enumeration getInitParameterNames()
The getInitParameterNames() method returns an enumeration of all the context parameternames. getInitParameterNames() has no parameters and throws no exceptions.
It returns this value:
• Enumeration
The getMajorVersion() Methodpublic int getMajorVersion()
The getMajorVersion() method returns an integer representing the major version of theservlet API that the servlet engine supports. If the servlet engine supported the servlet API 2.1,the result would be 2. getMajorVersion() has no parameters and throws no exceptions.
It returns this value:
• int
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
435
![Page 455: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/455.jpg)
The getMinorVersion() Methodpublic int getMinorVersion()
The getMinorVersion() method returns an integer representing the minor version of theservlet API that the servlet engine supports. If the servlet engine supported the servlet API 2.1,the result would be 1. getMinorVersion() has no parameters and throws no exceptions.
It returns this value:
• int
The getMimeType() Methodpublic java.lang.String getMimeType(java.lang.String file)
The getMimeType() method returns a string representing the MIME type of the passed-in file-name, or null if the MIME type of the file is not known. getMimeType() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
•java.lang.String
The getNamedDispatcher() Methodpublic RequestDispatcher getNamedDispatcher(java.lang.String name)
The getNamedDispatcher() method returns a reference to a RequestDispatcher objectbelonging a particular URI path. The getNamedDispatcher() method throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• RequestDispatcher
The getResource() Methodpublic java.net.URL getResource(java.lang.String path)throws java.net.MalformedURLException
The getResource() method returns a URL object of a resource matching the passed-in pathparameter, permitting a servlet to access content from the servlet engine’s document spacewithout system dependencies.
Appendixes
PART IV436
![Page 456: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/456.jpg)
getResource() has one parameter:
• java.lang.String
It returns this value:
• java.net.URL
It throws this exception:
• java.net.MalformedURLException
The getResourceAsStream() Methodpublic java.io.InputStreamgetResourceAsStream(java.lang.String path)
The getResourceAsStream() method returns an InputStream object, which allows access tothe resource matching the passed in URL path. getResourceAsStream() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.io.InputStream
The getRequestDispatcher() Methodpublic RequestDispatchergetRequestDispatcher(java.lang.String urlpath)
The getRequestDispatcher() method returns a RequestDispatcher object based on thepassed-in URL path. getRequestDispatcher() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• RequestDispatcher
The log(java.lang.String msg) Methodpublic void log(java.lang.String msg)
This log() method writes the passed-in message to the context’s log. The location of the log isservlet-engine specific. log() returns no value and throws no exceptions.
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
437
![Page 457: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/457.jpg)
It has one parameter:
• java.lang.String
The log(java.lang.String msg, java.lang.Throwable throwable)Methodpublic void log(java.lang.String msg,java.lang.Throwable throwable)
This log() method writes the passed-in message and the stack trace of the passed-inThrowable object to the context’s log. The location of the log is servlet-engine specific. log()returns no value and throws no exceptions.
It has two parameters:
• java.lang.String
• java.lang.Throwable
The getRealPath() Methodpublic java.lang.String getRealPath(java.lang.String path)
The getRealPath() method returns a string representing the passed-in virtual path convertedto the real path based on the operating system on which the servlet engine is running.getRealPath() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.String
The getServerInfo() Methodpublic java.lang.String getServerInfo()
The getServerInfo() method returns a string representing the name and version of theservlet. getServerInfo() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getAttribute() Methodpublic java.lang.Object getAttribute(java.lang.String name)
Appendixes
PART IV438
![Page 458: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/458.jpg)
The getAttribute() method returns an object stored in the ServletContext and keyed by thename value passed in. This is one of the methods used to share resources between servlets. Thereturning object must be downcast to its original type before use. getAttribute() throws noexceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.Object
The getAttributeNames() Methodpublic java.util.Enumeration getAttributeNames()
The getAttributeNames() method returns an enumeration of strings representing the namesof the attributes currently stored in the ServletContext. getAttributeNames() has no para-meters and throws no exceptions.
It returns this value:
• java.util.Enumeration
The setAttribute() Methodpublic void setAttribute(java.lang.String name,java.lang.Object)
The setAttribute() method stores an object in the ServletContext and binds the object tothe given name. If the name already exists in the ServletContext, it is replaced.setAttribute() returns no value and throws no exceptions.
It has two parameters:
• java.lang.String
• java.lang.Object
The removeAttribute() Methodpublic void removeAttribute(java.lang.String name)
The removeAttribute() method removes the object, which is bound to the passed-in name,from the ServletContext. removeAttribute() returns no value and throws no exceptions.
It has one parameter:
• java.lang.String
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
439
![Page 459: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/459.jpg)
The ServletRequest Interfacepublic interface ServletRequest
The ServletRequest interface defines an object used to encapsulate information about theclient’s request. Information in the ServletRequest object includes parameter name/valuepairs, attributes, and an input stream. The ServletRequest interface defines the followingmethods to access this information.
The getAttribute() Methodpublic java.lang.Object getAttribute(java.lang.String name)
The getAttribute() method returns the value of the object keyed by the name string for thecurrent request. getAttribute() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.Object
The getAttributeNames() Methodpublic java.util.Enumeration getAttributeNames()
The getAttributeNames() method returns an enumeration containing the names of all theattributes in the current request. getAttributeNames() has no parameters and throws noexceptions.
It returns this value:
• java.util.Enumeration
The getCharacterEncoding() Methodpublic java.lang.String getCharacterEncoding()
The getCharacterEncoding() method returns a string representing the character set encodingfor this request. getCharacterEncoding() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getContentLength() Methodpublic int getContentLength()
Appendixes
PART IV440
![Page 460: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/460.jpg)
The getContentLength() method returns an integer value equal to the length of the request’sdata. It is equivalent to the CGI variable CONTENT_LENGTH. getContentLength() has no para-meters and throws no exceptions.
It returns this value:
• int
The getContentType() Methodpublic java.lang.String getContentType()
The getContentType() method returns a string representing the MIME type of the request’sdata. It is equivalent to the CGI variable CONTENT_TYPE. getContentType() has no parametersand throws no exceptions.
It returns this value:
• java.lang.String
The getInputStream() Methodpublic ServletInputStream getInputStream()throws java.io.IOException
The getInputStream() method returns an input stream for reading binary data from therequest’s body. getInputStream() has no parameters.
It returns this value:
• ServletInputStream
It throws this exception:
• java.io.IOException
The getLocale() Methodpublic Locale getLocale()
The getLocale() method returns the client’s most preferred locale. getLocale() has no para-meters and throws no exceptions.
It returns this value:
• Locale
The getLocales() Methodpublic Enumeration getLocales()
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
441
![Page 461: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/461.jpg)
The getLocales() method returns an enumeration containing the client’s most preferredLocale objects. getLocales() has no parameters and throws no exceptions.
It returns this value:
• Enumeration
The getParameter() Methodpublic java.lang.String getParameter(java.lang.String name)
The getParameter() method returns the value of the requested parameter. If the parameter hasor could have more than one value, use the getParameterValues() method. getParameter()throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.String
The getParameterNames() Methodpublic java.util.Enumeration getParameterNames()
The getParameterNames() method returns an enumeration of strings representing the parame-ter names for this request. getParameterNames() has no parameters and throws no exceptions.
It returns this value:
• java.util.Enumeration
The getParameterValues() Methodpublic java.lang.String[] getParameterValues(java.lang.String name)
The getParameterValues() method returns an array of strings representing all values for thenamed parameter in the current request. getParameterValues() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.String[]
The getProtocol() Methodpublic java.lang.String getProtocol()
Appendixes
PART IV442
![Page 462: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/462.jpg)
The getProtocol() method returns a string representing the protocol and version of therequest. It is the same as the CGI variable SERVER_PROTOCOL. getProtocol() has no parame-ters and throws no exceptions.
It returns this value:
• java.lang.String
The getRequestDispatcher() Methodpublic RequestDispatcher getRequestDispatcher(java.lang.String path)
The getRequestDispatcher() method returns a RequestDispatcher object using a relativepath. getRequestDispatcher() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• RequestDispatcher
The getScheme() Methodpublic java.lang.String getScheme()
The getScheme() method returns a string representing the scheme of the URL used in therequest. Example schemes include http, https, and ftp. getScheme() has no parameters andthrows no exceptions.
It returns this value:
• java.lang.String
The getServerName() Methodpublic java.lang.String getServerName()
The getServerName() method returns a string representing the host name of the server thatreceived the request. It is the same as the CGI variable SERVER_NAME. getServerName() has noparameters and throws no exceptions.
It returns this value:
• java.lang.String
The getServerPort() Methodpublic int getServerPort()
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
443
![Page 463: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/463.jpg)
The getServerPort() method returns an integer representing the port number on which therequest was received. It is the same as the CGI variable SERVER_PORT. getServerPort() hasno parameters and throws no exceptions.
It returns this value:
• int
The getReader() Methodpublic java.io.BufferedReader getReader()throws java.io.IOException
The getReader() method returns a BufferedReader for reading text input from the requestbody. getReader() has no parameters.
It returns this value:
• java.io.BufferedReader
It throws this exception:
• java.io.IOException
The getRemoteAddress() Methodpublic java.lang.String getRemoteAddress()
The getRemoteAddress() method returns a string representing the IP address of the clientsending the request. It is the same as the CGI variable REMOTE_ADDR. getRemoteAddress() hasno parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getRemoteHost() Methodpublic java.lang.String getRemoteHost()
The getRemoteHost() method returns a string representing the qualified hostname of the clientsending the request. It is the same as the CGI variable REMOTE_HOST. getRemoteHost() has noparameters and throws no exceptions.
It returns this value:
• java.lang.String
The isSecure() Methodpublic boolean isSecure()
Appendixes
PART IV444
![Page 464: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/464.jpg)
The isSecure() method returns a boolean value indicating whether the request was madewith a secure channel. isSecure() has no parameters and throws no exceptions.
It returns this value:
• boolean
The removeAttribute() Methodpublic void removeAttribute(java.lang.String name)
The removeAttribute() method removes the named attribute from the ServletRequest.removeAttribute() returns no value and throws no exceptions.
It has one parameter:
• java.lang.String
The setAttribute() Methodpublic void setAttribute(java.lang.String key,java.lang.Object object) throws IllegalStateException
The setAttribute() method adds an attribute to the request’s context keyed by the passed-inkey string. It throws an IllegalStateException if the key already exists. setAttribute()returns no value.
It has two parameters:
• java.lang.String
• java.lang.Object
It throws this exception:
• IllegalStateException
The ServletResponse Interfacepublic interface ServletResponse
The ServletResponse interface defines an object for sending MIME data back to the clientfrom the servlet’s service method. The ServletResponse object is a parameter of the servlet’sservice method. The ServletResponse interface defines several methods for implementingobjects.
The flushBuffer() Methodpublic void flushBuffer()throws IOException
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
445
![Page 465: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/465.jpg)
The flushBuffer() method flushes and commits the response. flushBuffer() has no parame-ters and returns no value.
It throws this exception:
• java.io.IOException
The getBufferSize() Methodpublic int getBufferSize()
The getBufferSize() method returns the size of the response buffer. getBufferSize() has noparameters and throws no exceptions.
It returns this value:
• int
The getCharacterEncoding() Methodpublic java.lang.String getCharacterEncoding()
The getCharacterEncoding() method returns the character set encoding used for thisrequest’s body. If there has been no content type assigned, it is, by default, set to text/plain.getCharacterEncoding() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getLocale() Methodpublic Locale getLocale()
The getLocale() method returns the current response locale. getLocale() has no parametersand throws no exceptions.
It returns this value:
• Locale
The getOutputStream() Methodpublic ServletOutputStream getOutputStream()throws java.io.IOException
The getOutputStream() method returns an output stream used for writing binary data to theresponse. getOutputStream() has no parameters.
It returns this value:
• ServletOutputStream
Appendixes
PART IV446
![Page 466: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/466.jpg)
It throws this exception:
• java.io.IOException
The getWriter() Methodpublic java.io.PrintWriter getWriter()throws java.io.IOException
The getWriter() method returns a print writer used for writing formatted text to the responseobject. getWriter() has no parameters.
It returns this value:
• java.io.PrintWriter
It throws this exception:
• java.io.IOException
The isCommitted() Methodpublic boolean isCommitted()
The isCommitted() method returns true if part of the response has already been sent.isCommitted() has no parameters and throws no exceptions.
It returns this value:
• boolean
The reset() Methodpublic void reset()
The reset() method empties the response buffer and clears the response headers. reset() hasno parameters, returns no value, and throws no exceptions.
The setBufferSize() Methodpublic void setBufferSize(int size)
The setBufferSize() method sets the size of the response buffer. setBufferSize() returnsno value and throws no exceptions.
It has one parameter:
• int
The setContentLength() Methodpublic void setContentLength(int len)
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
447
![Page 467: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/467.jpg)
The setContentLength() method sets the content length of the current response.setContentLength() returns no value and throws no exceptions.
It has one parameter:
• int
The setContentType() Methodpublic void setContentType(java.lang.String type)
The setContentType() method sets the content type of the current response. You can set thisproperty only once for the current response. This method must be called before calling thegetWriter() or getOuputStream() methods. setContentType() returns no value and throwsno exceptions.
It has one parameter:
• java.lang.String
The setLocale() Methodpublic void setLocale(Locale locale)
The setLocale() method sets the response locale, including headers and character sets.setLocale() returns no value and throws no exceptions.
It has one parameter:
• Locale
The SingleThreadModel Interfacepublic interface SingleThreadModel
The SingleThreadModel interface defines a single threaded model for implementing theservlet’s execution. Implementing this interface makes the servlet thread safe. This guaranteesthat the implementing servlet’s service method will not be executed concurrently by more thanone thread. No methods are defined by the SingleThreadModel interface.
ClassesClasses for the javax.servlet package are GenericServlet, ServletInputStream, andServletOutputStream. Their methods are described in the following sections.
Appendixes
PART IV448
![Page 468: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/468.jpg)
The GenericServlet ClassThe GenericServlet class was created to provide a basic foundation of new servlets. It pro-vides default life cycle methods and default implementations of the ServletConfig’s methods.
The GenericServlet() Methodpublic GenericServlet()
The GenericServlet() method is an empty default constructor. GenericServlet() has noparameters, returns no value, and throws no exceptions.
The destroy() Methodpublic void destroy()
The destroy() method is executed when the servlet is removed from the running service. Itperforms any cleanup of resources that were allocated in the init() method. destroy() hasno parameters, returns no value, and throws no exceptions.
The getInitParameter() Methodpublic java.lang.String getInitParameter(java.lang.String name)
The getInitParameter() method returns a string containing the value of the initializationparameter keyed by the passed-in name. getInitParameter() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.String
The getInitParameterNames() Methodpublic java.util.Enumeration getInitParameterNames()
The getInitParameterNames() method returns an enumeration containing all of the names foreach initialization parameter. getInitParameterNames() has no parameters and throws noexceptions.
It returns this value:
• java.util.Enumeration
The getServletConfig() Methodpublic ServletConfig getServletConfig()
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
449
![Page 469: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/469.jpg)
The getServletConfig() method returns a ServletConfig object containing any startup con-figuration information for this servlet. getServletConfig() has no parameters and throws noexceptions.
It returns this value:
• ServletConfig
The getServletContext() Methodpublic ServletContext getServletContext()
The getServletContext() method returns a ServletContext object containing informationabout the servlet’s network service. getServletContext() has no parameters and throws noexceptions.
It returns this value:
• ServletContext
The getServletInfo() Methodpublic java.lang.String getServletInfo()
The getServletInfo() method returns a string containing servlet-specific information aboutthe implementing servlet. getServletInfo() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The init(ServletConfig config) Methodpublic void init(ServletConfig config)throws ServletException
This init() method marks the beginning of a servlet’s life. It is called only when the servlet isfirst loaded, and it must execute successfully before the servlet can service requests. Theinit() method should contain all initialization code for the servlet. It returns no value.
It has one parameter:
• ServletConfig (encapsulates the servlet’s startup configuration and initialization para-meters)
It throws this exception:
• ServletException
Appendixes
PART IV450
![Page 470: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/470.jpg)
The init() Methodpublic void init()throws ServletException
This parameterless implementation of the init() method is provided only for convenience. Itprevents a derived servlet from having to store the ServletConfig object. init() has no para-meters and returns no value.
It throws this exception:
• ServletException
The log(java.lang.String message) Methodpublic void log(java.lang.String message)
This log() method takes the passed-in message and the name of the servlet and writes them toa log file. The location of the log is server specific. log() returns no value and throws noexceptions.
It has one parameter:
• java.lang.String
The log(java.lang.String message, java.lang.Throwable t)Methodpublic void log(java.lang.String message,java.lang.Throwable t)
This log() method takes the passed-in message and Throwable object and logs the messagewith a stack trace from the Throwable object. log() returns no value and throws no excep-tions.
It has two parameters:
• java.lang.String
• java.lang.Throwable
The service() Methodpublic void service(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException
The service() method defines the servlet’s entry point for servicing requests. It can be exe-cuted only after the servlet’s init() method has executed successfully. The service() methodis the life cycle method executed for every incoming request. It returns no value.
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
451
![Page 471: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/471.jpg)
It has two parameters:
• ServletRequest
• ServletResponse
It throws these exceptions:
• ServletException
• java.io.IOException
The ServletInputStream ClassThe ServletInputStream is an abstract class defined for servlet writers to get data from theclient. It is meant to be implemented by a network services writer. This class has two methods.
The ServletInputStream() Methodprotected ServletInputStream()
The ServletInputStream() method is the empty default constructor. It has no parameters,returns no value, and throws no exceptions.
The readLine() Methodpublic void readLine(byte[] b,int off,int len)throws java.io.IOException
The readLine() method reads the len of bytes into the passed-in byte array b, starting at posi-tion off. If the character \n is encountered, no more bytes are read in. readLine() returns novalue.
It has three parameters:
• byte[]
• int
• int
It throws this exception:
• java.io.IOException
The ServletOutputStream ClassThe ServletOutputStream class is used to write responses back to the client. It is an abstractclass that is implemented by the network services implementor. To access the
Appendixes
PART IV452
![Page 472: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/472.jpg)
ServletOutputStream, you must call the ServletResponse’s getOutputStream() method.The class has several methods.
The ServletOutputStream() Methodpublic ServletOutputStream()throws java.io.IOException
The ServletOutputStream() method is the empty default constructor. It has no parametersand returns no value.
It throws this exception:
• java.io.IOException
The print(boolean value) Methodpublic void print(boolean value)throws java.io.IOException
This version of the print() method prints the passed-in boolean value to the output stream.
It has one parameter:
• boolean
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
453
The print() method always throws a java.io.IOException exception. For all printvalues, the print() method returns no value.
NOTE
The print(char value) Methodpublic void print(char value)throws java.io.IOException
This version of the print() method prints the passed-in char value to the output stream.
It has one parameter:
• char
The print(double value) Methodpublic void print(double value)throws java.io.IOException
This version of the print() method prints the passed-in double value to the output stream.
![Page 473: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/473.jpg)
It has one parameter:
• double
The print(float value) Methodpublic void print(float value)throws java.io.IOException
This version of the print() method prints the passed-in float value to the output stream.
It has one parameter:
• float
The print(int value) Methodpublic void print(int value)throws java.io.IOException
This version of the print() method prints the passed-in int value to the output stream.
It has one parameter:
• int
The print(long value) Methodpublic void print(long value)throws java.io.IOException
This version of the print() method prints the passed-in long value to the output stream.
It has one parameter:
• long
The print(java.lang.String value) Methodpublic void print(java.lang.String value)throws java.io.IOException
This version of the print() method prints the passed-in String value to the output stream.
It has one parameter:
• java.lang.String
The println() Methodpublic void println()throws java.io.IOException
Appendixes
PART IV454
![Page 474: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/474.jpg)
This version of the println() method prints CRLF to the output stream and has no parameters.
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
455
The println() method always throws a java.io.IOException exception. For all printvalues, the println() method returns no value.
NOTE
The println(java.lang.String value) Methodpublic void println(java.lang.String value)throws java.io.IOException
This version of the println() method prints the passed-in String value to the output stream,followed by a CRLF.
It has one parameter:
• java.lang.String
The println(boolean value) Methodpublic void println(boolean value)throws java.io.IOException
This version of the println() method prints the passed-in boolean value to the output stream,followed by a CRLF.
It has one parameter:
• boolean
The println(char value) Methodpublic void println(char value)throws java.io.IOException
This version of the println() method prints the passed-in char value to the output stream, fol-lowed by a CRLF.
It has one parameter:
• char
The println(int value) Methodpublic void println(int value)throws java.io.IOException
This version of the println() method prints the passed-in int value to the output stream, fol-lowed by a CRLF.
![Page 475: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/475.jpg)
It has one parameter:
• int
The println(long value) Methodpublic void println(long value)throws java.io.IOException
This version of the println() method prints the passed-in long value to the output stream, fol-lowed by a CRLF.
It has one parameter:
• long
The println(float value) Methodpublic void println(float value)throws java.io.IOException
This version of the println() method prints the passed-in float value to the output stream,followed by a CRLF.
It has one parameter:
• float
The println(double value) Methodpublic void println(double value)throws java.io.IOException
This version of the println() method prints the passed-in double value to the output stream,followed by a CRLF.
It has one parameter:
• double
ExceptionsExceptions for the javax.servlet package are ServletException andUnavailableException. Their methods are described in the following sections.
The ServletExceptionA ServletException object is thrown when a problem is encountered within a servlet.
Appendixes
PART IV456
![Page 476: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/476.jpg)
The ServletException() Methodpublic ServletException()
The ServletException() method is the empty constructor. It has no parameters, returns novalue, and throws no exceptions.
The ServletException(java.lang.String message) Methodpublic ServletException(java.lang.String message)
This method creates a new ServletException object with the passed in string as the message.
It has one parameter:
• java.lang.String
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
457
The ServletException() method always returns no value and throws no exceptions.
NOTE
The ServletException(java.lang.String message,java.lang.Throwable rootCause) Methodpublic ServletException(java.lang.String message,java.lang.Throwable rootCause)
This method creates a ServletException object with a message and a Throwable object repre-senting the cause of the exception.
It has two parameters:
• java.lang.String
• java.lang.Throwable
The ServletException() Methodpublic ServletException(java.lang.Throwable rootCause)
This method creates a new ServletException object with a Throwable object representing thecause of the exception.
It has one parameter:
• java.lang.Throwable
The getRootCause() Methodpublic java.lang.Throwable getRootCause()
![Page 477: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/477.jpg)
The getRootCause() method returns a Throwable object representing the cause of the excep-tion. getRootCause() has no parameters and throws no exceptions.
It returns this value:
• java.lang.Throwable
The UnavailableExceptionAn UnavailableException is thrown when a servlet is not available to service a request. Thetwo types of UnavailableExceptions are permanent and temporary.
When a servlet is permanently unavailable, the servlet will not be able to service requests untilsome administrative task is completed.
When a servlet is temporarily unavailable, the servlet is expected to be able to service requestswithin a given period of time.
The UnavailableException(java.lang.String msg, int seconds)Constructorpublic UnavailableException(java.lang.String msg, int seconds)
This constructor creates an UnavailableException() with an int value, representing a esti-mated time of unavailability. It also receives a reference to a String representing the errormessage.
It has two parameters:
• java.lang.String
• int
The UnavailableException(java.lang.String msg) Methodpublic UnavailableException(java.lang.String msg)
This constructor creates an UnavailableException() with a String representing the errormessage. This constructor create an UnavailableException(), denoting permanent unavail-ability
It has one parameter:
• java.lang.String
The isPermanent() Methodpublic boolean isPermanent()
Appendixes
PART IV458
![Page 478: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/478.jpg)
The isPermanent() method returns true if the servlet is permanently unavailable; otherwise,it returns false. isPermanent() has no parameters and throws no exceptions.
It returns this value:
• boolean
The getUnavailableSeconds() Methodpublic int getUnavailableSeconds()
The getUnavailableSeconds() method returns an int representing the number of seconds aservlet is expected to be temporarily unavailable. getUnavailableSeconds() has no parame-ters and throws no exceptions.
It returns this value:
• int
The javax.servlet Package
APPENDIX B
B
TH
EJA
VA
X.SERV
LETP
AC
KA
GE
459
![Page 479: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/479.jpg)
![Page 480: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/480.jpg)
APPENDIX
CThe javax.servlet.httpPackage
IN THIS APPENDIX• Interfaces 462
• Classes 479
![Page 481: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/481.jpg)
The java.servlet.http package contains the interfaces and classes that are implemented andextended, respectively, to create HTTP-specific servlets. Figure C.1 illustrates thejavax.servlet.http object model.
Appendixes
PART IV462
javax.servlet.http.HttpUtils
<<Interface>>java.util.EventListener
java.util.EventObject
javax.servlet.http.Cookie
<<Interface>>javax.servlet.http.HttpServletRequest
java.lang.Object <<Interface>>javax.servlet.Servlet
<<Interface>>javax.servlet.ServletRequest
<<Interface>>javax.servlet.http.HttpSession
<<Interface>>javax.servlet.http.HttpSessionContext
<<Interface>>javax.servlet.http.HttpSessionBindingListener
<<Interface>>javax.servlet.ServletResponse
<<Interface>>javax.servlet.http.HttpServletResponse
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
javax.servlet.http.HttpSessionBindingEvent
<<Interface>>java.lang.Cloneable
<<Interface>>javax.servlet.ServletConfig
<<Interface>>java.io.Serializable
FIGURE C.1The javax.servlet.http object model.
InterfacesInterfaces for the java.servlet.http package are HttpServletRequest,HttpServletResponse, HttpSession, and HttpSessionBindingListener.
The HttpServletRequest Interfacepublic interface HttpServletRequestextends ServletRequest
The HttpServletRequest interface defines an object that provides the HttpServlet.service() method with access to HTTP-protocol specific header informationsent by the client. The HttpServletRequest interface has 26 methods, described in the follow-ing sections.
![Page 482: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/482.jpg)
The getAuthType() Methodpublic java.lang.String getAuthType()
The getAuthType() method returns the authentication scheme used in this request. It is thesame as the AUTH_TYPE CGI variable. getAuthType() has no parameters and throws no excep-tions.
It returns this value:
• java.lang.String
The getContextPath() Methodpublic java.lang.String getContextPath()
The getContextPath() method returns the context path of this request. getContextPath() hasno parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getCookies() Methodpublic Cookie[] getCookies()
The getCookies() method returns an array of Cookie objects found in the client request.getCookies() has no parameters and throws no exceptions.
It returns this value:
• Cookie[]
The getDateHeader() Methodpublic long getDateHeader(java.lang.String name)
The getDateHeader() method returns the value of the requested date header field found in theclient request. getDateHeader() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• long
The getHeader() Methodpublic java.lang.String getHeader(java.lang.String name)
The javax.servlet.http Package
APPENDIX C463
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 483: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/483.jpg)
The getHeader() method returns the value of the requested header field found in the clientrequest. getHeader() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.String
The getHeaders() Methodpublic Enumeration getHeaders(java.lang.String name)
The getHeaders() method returns an enumeration of strings containing all of the values forthe given header. getHeaders() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• Enumeration
The getHeaderNames() Methodpublic Enumeration getHeaderNames()
The getHeaderNames() method returns an enumeration containing all of the header namesfound in the client request. getHeaderNames() has no parameters and throws no exceptions.
It returns this value:
• Enumeration
The getIntHeader() Methodpublic int getIntHeader(java.lang.String name)
The getIntHeader() method returns the int value of the named header field found in theclient request. getIntHeader() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• int
Appendixes
PART IV464
![Page 484: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/484.jpg)
The getMethod() Methodpublic java.lang.String getMethod()
The getMethod() method returns the HTTP method used by the client request. It is the sameas the CGI variable REQUEST_METHOD. getMethod() has no parameters and throws no excep-tions.
It returns this value:
• java.lang.String
getPathInfo() Methodpublic java.lang.String getPathInfo()
The getPathInfo() method returns a string containing any additional path information follow-ing the servlet path, but preceding the query string. It is the same as the CGI variablePATH_INFO. getPathInfo() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getPathTranslated() Methodpublic java.lang.String getPathTranslated()
The getPathTranslated() method returns the same information as the getPathInfo()method, but translates the path to its real path name before returning it. It is the same as theCGI variable PATH_TRANSLATED. getPathTranslated() has no parameters and throws noexceptions.
It returns this value:
• java.lang.String
getQueryString() Methodpublic java.lang.String getQueryString()
The getQueryString() method returns the query string from the request. It is the same as theCGI variable QUERY_STRING. getQueryString() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getRemoteUser() Methodpublic java.lang.String getRemoteUser()
The javax.servlet.http Package
APPENDIX C465
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 485: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/485.jpg)
The getRemoteUser() method returns the name of the user making the request. If the name isnot available, null is returned. It is the same as the CGI variable REMOTE_USER.getRemoteUser() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getRequestedSessionId() Methodpublic java.lang.String getRequestedSessionId()
The getRequestedSessionId() method returns the session ID associated with the request.getRequestedSessionId() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getRequestURI() Methodpublic java.lang.String getRequestURI()
The getRequestURI() method returns the first line of the request’s URI. This is the part of theURI that is found to the left of the query string. getRequestURI() has no parameters andthrows no exceptions.
It returns this value:
• java.lang.String
The getUserPrincipal() Methodpublic java.security.Principal getUserPrincipal()
The getUserPrincipal() method returns the principal of the user making the request.getUserPrincipal() has no parameters and throws no exceptions.
It returns this value:
• java.security.Principal
The getServletPath() Methodpublic java.lang.String getServletPath()
The getServletPath() method returns the part of the URI that refers to the servlet beinginvoked. getServletPath() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
Appendixes
PART IV466
![Page 486: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/486.jpg)
The getSession(boolean create) Methodpublic HttpSession getSession(boolean create)
This getSession() method returns the session associated with the request. If there is no validsession and the boolean parameter passed in is true, it will create a new session.getSession() throws no exceptions.
It has one parameter:
• boolean
It returns this value:
• HttpSession
The getSession() Methodpublic HttpSession getSession()
This getSession() method performs the same as the previous getSession() method; it justperforms as if it were always passed a true value. getSession() has no parameters andthrows no exceptions.
It returns this value:
• HttpSession
The isRequestedSessionValid() Methodpublic boolean isRequestedSessionValid()
The isRequestedSessionValid() method returns true if the session is valid in the currentcontext; otherwise, it returns false. isRequestedSessionValid() has no parameters andthrows no exceptions.
It returns this value:
• boolean
The isRequestedSessionFromCookie() Methodpublic boolean isRequestedSessionFromCookie()
The isRequestedSessionFromCookie() method returns true if the session ID from therequest came in as a cookie; otherwise, it returns false. isRequestedSessionFromCookie()has no parameters and throws no exceptions.
It returns this value:
• boolean
The javax.servlet.http Package
APPENDIX C467
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 487: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/487.jpg)
The isRequestedSessionIdFromURL() Methodpublic boolean isRequestedSessionIdFromURL()
The isRequestedSessionIdFromURL() method returns true if the session ID from the requestcame in as part of the URL; otherwise it returns false. isRequestedSessionIdFromURL() hasno parameters and throws no exceptions.
It returns this value:
• boolean
The HttpServletResponse Interfacepublic interface HttpServletResponseextends ServletRequest
The HttpServletResponse interface defines an object that provides the HttpServlet.service() method with the capability to manipulate HTTP-protocol specificheader information and return data to the client. The HttpServletResponse interface has 39fields and 10 methods, described in the following sections.
The SC_CONTINUE Fieldpublic static final int SC_CONTINUE
This field represents a status code of (100), indicating that the client can continue.
The SC_SWITCHING_PROTOCOLS Fieldpublic static final int SC_SWITCHING_PROTOCOLS
This field represents a status code of (101), indicating the server is switching protocols accord-ing to the Upgrade header.
The SC_OK Fieldpublic static final int SC_OK
This field represents a status code of (200), indicating the request succeeded normally.
The SC_CREATED Fieldpublic static final int SC_CREATED
This field represents a status code of (201), indicating the request succeeded and created a newresource on the server.
The SC_ACCEPTED Fieldpublic static final int SC_ACCEPTED
Appendixes
PART IV468
![Page 488: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/488.jpg)
This field represents a status code of (202), indicating that a request was accepted for process-ing, but was not completed.
The SC_NON_AUTHORITATIVE_INFORMATION Fieldpublic static final int SC_NON_AUTHORITATIVE_INFORMATION
This field represents a status code of (203), indicating that the meta information presented bythe client did not originate from the server.
The SC_NO_CONTENT Fieldpublic static final int SC_NO_CONTENT
This field represents a status code of (204), indicating that the request succeeded but that therewas no new information to return.
The SC_RESET_CONTENT Fieldpublic static final int SC_RESET_CONTENT
This field represents a status code of (205), indicating that the agent should reset the documentview that caused the request to be sent.
The SC_PARTIAL_CONTENT Fieldpublic static final int SC_PARTIAL_CONTENT
This field represents a status code of (206), indicating that the server has fulfilled the partialGET request for the resource.
The SC_MULTIPLE_CHOICES Fieldpublic static final int SC_MULTIPLE_CHOICES
This field represents a status code of (300), indicating that the requested resource correspondsto any one of a set of representations, each with its own specific location.
The SC_MOVED_PERMANENTLY Fieldpublic static final int SC_MOVED_PERMANENTLY
This field represents a status code of (301), indicating that the resource has permanentlymoved to a new location, and that future references should use a new URI with their requests.
The SC_MOVED_TEMPORARILY Fieldpublic static final int SC_MOVED_TEMPORARILY
This field represents a status code of (302), indicating that the resource has temporarily movedto another location, but that future references should still use the original URI to access theresource.
The javax.servlet.http Package
APPENDIX C469
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 489: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/489.jpg)
The SC_SEE_OTHER Fieldpublic static final int SC_SEE_OTHER
This field represents a status code of (303), indicating that the response to the request can befound under a different URI.
The SC_NOT_MODIFIED Fieldpublic static final int SC_NOT_MODIFIED
Thistus code of (304), indicating that a conditional GET operation found that the resource wasavailable and not modified.
The SC_USE_PROXY Fieldpublic static final int SC_USE_PROXY
This field represents a status code of (305), indicating that the requested resource must beaccessed through the proxy given by the location field.
The SC_BAD_REQUEST Fieldpublic static final int SC_BAD_REQUEST
This field represents a status code of (400), indicating the request sent by the client was syntac-tically incorrect.
The SC_UNAUTHORIZED Fieldpublic static final int SC_UNAUTHORIZED
This field represents a status code of (401), indicating that the request requires HTTP authenti-cation.
The SC_PAYMENT_REQUIRED Fieldpublic static final int SC_PAYMENT_REQUIRED
This field represents a status code of (402) for future use.
The SC_FORBIDDEN Fieldpublic static final int SC_FORBIDDEN
This field represents a status code of (403), indicating the server understood the request butrefused to fulfill it.
The SC_NOT_FOUND Fieldpublic static final int SC_NOT_FOUND
Appendixes
PART IV470
![Page 490: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/490.jpg)
This field represents a status code of (404), indicating that the requested resource is not avail-able.
The SC_METHOD_NOT_ALLOWED Fieldpublic static final int SC_METHOD_NOT_ALLOWED
This field represents a status code of (405), indicating that the method specified in theRequest-Line is not allowed for the resource identified by the Request-URI.
The SC_NOT_ACCEPTABLE Fieldpublic static final int SC_NOT_ACCEPTABLE
This field represents a status code of (406), indicating that the resource identified by therequest is only capable of generating response entities which have content characteristics notacceptable according to the accept headers sent in the request.
The SC_PROXY_AUTHENTICATION_REQUIRED Fieldpublic static final int SC_PROXY_AUTHENTICATION_REQUIRED
This field represents a status code of (407), indicating that the client must first authenticateitself with the proxy.
The SC_REQUEST_TIMEOUT Fieldpublic static final int SC_REQUEST_TIMEOUT
This field represents a status code of (408), indicating that the client did not produce a requestwithin the time that the server was prepared to wait.
The SC_CONFLICT Fieldpublic static final int SC_CONFLICT
This field represents a status code of (409), indicating that the request could not be completedbecause of a conflict with the current state of the resource.
The SC_GONE Fieldpublic static final int SC_GONE
This field represents a status code of (410), indicating that the resource is no longer availableat the server and no forwarding address is known. This condition should be considered perma-nent.
The SC_LENGTH_REQUIRED Fieldpublic static final int SC_LENGTH_REQUIRED
The javax.servlet.http Package
APPENDIX C471
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 491: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/491.jpg)
This field represents a status code of (411), indicating that the request cannot be handled with-out a defined Content-Length.
The SC_PRECONDITION_FAILED Fieldpublic static final int SC_PRECONDITION_FAILED
This field represents a status code of (412), indicating that the precondition given in one ormore of the request-header fields evaluated to false when it was tested on the server.
The SC_REQUEST_ENTITY_TOO_LARGE Fieldpublic static final int SC_REQUEST_ENTITY_TOO_LARGE
This field represents a status code of (413), indicating that the server is refusing to process therequest because the request entity is larger than the server is willing or able to process.
The SC_REQUEST_URI_TOO_LONG Fieldpublic static final int SC_REQUEST_URI_TOO_LONG
This field represents a status code of (414), indicating that the server is refusing to service therequest because the Request-URI is longer than the server is willing to interpret.
The SC_UNSUPPORTED_MEDIA_TYPE Fieldpublic static final int SC_UNSUPPORTED_MEDIA_TYPE
This field represents a status code of (415), indicating that the server is refusing to service therequest because the entity of the request is in a format not supported by the requested resourcefor the requested method.
The SC_INTERNAL_SERVER_ERROR Fieldpublic static final int SC_INTERNAL_SERVER_ERROR
This field represents a status code of (500), indicating an error inside the HTTP server that pre-vented it from fulfilling the request.
The SC_NOT_IMPLEMENTED Fieldpublic static final int SC_NOT_IMPLEMENTED
This field represents a status code of (501), indicating the HTTP server does not support thefunctionality needed to fulfill the request.
The SC_BAD_GATEWAY Fieldpublic static final int SC_BAD_GATEWAY
This field represents a status code of (502), indicating that the HTTP server received an invalidresponse from a server it consulted when acting as a proxy or gateway.
Appendixes
PART IV472
![Page 492: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/492.jpg)
The SC_SERVICE_UNAVAILABLE Fieldpublic static final int SC_SERVICE_UNAVAILABLE
This field represents a status code of (503), indicating that the HTTP server is temporarilyoverloaded, and unable to handle the request.
The SC_GATEWAY_TIMEOUT Fieldpublic static final int SC_GATEWAY_TIMEOUT
This field represents a status code of (504), indicating that the server did not receive a timelyresponse from the upstream server while acting as a gateway or proxy.
The SC_HTTP_VERSION_NOT_SUPPORTED Fieldpublic static final int SC_HTTP_VERSION_NOT_SUPPORTED
This field represents a status code of (505), indicating that the server does not support orrefuses to support the HTTP version found in the request.
The addCookie() Methodpublic void addCookie(Cookie cookie)
The addCookie() method adds a Cookie to the HttpServletResponse object. addCookie()throws no exceptions and returns no value.
It has one parameter:
• Cookie
The containsHeader() Methodpublic boolean containsHeader(java.lang.String name)
The containsHeader() method returns true if the named header exists in the response.containsHeader() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• boolean
The encodeURL() Methodpublic java.lang.String encodeURL(java.lang.String url)
The encodeURL() method’s URL encodes the passed-in string and returns it. If no changes arenecessary, then it simply returns the string. encodeURL() throws no exceptions.
The javax.servlet.http Package
APPENDIX C473
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 493: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/493.jpg)
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.String
The encodeRedirectURL() Methodpublic java.lang.String encodeRedirectURL(java.lang.String url)
The encodeRedirectURL() method’s URL encodes the passed-in string for use in thesendRedirect() method. If no changes are necessary, it simply returns the string.encodeRedirectURL() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.String
The sendError(int sc, java.lang.String message) Methodpublic void sendError(int sc,java.lang.String message)
throws java.io.IOException
This sendError() method sends an error to the client in the response object. The error consistsof the int status code and a string message. sendError() returns no value.
It has two parameters:
• int
• java.lang.String
It throws this exception:
• java.io.IOException
The sendError(int sc) Methodpublic void sendError(int sc)throws java.io.IOException
This sendError() method sends an error to the client in the response object. The error consistsof only the int status code. sendError() returns no value.
Appendixes
PART IV474
![Page 494: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/494.jpg)
It has one parameter:
• int
It throws this exception:
• java.io.IOException
The sendRedirect() Methodpublic void sendRedirect(java.lang.String url)throws java.io.IOException
The sendRedirect() method redirects the client to the passed-in URL, which must be anabsolute URL. sendRedirect() returns no value.
It has one parameter:
• java.lang.String
It throws this exception:
• java.io.IOException
The setDateHeader() Methodpublic void setDateHeader(java.lang.String name,long date)
The setDateHeader() method adds a name/date-value field to the response header. The datevalue is a long representing milliseconds since the epoch. setDateHeader() returns no valueand throws no exception.
It has two parameters:
• java.lang.String
• long
The setIntHeader() Methodpublic void setIntHeader(java.lang.String name,int value)
The setIntHeader() method adds a name/int-value field to the response header. If the field isalready present in the request, it is replaced. setIntHeader() returns no value and throws noexceptions.
It has two parameters:
• java.lang.String
• int
The javax.servlet.http Package
APPENDIX C475
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 495: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/495.jpg)
The setStatus() Methodpublic void setStatus(int sc)
The setStatus() method sets the status code for the response. setStatus() returns no valueand throws no exceptions.
It has one parameter:
• int
The HttpSession Interfacepublic interface HttpSession
The HttpSession interface defines an object that provides an association between a client andserver; this association persists over multiple connections. Using HttpSession gives you theability to maintain state between transactions. This interface has 12 methods, described in thefollowing sections.
The getAttribute() Methodpublic java.lang.Object getAttribute(java.lang.String name)
The getAttribute() method returns a reference to the named object in the current session.The object must be downcasted to its original type. getAttribute() throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.Object
The getAttributeNames() Methodpublic Enumeration getAttributeNames()
The getAttributeNames() method returns an enumeration of strings representing all of thedata objects bound to this session. getAttributeNames() has no parameters and throws noexceptions.
It returns this value:
• Enumeration
The getCreationTime() Methodpublic long getCreationTime()
Appendixes
PART IV476
![Page 496: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/496.jpg)
The getCreationTime() method returns the time in which the session was created. This timevalue is a long representing the milliseconds elapsed since January 1, 1970 UTC.getCreationTime() has no parameters and throws no exceptions.
It returns this value:
• long
The getId() Methodpublic java.lang.String getId()
The getId() method returns a string containing a unique identifier for the currentHttpSession. getId() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getLastAccessedTime() Methodpublic long getLastAccessedTime()
The getLastAccessedTime() method returns the last time, in milliseconds, the client sent arequest with HttpSession. getLastAccessedTime() has no parameters and throws no excep-tions.
It returns this value:
• long
The getMaxIntervalTime() Methodpublic int getMaxIntervalTime()
The getMaxIntervalTime() method returns the maximum interval between requests that theserver will keep the session valid. getMaxIntervalTime() has no parameters and throws noexceptions.
It returns this value:
• int
The invalidate() Methodpublic void invalidate()
The invalidate() method forces the session to be invalidated and removed from the context.invalidate() has no parameters, returns no value, and throws no exceptions.
The javax.servlet.http Package
APPENDIX C477
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 497: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/497.jpg)
The isNew() Methodpublic boolean isNew()
The isNew() method returns true if the server has just created the session and the session hasnot been acknowledged by the client. isNew() has no parameters and throws no exceptions.
It returns this value:
• boolean
The setAttribute() Methodpublic void setAttribute(java.lang.String name)java.lang.Object value)
The setAttribute() method binds the passed-in object to the passed-in string and puts theobject into the session. If an object in the session is already bound to the name, it is replaced.setAttribute() returns no value and throws no exceptions.
It has two parameters:
• java.lang.String
• java.lang.Object
The removeAttribute() Methodpublic void removeAttribute(java.lang.String name)
The removeAttribute() method removes the object from the current session that is bound tothe passed-in name. All objects implementing the HttpSessionBindingListener interface willhave their valueUnbound() methods called. removeAttribute() returns no value and throwsno exceptions.
It has one parameter:
• java.lang.String
The setMaxIntervalTime() Methodpublic void setMaxIntervalTime(int interval)
The setMaxIntervalTime() method sets the maximum interval between requests before aserver invalidates the session. setMaxIntervalTime() returns no value and throws no excep-tions.
It has one parameter:
• int
Appendixes
PART IV478
![Page 498: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/498.jpg)
The HttpSessionBindingListener Interfacepublic interface HttpSessionBindingListenerextends java.util.EventListener
The HttpSessionBindingListener interface defines methods that an object can implement ifit wants to be notified of an object in the session being bound or unbound. TheHttpSessionBindingListener interface has two methods, described in the following sections.
The valueBound() Methodpublic void valueBound(HttpSessionBindingEvent event)
The valueBound() method notifies a listener that the object is being bound into a session.valueBound() returns no value and throws no exceptions.
It has one parameter:
• HttpSessionBindingEvent
The valueUnBound() Methodpublic void valueUnBound(HttpSessionBindingEvent event)
The valueUnBound() method notifies a listener that the object is being unbound from a ses-sion. valueUnBound() returns no value and throws no exceptions.
It has one parameter:
• HttpSessionBindingEvent
ClassesThe four classes for the java.servlet.http package are Cookie, HttpServlet,HttpSessionBindingEvent, and HttpUtils.
The Cookie Classpublic class Cookieextends java.lang.Objectimplements java.lang.Cloneable
The Cookie class represents a cookie used for session management in HTTP protocols.Cookies are name/value pairs that are created by the server and stored in the client. TheCookie class has 17 methods, described in the following sections.
The Cookie() Methodpublic Cookie(java.lang.String name,java.lang.String value)
The javax.servlet.http Package
APPENDIX C479
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 499: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/499.jpg)
The Cookie() constructor initializes a Cookie object with the passed-in name/value pair.Names cannot contain whitespace, commas, or semicolons and should only contain ASCIIalphanumeric characters. Cookie() returns no value and throws no exceptions.
It has two parameters:
• java.lang.String
• java.lang.String
The setComment() Methodpublic void setComment(java.lang.String purpose)
The setComment() method is used to describe the cookie’s purpose when requested by theclient. setComment() returns no value and throws no exceptions.
It has one parameter:
• java.lang.String
The getComment() Methodpublic java.lang.String getComment()
The getComment() method returns the comment used to describe the cookie’s purpose.getComment() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The setDomain() Methodpublic void setDomain(java.lang.String pattern)
The setDomain() method sets the pattern to match the host’s domain. If the host does notmatch, the cookie will not be presented to the host. setDomain() returns no value and throwsno exceptions.
It has one parameter:
• java.lang.String
The getDomain() Methodpublic java.lang.String getDomain()
The getDomain() method returns the domain pattern of this cookie. getDomain() has no para-meters and throws no exceptions.
Appendixes
PART IV480
![Page 500: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/500.jpg)
It returns this value:
• java.lang.String
The setMaxAge() Methodpublic void setMaxAge(int value)
The setMaxAge() method sets the maximum age of the cookie. The cookie will expire after thepassed-in number of seconds. setMaxAge() returns no value and throws no exceptions.
It has one parameter:
• int
The getMaxAge() Methodpublic int getMaxAge()
The getMaxAge() method returns the maximum age of the cookie in seconds. getMaxAge() hasno parameters and throws no exceptions.
It returns this value:
• int
The setPath() Methodpublic void setPath(java.lang.String uri)
The setPath() method sets the valid path for the cookie. If the URL does not begin with thepassed-in value, it is not a valid path. setPath() returns no value and throws no exceptions.
It has one parameter:
• java.lang.String
The getPath() Methodpublic java.lang.String getPath()
The getPath() method returns the URL prefix for which this cookie is targeted. getPath()has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The setSecure() Methodpublic void setSecure(boolean flag)
The javax.servlet.http Package
APPENDIX C481
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 501: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/501.jpg)
The setSecure() method indicates to the user agent that the cookie should only be transmittedusing a secure protocol. setSecure() returns no value and throws no exceptions.
It has one parameter:
• boolean
The getSecure() Methodpublic boolean getSecure()
The getSecure() method returns true if the cookie can only be transmitted using a secureprotocol. getSecure() has no parameters and throws no exceptions.
It returns this value:
• boolean
The getName() Methodpublic java.lang.String getName()
The getName() method returns the name of the cookie. getName() has no parameters andthrows no exceptions.
It returns this value:
• java.lang.String
The setValue() Methodpublic void setValue(java.lang.String value)
The setValue() method sets the value of the cookie. setValue() returns no value and throwsno exceptions.
It has one parameter:
• java.lang.String
The getValue() Methodpublic java.lang.String getValue()
The getValue() method returns the value of the cookie. getValue() has no parameters andthrows no exceptions.
It returns this value:
• java.lang.String
Appendixes
PART IV482
![Page 502: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/502.jpg)
The getVersion() Methodpublic int getVersion()
The getVersion() method returns the version number of the cookie. A zero indicates that thecookie is based on the original specification developed by Netscape. A one indicates the cookieis based on the RFC 2109. getVersion() has no parameters and throws no exceptions.
It returns this value:
• int
The setVersion() Methodpublic void setVersion(int value)
The setVersion() method sets the cookie protocol used when the cookie saves itself.setVersion() returns no value and throws no exceptions.
It has one parameter:
• int
The clone() Methodpublic java.lang.Object clone()
The clone() method returns a copy of this object. clone() has no parameters and throws noexceptions.
It returns this value:
• java.lang.Object
The HttpServlet Classpublic class HttpServletextends javax.servlet.GenericServletimplements java.io.Serializable
The HttpServlet class is meant to simplify the writing of HTTP servlets. It extends theGenericServlet class and implements the java.io.Serializable interface. The HttpServletclass is an abstract class; therefore it cannot be instantiated directly. The HttpServlet classhas 11 methods, described in the following sections.
The HttpServlet() Methodpublic HttpServlet()
The HttpServlet() constructor is a default empty constructor. HttpServlet() has no parame-ters, returns no value, and throws no exceptions.
The javax.servlet.http Package
APPENDIX C483
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 503: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/503.jpg)
The doGet() Methodprotected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletExceptionjava.io.IOException
The doGet() method services all GET requests for the servlet.
Appendixes
PART IV484
The HttpServlet class’s doGet, doPost, doPut, doDelete, doOptions, and doTracemethods all receive the same two parameters—an HttpServletRequest object, whichencapsulates the client’s request, and an HttpServletResponse object, which containsthe response that is sent back to the client. Each of these methods throws aServletException if it cannot service the request and throws a java.io.IOExceptionif there was an I/O error. These methods return no value.
NOTE
The doPost() Methodprotected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletExceptionjava.io.IOException
The doPost() method services all POST requests for the servlet.
The doPut() Methodprotected void doPut(HttpServletRequest request,HttpServletResponse response)throws ServletExceptionjava.io.IOException
The doPut() method services all PUT requests for the servlet.
The doDelete() Methodprotected void doDelete(HttpServletRequest request,HttpServletResponse response)throws ServletExceptionjava.io.Exception
The doDelete() method services all DELETE requests for the servlet.
![Page 504: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/504.jpg)
The doOptions() Methodprotected void doOptions(HttpServletRequest request,HttpServletResponse response)throws ServletExceptionjava.io.Exception
The doOptions() method services all OPTIONS requests for the servlet. The default implemen-tation automatically determines what HTTP options are supported.
The doTrace() Methodprotected void doTrace(HttpServletRequest request,HttpServletResponse response)throws ServletExceptionjava.io.Exception
The doTrace() method services all TRACE requests for the servlet.
getLastModifiedTime() Methodprotected long getLastModifiedTime(HttpServletRequest request)
The getLastModifiedTime() method returns the last time the requested entity was modified.The value returned is measured in milliseconds since January 1, 1970.getLastModifiedTime() throws no exceptions.
It has one parameter:
• HttpServletRequest
It returns this value:
• long
The service(HttpServletRequest request, HttpServletResponseresponse) Methodprotected void service(HttpServletRequest request,HttpServletResponse response)throws ServletExceptionjava.io.Exception
This is an HTTP-specific implementation of the Servlet.service() method. It handles stan-dard HTTP requests by dispatching them to the appropriately implemented methods. The service() method throws a ServletException if it cannot service the request and throws ajava.io.IOException if there was an I/O error. service() returns no value.
The javax.servlet.http Package
APPENDIX C485
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 505: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/505.jpg)
It has two parameters:
• HttpServletRequest
• HttpServletResponse
It throws these exceptions:
• ServletException
• java.io.IOException
The service(ServletRequest request, ServletResponse response)Methodpublic void service(ServletRequest request,ServletResponse response)throws ServletExceptionjava.io.Exception
This method implements the Servlet.service() method by delegating requests to the appro-priate HTTP-specific service() method. The service() method throws a ServletExceptionif it cannot service the request and throws a java.io.IOException if there was an I/O error.service() returns no value.
It has two parameters:
• ServletRequest
• ServletResponse
It throws these exceptions:
• ServletException
• java.io.IOException
The HttpSessionBindingEvent Classpublic class HttpSessionBindingEventextends java.util.EventObject
The HttpSessionBindingEvent class is sent to all objects that implement theHttpSessionBindingListener when a listener is bound or unbound from an HttpSession.The HttpSessionBindingEvent class has three methods, described in the following sections.
The HttpSessionBindingEvent() Methodpublic HttpSessionBindingEvent(HttpSession session,java.lang.String name)
Appendixes
PART IV486
![Page 506: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/506.jpg)
The HttpSessionBindingEvent() constructor initializes the object with the session acting asthe source of the event and the name of the object being bound or unbound.HttpSessionBindingEvent() returns no value and throws no exceptions.
It has two parameters:
• HttpSession
• java.lang.String
The getName() Methodpublic java.lang.String getName()
The getName() method returns the name of the object that is being bound or unbound.getName() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getSession() Methodpublic HttpSession getSession()
The getSession() method returns the session from which the listener is being bound orunbound. getSession() has no parameters and throws no exceptions.
It returns this value:
• HttpSession
The HttpUtils Classpublic class HttpUtilsextends java.util.EventObject
The HttpUtils class contains a collection of static utility methods that are useful to HTTPservlets. The HttpUtils class has four methods, described in the following sections.
The HttpUtils() Methodpublic HttpUtils()
The HttpUtils() constructor creates an empty HttpUtility object. HttpUtils() has no para-meters, returns no value, and throws no exceptions.
The parseQueryString() Methodpublic static java.util.HashtableparseQueryString(java.lang.String s)
The javax.servlet.http Package
APPENDIX C487
C
TH
EJA
VAX.SERV
LET.HTTP
PA
CKA
GE
![Page 507: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/507.jpg)
The parseQueryString() method takes the passed-in query string and parses it into a hashtable of key/value pairs where the values are arrays of strings. parseQueryString() throws noexceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.util.Hashtable
The parsePostData() Methodpublic static java.util.HashtableparsePostData(int len,ServletInputStream in)
The parsePostData() method takes HTML from data that is sent to the server as a POSTrequest, parses it, and returns a hash table of key/value pairs. If keys have multiple values, theirvalues are stored as an array of strings. parsePostData() throws no exceptions.
It has two parameters:
• int
• ServletInputStream
It returns this value:
• java.util.Hashtable
The getRequestURL() Methodpublic static java.lang.StringBuffergetRequestURL(HttpServletRequest request)
The getRequestURL() method takes a request object and reconstructs the URL used by theclient to make the request. getRequestURL() throws no exceptions.
It has one parameter:
• HttpServletRequest
It returns this value:
• java.lang.StringBuffer
Appendixes
PART IV488
![Page 508: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/508.jpg)
APPENDIX
DThe javax.servlet.jspPackage
IN THIS APPENDIX• Interfaces 490
• Classes 492
• Exceptions 511
![Page 509: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/509.jpg)
The javax.servlet.jsp package makes up the bulk of the Java Server Pages API. It is cov-ered completely in the following sections. Figure D.1 contains the javax.servlet.jsp objectmodel.
Appendixes
PART IV490
<<Interface>>javax.servlet.Servlet
<<Interface>>JspPage
<<Interface>>HttpJspPage
java.lang.Exception
java.lang.Object
PageContextJspFactoryJspEngineInfo
JspException
JspError
java.io.Writer
JspWriter
FIGURE D.1The javax.servlet.jsp Object Model.
InterfacesThe javax.servlet.jsp package has two interfaces: HttpJspPage and JspPage.
The HttpJspPage Interfacepublic interface HttpJspPage extends JspPage
This is the interface that a JSP processor-generated class for the HTTP protocol must satisfy. Itextends JspPage and defines a single method.
The _jspService() Methodpublic void _jspService(
javax.servlet.http.HttpServletRequest request,javax.servlet.http.HttpServletResponse response)throws javax.servlet.ServletException,java.io.IOException
![Page 510: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/510.jpg)
The _jspService method corresponds to the body of the JSP page. It is defined automaticallyby the JSP processor and should never be redefined by the JSP author. It returns no value.
It has two parameters:
• HttpServletRequest
• HttpServletResponse
It throws these exceptions:
• javax.servlet.ServletException
• java.io.IOException
The JspPage Interfacepublic interface JspPage extends javax.servlet.Servlet
This is the interface that a JSP processor-generated class must implement.
This interface defines a protocol with three methods; only two of them, jspInit() andjspDestroy(), are part of this interface. The signature of the third method, _jspService(),depends on the specific protocol used and cannot be expressed in a generic way in Java.
A class implementing this interface is responsible for invoking these methods at the appropri-ate time based on the corresponding Servlet-based method invocations.
The jspInit() and jspDestroy() methods can be defined by a JSP author, but the_jspService() method is defined automatically by the JSP processor based on the contents ofthe JSP page.
The jspInit() Methodpublic void jspInit()
The jsp_init() method is invoked when the JspPage is initialized. After the JspPage is ini-tialized, the getServletConfig() method will return the desired value. jsp_init() is synony-mous with the init() method of a servlet.
It has no parameters, returns no value, and throws no exceptions.
The jspDestroy() Methodpublic void jspDestroy()
The jspDestroy() method is invoked when the JspPage is about to be destroyed. It is synony-mous with the destroy() method of a servlet.
It has no parameters, returns no value, and throws no exceptions.
The javax.servlet.jsp Package
APPENDIX D491
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 511: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/511.jpg)
ClassesThe javax.servlet.jsp package has four classes: JspEngineInfo, JspFactory, JspWriter,and PageContext.
The JspEngineInfo Classpublic abstract class JspEngineInfo
The JspEngineInfo class is an abstract class that provides information on the current JSPengine. It defines two methods.
The JspEngineInfo() Methodpublic JspEngineInfo()
The JspEngineInfo() method is an empty default constructor. It has no parameters, returns novalue, and throws no exceptions.
The getImplementationVersion() Methodpublic java.lang.String getImplementationVersion()
The getImplementationVersion() method returns the current version of the JSP specification.The version number must begin with a number. If the version is not defined, a null will bereturned. It has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The JspFactory Classpublic abstract class JspFactory extends java.lang.Object
JspFactory is an abstract class that defines a number of factory methods available to a JSPpage at runtime for the purposes of creating instances of various interfaces and classes used tosupport the JSP implementation. It has one field and six methods.
The deflt Fieldprivate static JspFactory deflt
The deflt field represents the default JSPFactory implementation.
The JspFactory() Methodpublic JspFactory()
Appendixes
PART IV492
![Page 512: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/512.jpg)
The JspFactory() method is an empty default constructor. It has no parameters, returns novalue, and throws no exceptions.
The setDefaultFactory() Methodpublic static void setDefaultFactory(JspFactory deflt)
The setDefaultFactory() method sets the default factory for this JSP implementation. It isillegal for any principal other than the JSP Engine runtime to call this method. It returns novalue and throws no exceptions.
It has one parameter:
• JspFactory
The getDefaultFactory() Methodpublic static JspFactory getDefaultFactory()
The getDefaultFactory() method returns the default factory for this JSP implementation. Ithas no parameters and throws no exceptions.
It returns this value:
• JspFactory
The getPageContext() Methodpublic abstract PageContext getPageContext(
javax.servlet.Servlet servlet,javax.servlet.ServletRequest request,javax.servlet.ServletResponse response,java.lang.String errorPageURL,boolean needsSession,int buffer,boolean autoflush)
The getPageContext() method obtains an instance of an implementation-dependentjavax.servlet.jsp.PageContext abstract class for the calling servlet and currently pendingrequest and response. This method is typically called early in the processing of the_jspService() method of a JSP implementation class to obtain a PageContext object for therequest being processed. Invoking this method results in the PageContext.initialize()method being invoked. The returned object is a properly initialized PageContext. AllPageContext objects obtained through this method must be released by invokingreleasePageContext().
The getPageContext() method throws no exceptions. It has seven parameters:
• javax.servlet.Servlet
• javax.servlet.ServletRequest
The javax.servlet.jsp Package
APPENDIX D493
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 513: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/513.jpg)
• javax.servlet.ServletResponse
• java.lang.String
• boolean
• int
• boolean
It returns this value:
• PageContext
The releasePageContext() Methodpublic void releasePageContext(PageContext pc)
The releasePageContext() method is called to release a previously allocated PageContextobject returned from a call to getPageContext(). This method should be invoked prior toreturning from the _jspService() method of a JSP implementation class. It returns no valueand throws no exceptions.
It has one parameter:
• PageContext
The getEngineInfo() Methodpublic JspEngineInfo getEngineInfo()
The getEngineInfo() method is called to get implementation-specific information on the cur-rent JSP engine. It has no parameters and throws no exceptions.
It returns this value:
• JspEngineInfo
The JspWriter Classpublic abstract class JspWriter extends java.io.Writer
JspWriter is an abstract class that emulates some functionality found in thejava.io.BufferedWriter and java.io.PrintWriter classes. However it differs in that itthrows a java.io.IOException from the print methods where PrintWriter does not. The“out” implicit variable of a JSP implementation class is of this type. It defines four fields and28 methods.
The NO_BUFFER Fieldpublic static final int NO_BUFFER
Appendixes
PART IV494
![Page 514: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/514.jpg)
This field is a constant indicating that the Writer is not buffering output.
The DEFAULT_BUFFER Fieldpublic static final int DEFAULT_BUFFER
This field is a constant indicating that the Writer is buffered and is using the implementationdefault buffer size.
The bufferSize Fieldprotected int bufferSize
This field gives the Writer buffer size.
The autoFlush Fieldprotected boolean autoFlush
This field indicates whether the buffer will be automatically flushed.
The JspWriter() Methodprotected JspWriter(int bufferSize, boolean autoFlush)
The JspWriter() method is a protected constructor. It returns no value and throws no excep-tions.
It has two parameters:
• int
• boolean
The newLine() Methodpublic void newLine() throws java.io.IOException
The newLine() method writes a line separator. The line separator string is defined by the sys-tem property line.separator, and is not guaranteed to be a single new line (\n) character.This method has no parameters and returns no value.
It throws this exception:
• java.io.IOException
The print(boolean b) Methodpublic void print(boolean b) throws java.io.IOException
The print(boolean b) method prints a boolean value. The string produced byString.valueOf(boolean) is translated into bytes according to the platform’s default charac-ter encoding, and these bytes are written in exactly the manner of the Writer.write(int)method.
The javax.servlet.jsp Package
APPENDIX D495
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 515: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/515.jpg)
It has one parameter:
• boolean
Appendixes
PART IV496
The print() method prints data type values, which are translated into bytes. For allvalues, these bytes are written in exactly the same manner as the Writer.write(int)method.
NOTE
The print(char c) Methodpublic void print(char c) throws java.io.IOException
The print(char c) method prints a char value. The character is translated into one or morebytes according to the platform’s default character encoding.
It has one parameter:
• char
The print(int i) Methodpublic void print(int i) throws java.io.IOException
The print(int i) method prints an integer. The string produced by String.valueOf(int) istranslated into bytes according to the platform’s default character encoding.
It has one parameter:
• int
The print(long l) Methodpublic void print(long l) throws java.io.IOException
The print(long l) method prints a long. The string produced by String.valueOf(long) istranslated into bytes according to the platform’s default character encoding.
The print() method’s parameter is determined by the print value. The methodalways throws a java.io.IOException exception. For all print values, the print()method returns no value.
NOTE
![Page 516: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/516.jpg)
It has one parameter:
• long
The print(float f) Methodpublic void print(float f) throws java.io.IOException
The print(float f) method prints a float. The string produced by String.valueOf(float)is translated into bytes according to the platform’s default character encoding.
It has one parameter:
• float
The print(double d) Methodpublic void print(double d) throws java.io.IOException
The print(double d) method prints a double. The string produced by String.valueOf(double) is translated into bytes according to the platform’s default characterencoding.
It has one parameter:
• double
The print(char[] s) Methodpublic void print(char[] s) throws java.io.IOException
The print(char[] s) method prints an array of characters. The characters are converted intobytes according to the platform’s default character encoding.
It has one parameter:
• char[]
The print(java.lang.String s) Methodpublic void print(java.lang.String s) throws java.io.IOException
The print(java.lang.String s) method prints a string. If the argument is null then thestring “null” is printed. Otherwise, the string’s characters are converted into bytes according tothe platform’s default character encoding.
It has one parameter:
• java.lang.String
The print(java.lang.Object obj) Methodpublic void print(java.lang.Object obj) throws java.io.IOException
The javax.servlet.jsp Package
APPENDIX D497
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 517: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/517.jpg)
The print(java.lang.Object obj) method prints an object. The string produced by theString.valueOf(Object) method is translated into bytes according to the platform’s defaultcharacter encoding.
It has one parameter:
• java.lang.Object
The println() Methodpublic void println() throws java.io.IOException
The println() method terminates the current line by writing the line separator string. The lineseparator string is defined by the system property line.separator, and is not necessarily asingle newline character (\n). This method has no parameters.
Appendixes
PART IV498
The println() method always throws a java.io.IOException exception. It returns novalue.
NOTE
The println(boolean x) Methodpublic void println(boolean x) throws java.io.IOException
The println(boolean x) method prints a boolean value and then terminates the line. Thismethod behaves as though it invokes print(boolean) and then println().
It has one parameter:
• boolean
The println(char x) Methodpublic void println(char x) throws java.io.IOException
The println(char x) method prints a character and then terminates the line. This methodbehaves as though it invokes print(char) and then println().
It has one parameter:
• char
The println(int x) Methodpublic void println(int x) throws java.io.IOException
The println(int x) method prints an integer and then terminates the line. This methodbehaves as though it invokes print(int) and then println().
![Page 518: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/518.jpg)
It has one parameter:
• int
The println(long x) Methodpublic void println(long x) throws java.io.IOException
The println(long x) method prints a long integer and then terminates the line. This methodbehaves as though it invokes print(long) and then println().
It has one parameter:
• long
The println(float x) Methodpublic void println(float x) throws java.io.IOException
The println(float x) method prints a float and then terminates the line. This methodbehaves as though it invokes print(float) and then println().
It has one parameter:
• float
The println(double x) Methodpublic void println(double x) throws java.io.IOException
The println(double x) method prints a double-precision floating-point number and then ter-minates the line. This method behaves as though it invokes print(double) and thenprintln().
It has one parameter:
• double
The println(char[] x) Methodpublic void println(char[] x) throws java.io.IOException
The println(char[] x) method prints an array of characters and then terminates the line.This method behaves as though it invokes print(char[]) and then println().
It has one parameter:
• char[]
The println(java.lang.String x) Methodpublic void println(java.lang.String x) throws java.io.IOException
The javax.servlet.jsp Package
APPENDIX D499
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 519: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/519.jpg)
The println(java.lang.String x) method prints a string and then terminates the line. Thismethod behaves as though it invokes print(String) and then println().
It has one parameter:
• java.lang.String
The println(java.lang.Object x) Methodpublic void println(java.lang.Object x) throws java.io.IOException
The println(java.lang.Object x) method prints an object and then terminates the line. Thismethod behaves as though it invokes print(Object) and then println().
It has one parameter:
• java.lang.Object
The clear() Methodpublic void clear() throws java.io.IOException
The clear() method clears the contents of the buffer. If the buffer has been already beenflushed then the clear operation throws an IOException to signal the fact that some data hasalready been irrevocably written to the client response stream. This method has no parametersand returns no value.
It throws this exception:
• java.io.IOException
The clearBuffer() Methodpublic void clearBuffer() throws java.io.IOException
The clearBuffer() method clears the current contents of the buffer. Unlike clear(), thismethod will not throw an IOException if the buffer has already been flushed. It merely clearsthe current contents of the buffer and returns. This method has no parameters and returns novalue.
It throws this exception:
• java.io.IOException
The flush() Methodpublic void flush() throws java.io.IOException
The flush() method flushes the stream. If the stream has saved any characters from the vari-ous write() methods in a buffer, they are written immediately to their intended destination.Then, if that destination is another character or byte stream, that stream is flushed. Thus one
Appendixes
PART IV500
![Page 520: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/520.jpg)
flush() invocation will flush all the buffers in a chain of Writers and OutputStreams. Thismethod has no parameters and returns no value.
It throws this exception:
• java.io.IOException
The close() Methodpublic void close() throws java.io.IOException
The close() method closes the stream, flushing it first. After a stream has been closed, furtherwrite() or flush() invocations will cause an IOException to be thrown. Closing a previouslyclosed stream, however, has no effect. This method has no parameters and returns no value.
It throws this exception:
• java.io.IOException
The getBufferSize() Methodpublic int getBufferSize() throws java.io.IOException
The getBufferSize() method returns the size of the buffer in bytes, or 0 if there is no buffer.It has no parameters.
It returns this value:
• int
It throws this exception:
• java.io.IOException
The getRemaining() Methodpublic int getRemaining() throws java.io.IOException
The getRemaining() method returns the number of bytes unused in the buffer. It has no para-meters.
It returns this value:
• int
It throws this exception:
• java.io.IOException
The isAutoFlush() Methodpublic boolean isAutoFlush()
The javax.servlet.jsp Package
APPENDIX D501
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 521: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/521.jpg)
The isAutoFlush() method returns whether auto flush is on or not. It has no parameters.
It returns this value:
• boolean
It throws this exception:
• java.io.IOException
The PageContext Classpublic abstract class PageContext extends java.lang.Object
The PageContext class is an abstract class, designed to be extended to provide implementa-tion-dependent implementations by JSP engine runtime environments. A PageContext instanceis obtained by a JSP implementation class by calling the JspFactory.getPageContext()method, and is released by calling JspFactory.releasePageContext().
The PageContext object provides a number of facilities to the page and/or component authorand page implementer. A list of some of these facilities includes
• a single API to manage the various scoped namespaces
• a number of convenience APIs to access various public objects
• a mechanism to obtain the JspWriter for output
• a mechanism to manage session usage by the page
• a mechanism to expose page directive attributes to the scripting environment
• mechanisms to forward or include the current request to other active components in theapplication
• a mechanism to handle errorpage exception processing
The PageContext class has 13 fields and 25 methods.
The APPLICATION Fieldpublic static final java.lang.String APPLICATION
This field indicates a name used to store the ServletContext in the PageContext name table.
The APPLICATION_SCOPE Fieldpublic static final int APPLICATION_SCOPE
This field indicates that a named reference remains available in the ServletContext until it isreclaimed.
Appendixes
PART IV502
![Page 522: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/522.jpg)
The CONFIG Fieldpublic static final java.lang.String CONFIG
This field indicates a name used to store the ServletConfig in the PageContext name table.
The EXCEPTION Fieldpublic static final java.lang.String EXCEPTION
This field indicates a name used to store uncaught exceptions in the ServletRequest attributelist and PageContext name table.
The OUT Fieldpublic static final java.lang.String OUT
This field indicates a name used to store the current JspWriter in the PageContext nametable.
The PAGE Fieldpublic static final java.lang.String PAGE
This field indicates a name used to store the servlet in this PageContext’s nametables.
The PAGE_SCOPE Fieldpublic static final int PAGE_SCOPE
This field indicates that a named reference remains available in this PageContext until thereturn from the current Servlet.service() invocation.
The PAGECONTEXT Fieldpublic static final java.lang.String PAGECONTEXT
This field indicates a name used to store this PageContext in it’s own name tables.
The REQUEST Fieldpublic static final java.lang.String REQUEST
This field indicates a name used to store the ServletRequest in the PageContext name table.
The REQUEST_SCOPE Fieldpublic static final int REQUEST_SCOPE
This field indicates a request scope: The named reference remains available from theServletRequest associated with the servlet until the current request is completed.
The javax.servlet.jsp Package
APPENDIX D503
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 523: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/523.jpg)
The RESPONSE Fieldpublic static final java.lang.String RESPONSE
This field indicates a name used to store the ServletResponse in the PageContext name table.
The SESSION Fieldpublic static final java.lang.String SESSION
This field indicates a name used to store the HttpSession in the PageContext name table.
The SESSION_SCOPE Fieldpublic static final int SESSION_SCOPE
This field indicates the named reference that determines the scope of the HttpSession (if any)associated with the servlet until the HttpSession is invalidated.
The PageContext() Methodpublic PageContext()
The PageContext() method is an empty default constructor. It has no parameters, returns novalue, and throws no exceptions.
The findAttribute() Methodpublic abstract java.lang.Object findAttribute(java.lang.String name)
The findAttribute() method searches for the named attribute in page, request, session, andapplication scopes in order and returns the value associated or null. It throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.Object
The forward() Methodpublic abstract void forward(java.lang.String relativeUrlPath)
throws javax.servlet.ServletException,java.io.IOException
The forward() method is used to redirect or “forward” the current ServletRequest andServletResponse to another active component in the application.
If the relativeUrlPath begins with a “/” then the URL specified is calculated relative to theDOCROOT of the ServletContext for this JSP. If the path does not begin with a “/” then theURL specified is calculated relative to the URL of the request that was mapped to the callingJSP. The forward() method returns no value.
Appendixes
PART IV504
![Page 524: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/524.jpg)
It has one parameter:
• java.lang.String
It throws these exceptions:
• javax.servlet.ServletException
• java.io.IOException
The getAttribute(java.lang.String name) Methodpublic abstract java.lang.Object getAttribute(java.lang.String name)
The getAttribute(java.lang.String name) method returns the object associated with thename in the page scope or null. It throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• java.lang.Object
The getAttribute(java.lang.String name, int scope) Methodpublic abstract java.lang.Object getAttribute(java.lang.String name,
int scope)
The getAttribute(java.lang.String name, int scope) method returns the object associ-ated with the name in the specified scope or null. It throws no exceptions.
It has two parameters:
• java.lang.String
• int
It returns this value:
• java.lang.Object
getAttributeNamesInScope() Methodpublic abstract java.util.Enumeration getAttributeNamesInScope(int scope)
The getAttributeNamesInScope() method returns an enumeration of names of all the attrib-utes in the specified scope. It throws no exceptions.
It has one parameter:
• int
The javax.servlet.jsp Package
APPENDIX D505
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 525: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/525.jpg)
It returns this value:
• java.util.Enumeration
The getAttributesScope() Methodpublic abstract int getAttributesScope(java.lang.String name)
The getAttributesScope() method returns the scope of the object associated with the namespecified or 0. It throws no exceptions.
It has one parameter:
• java.lang.String
It returns this value:
• int
The getException() Methodpublic abstract java.lang.Exception getException()
The getException() method returns any exception passed to it as an errorpage. It has noparameters and throws no exceptions.
It returns this value:
• java.lang.Exception
The getOut() Methodpublic abstract JspWriter getOut()
The getOut() method returns the current JspWriter stream being used for client response. Ithas no parameters and throws no exceptions.
It returns this value:
• javax.servlet.jsp.JspWriter
The getPage() Methodpublic abstract java.lang.Object getPage()
The getPage() method returns the page implementation class instance associated with thisPageContext. It has no parameters and throws no exceptions.
It returns this value:
• java.lang.Object
Appendixes
PART IV506
![Page 526: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/526.jpg)
The getRequest() Methodpublic abstract javax.servlet.ServletRequest getRequest()
The getRequest() method returns the ServletRequest for this PageContext. It has no para-meters and throws no exceptions.
It returns this value:
• javax.servlet.ServletRequest
The getResponse() Methodpublic abstract javax.servlet.ServletResponse getResponse()
The getResponse() method returns the ServletResponse for this PageContext. It has noparameters and throws no exceptions.
It returns this value:
• javax.servlet.ServletResponse
The getServletConfig() Methodpublic abstract javax.servlet.ServletConfig getServletConfig()
The getServletConfig() method returns the ServletConfig for this PageContext. It has noparameters and throws no exceptions.
It returns this value:
• javax.servlet.ServletConfig
The getServletContext() Methodpublic abstract javax.servlet.ServletContext getServletContext()
The getServletContext() method returns the ServletContext for this PageContext. It hasno parameters and throws no exceptions.
It returns this value:
• javax.servlet.ServletContext
The getSession() Methodpublic abstract javax.servlet.http.HttpSession getSession()
The getSession() method returns the HttpSession for this PageContext or null. It has noparameters and throws no exceptions.
The javax.servlet.jsp Package
APPENDIX D507
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 527: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/527.jpg)
It returns this value:
• javax.servlet.http.HttpSession
The handlePageException() Methodpublic abstract void handlePageException(java.lang.Exception e)
throws javax.servlet.ServletException,java.io.IOException
The handlePageException() method is intended to process an un-handled “page” level excep-tion by redirecting the exception to either the specified error page for this JSP, or if none wasspecified, to perform some implementation dependent action. This method returns no value.
It has one parameter:
• java.lang.Exception
It throws these exceptions:
• javax.servlet.ServletException
• java.io.IOException
The include() Methodpublic abstract void include(java.lang.String relativeUrlPath)
throws javax.servlet.ServletException,java.io.IOException
The include() method causes the resource specified to be processed as part of the currentServletRequest and ServletResponse being processed by the calling Thread. The output ofthe target resource’s processing of the request is written directly to the ServletResponse out-put stream.
The current JspWriter “out” for this JSP is flushed as a side-effect of this call, prior to pro-cessing the include.
It is only valid to call this method from a Thread executing within a _jspService() method ofa JSP. This method returns no value.
It has one parameter:
• java.lang.String
It throws these exceptions:
• javax.servlet.ServletException
• java.io.IOException
Appendixes
PART IV508
![Page 528: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/528.jpg)
The initialize() Methodpublic abstract void initialize(javax.servlet.Servlet servlet,
javax.servlet.ServletRequest request,javax.servlet.ServletResponse response,java.lang.String errorPageURL,boolean needsSession,int bufferSize,boolean autoFlush)throws java.io.IOException,java.lang.IllegalStateException,java.lang.IllegalArgumentException
The initialize() method is called to initialize an un-initialized PageContext so that it can beused by a JSP Implementation class to service an incoming request and response within its_jspService() method.
This method is typically called from JspFactory.getPageContext() in order to initializestate.
This method is required to create an initial JspWriter, and associate the “out” name in pagescope with this newly created object. It returns no value.
It has seven parameters:
• javax.servlet.Servlet
• javax.servlet.ServletRequest
• javax.servlet.ServletResponse
• java.lang.String
• boolean
• int
• boolean
It throws these exceptions:
• java.io.IOException
• java.lang.IllegalStateException
• java.lang.IllegalArgumentException
The popBody() Methodpublic abstract JspWriter popBody()
The popBody() method returns the previous JspWriter “out” saved by the matchingpushBody() method, and updates the value of the “out” attribute in the page scope attributenamespace of the PageConxtext. This method has no parameters and throws no exceptions.
The javax.servlet.jsp Package
APPENDIX D509
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 529: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/529.jpg)
It returns this value:
• JspWriter
The pushBody() Methodpublic abstract BodyJspWriter pushBody()
The pushBody() method returns a new BodyJspWriter object, saves the current “out”JspWriter, and updates the value of the “out” attribute in the page scope attribute namespaceof the PageContext. It has no parameters and throws no exceptions.
It returns this value:
• BodyJspWriter
The release() Methodpublic abstract void release()
The release() method “resets” the internal state of a PageContext, releasing all internal references, and preparing the PageContext for potential reuse by a later invocation of initialize(). This method is typically called from JspFactory.releasePageContext().It has no parameters, returns no value, and throws no exceptions.
The removeAttribute(java.lang.String name) Methodpublic abstract void removeAttribute(java.lang.String name)
The removeAttribute(java.lang.String name) method removes the object reference associ-ated with the specified name. It returns no value and throws no exceptions.
It has one parameter:
• java.lang.String
The removeAttribute(java.lang.String name, int scope) Methodpublic abstract void removeAttribute(java.lang.String name, int scope)
The removeAttribute(java.lang.String name, int scope) method removes the object ref-erence associated with the specified name and scope. It returns no value and throws no excep-tions.
It has two parameters:
• java.lang.String
• int
Appendixes
PART IV510
![Page 530: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/530.jpg)
The setAttribute(java.lang.String name, java.lang.Objectattribute) Methodpublic abstract void setAttribute(java.lang.String name,
java.lang.Object attribute) throws NullPointerException
The setAttribute(java.lang.String name, java.lang.Object attribute) method regis-ters the name and object specified with page scope semantics. It returns no value.
It has two parameters:
• java.lang.String
• java.lang.Object
It throws this exception:
• NullPointerException
The setAttribute(java.lang.String name, java.lang.Object o, intscope) Methodpublic abstract void setAttribute(java.lang.String name,
java.lang.Object o,int scope) throws NullPointerException, java.lang.IllegalArgumentException
The setAttribute(java.lang.String name, java.lang.Object o, int scope) methodregisters the name and object specified with appropriate scope semantics. It returns no value.
It has three parameters:
• java.lang.String
• java.lang.Object
• int
It throws these exceptions:
• NullPointerException
• java.lang.IllegalArgumentException
ExceptionsThe javax.servlet.jsp package has two exceptions: JspError and JspException. Each hastwo methods.
The JspError Exceptionpublic class JspError extends JspException
The javax.servlet.jsp Package
APPENDIX D511
D
TH
EJA
VA
X.SERV
LET.JSPP
AC
KA
GE
![Page 531: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/531.jpg)
When the JspError exception is caught, output generation should stop and the exceptionshould be forwarded to errorpage.
The JspError(java.lang.String msg) Methodpublic JspError(java.lang.String msg)
The JspError(java.lang.String msg) method is a constructor with a message. It returns novalue and throws no exceptions.
It has one parameter:
• java.lang.String
The JspError() Methodpublic JspError()
This method is a default empty constructor. It has no parameters, returns no value, and throwsno exceptions.
The JspException Exceptionpublic class JspException extends java.lang.Exception
The JspException exception is a generic exception used by the JSP engine.
The JspException(java.lang.String msg) Methodpublic JspException (java.lang.String msg)
This method is a constructor with a message. It returns no value and throws no exceptions.
It has one parameter:
• java.lang.String
The JspException() Methodpublic JspException ()
This method is a default empty constructor. It has no parameters, returns no value, and throwsno exceptions.
Appendixes
PART IV512
![Page 532: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/532.jpg)
APPENDIX
EThejavax.servlet.jsp.tagextPackage
IN THIS APPENDIX• Interfaces 514
• Classes 522
![Page 533: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/533.jpg)
Appendixes
PART IV514
The JavaServer Pages 1.1 specification provides a portable mechanism for the description oftag libraries. Figure E.1 contains the javax.servlet.jsp.tagext object model.
FIGURE E.1The javax.servlet.jsp.tagext object model.
InterfacesThe javax.servlet.jsp.tagext package has two interfaces: Tag and BodyTag.
The Tag Interfacepublic interface Tag extends java.lang.Object
Actions in a tag library are defined through subclasses of the Tag interface. The interface has13 fields and 19 methods, as described in the following sections.
The bodyOut Fieldprotected BodyJspWriter bodyOut
This field is used to hold the reference to the BodyJspWriter.
<<Interface>>Tag
java.lang.Object
TagExtraInfo
BodyTagSupport
TagAttributeInfo TagLibraryInfo
javax.servlet.jsp.JspWriter
BodyContent
TagData TagInfo VariableInfo
<<Interface>>BodyTag
TagSupport
![Page 534: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/534.jpg)
The EVAL_BODY Fieldpublic static final int EVAL_BODY
This field is used to hold the reference to the return value for doStartTag() anddoAfterBody().
The EVAL_PAGE Fieldpublic static final int EVAL_PAGE
This field is used to hold the reference to the return value for doEndTag().
The libraryPrefix Fieldprivate java.lang.String libraryPrefix
This field is used to hold the prefix for the tag library of this tag.
The pageContext Fieldprotected PageContext pageContext
This field is used to hold the reference to the current PageContext.
The parent Fieldprivate Tag parent
This field is a reference to the parent tag kept by each Tag instance, which effectively providesa runtime execution stack.
The previousOut Fieldprivate JspWriter previousOut
This field is a reference to the JspWriter and is valid when the tag is reached.
The SKIP_BODY Fieldpublic static final int SKIP_BODY
This field indicates whether the body of the action should be evaluated.
The SKIP_PAGE Fieldpublic static final int SKIP_PAGE
This field indicates whether the action should continue to evaluate the rest of the page.
The tagData Fieldprotected TagData tagData
This field contains the value information for a tag instance.
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
515
![Page 535: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/535.jpg)
The tagId Fieldprivate java.lang.String tagId
This field contains the value information for a tag ID.
The tagName Fieldprivate java.lang.String tagName
This field contains a reference to the Tag’s short name.
The values Fieldprivate java.util.Hashtable values
This field contains a reference to a Hashtable containing the Tags and their associated values.
The Tag() Methodpublic Tag(java.lang.String libraryPrefix, java.lang.String tagName)
In this default constructor, all subclasses must define a public constructor with the same signa-ture, and to call the superclass’s constructor. This constructor is called by the code generatedby the JSP translator. Tag() returns no value and throws no exceptions.
It takes two parameters:
• java.lang.String
• java.lang.String
The doAfterBody() Methodpublic int doAfterBody() throws JspError
This method is invoked after every body evaluation. doAfterBody() has no parameters.
It returns this value:
• int
It throws this exception:
• JspError
The doBeforeBody() Methodpublic int doBeforeBody() throws JspError
This method is invoked before every body evaluation. doBeforeBody() has no parameters.
It returns this value:
• int
Appendixes
PART IV516
![Page 536: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/536.jpg)
It throws this exception:
• JspError
The doEndTag() Methodpublic int doEndTag() throws JspException
This method processes the end tag. This method will be called on all Tag objects. It returns anindication of whether the rest of the page should be evaluated or skipped. doEndTag() has noparameters.
It returns this value:
• int
It throws this exception:
• JspException
The doStartTag() Methodpublic int doStartTag() throws JspException
This method processes the start tag for this instance. The doStartTag() method assumes thatinitialize() has been invoked prior to its own execution. When this method is invoked, thebody has not yet been invoked. doStartTag() has no parameters.
It returns this value:
• int
It throws this exception:
• JspException
The findAncestorWithClass() Methodpublic static final Tag findAncestorWithClass(Tag from,
java.lang.Class class)
This method finds the instance of a given class type that is closest to a given instance. Thismethod is used for coordination among cooperating tags. findAncestorWithClass() throwsno exceptions.
It takes two parameters:
• Tag
• java.lang.Class
It returns this value:
• Tag
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
517
![Page 537: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/537.jpg)
The getBodyOut() Methodprotected final BodyJspWriter getBodyOut()
This method returns the value of the current “out” JspWriter. getBodyOut() has no parame-ters and throws no exceptions.
It returns this value:
• BodyJspWriter
The getLibraryPrefix() Methodpublic java.lang.String getLibraryPrefix()
This method returns the library prefix being used with this tag. getLibraryPrefix() has noparameters and throws no exceptions.
It returns this value:
• java.lang.String
The getPageContext() Methodpublic PageContext getPageContext()
This method returns the PageContext for this tag. getPageContext() has no parameters andthrows no exceptions.
It returns this value:
• PageContext
The getParent() Methodpublic Tag getParent()
This method returns the parent extension tag instance or null. getParent() has no parametersand throws no exceptions.
It returns this value:
• Tag
The getPreviousOut() Methodprotected final JspWriter getPreviousOut()
This method returns the value of the “out” JspWriter prior to pushing a BodyJspWriter.getPreviousOut() has no parameters and throws no exceptions.
It returns this value:
• JspWriter
Appendixes
PART IV518
![Page 538: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/538.jpg)
The getTagData() Methodpublic TagData getTagData()
This method returns the immutable TagData for this tag. getTagData() has no parameters andthrows no exceptions.
It returns this value:
• TagData
The getTagId() Methodpublic java.lang.String getTagId()
This method returns the value of the Tag Id or null. getTagId() has no parameters and throwsno exceptions.
It returns this value:
• java.lang.String
The getTagName() Methodpublic java.lang.String getTagName()
This method returns the short name for the Tag. getTagName() has no parameters and throwsno exceptions.
It returns this value:
• java.lang.String
The getValue() Methodpublic java.lang.Object getValue(java.lang.String key)
This method returns the value associated with the tag. getValue() throws no exceptions.
It takes one parameter:
• java.lang.String
It returns this value:
• java.lang.Object
The initialize() Methodpublic void initialize(Tag parent,
TagData tagData,PageContext pc)
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
519
![Page 539: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/539.jpg)
This method initializes a Tag instance so it can be used or reused. A newly created Tag instancemust be prepared by invoking this method before invoking doStartTag(). A Tag instance thathas been used and released by invoking release() must be reinitialized by invoking thismethod. initialize() returns no value and throws no exceptions.
It takes three parameters:
• Tag
• TagData
• PageContext
The release() Methodpublic void release()
This method releases a Tag instance so it can be used or reused. release() has no parameters,returns no value, and throws no exceptions.
The setBodyOut() Methodpublic void setBodyOut(BodyJspWriter b)
This method sets the BodyJspWriter. It will be invoked once per action invocation at most. Itwill not be invoked if there is no body evaluation. setBodyOut() returns no value and throwsno exceptions.
It takes one parameter:
• BodyJspWriter
The setValue() Methodpublic void setValue(java.lang.String key,
java.lang.Object value)
This method sets a user-defined value on the Tag. setValue() returns no value and throws noexceptions.
It takes two parameters:
• java.lang.String
• java.lang.Object
The BodyTag Interfacepublic interface BodyTag extends Tag
The BodyTag interface extends Tag by defining additional methods that let a Tag handler accessits body.
Appendixes
PART IV520
![Page 540: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/540.jpg)
The interface provides one field and three new methods. The first is to be invoked with theBodyContent for the evaluation of the body; the second is to be reevaluated after every bodyevaluation.
The EVAL_BODY_TAG Fieldpublic static final int EVAL_BODY_TAG
This field requests the creation of new BodyContent on which to evaluate the body of this tag.It is returned from doStartTag and doAfterBody. This is an illegal return value fordoStartTag when the class does not implement BodyTag, because BodyTag is needed to manip-ulate the new Writer.
The setBodyContent() Methodpublic void setBodyContent(BodyContent b)
This method is used by the JSP engine to set the body content of the tag. It returns no valueand throws no exceptions.
It takes one parameter:
• BodyContent
The doInitBody() Methodpublic void doInitBody() throws JspException
The method will be invoked once per action invocation by the page implementation. It’sinvoked after a new BodyContent has been obtained and set on the tag handler through thesetBodyContent() method and before the evaluation of the tag’s body into that BodyContent.It has no parameters and returns no value.
It throws this exception:
• JspException
The doAfterBody() Methodpublic int doAfterBody() throws JspException
The doAfterBody() method is executed after some body has been evaluated. It is not invokedin empty tags or in tags returning SKIP_BODY in doStartTag(). It has no parameters andreturns no value.
It throws this exception:
• JspException
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
521
![Page 541: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/541.jpg)
ClassesThe nine classes defined to develop JavaServer Pages tag libraries are described in the follow-ing sections.
The BodyContent Classpublic abstract class BodyContent extends JspWriter
BodyContent is a JspWriter subclass that can be used to process body evaluations so they canbe re-extracted at a later time. It has five methods.
The BodyContent() Methodprotected BodyContent(JspWriter writer)
This method is used to construct a BodyJspWriter. It should only be used by a subclass.BodyJspWriter() returns no values and throws no exceptions.
It takes one parameter:
• JspWriter
The clearBody() Methodpublic void clearBody()
The clearBody() method is another implementation of the JspWriter method clear(). Theonly difference is that clearBody() is guaranteed not to throw an exception. clearBody() hasno parameters, returns no value, and throws no exceptions.
The getReader() Methodpublic abstract java.io.Reader getReader()
The getReader() method returns the value of this BodyJspWriter as a Reader, after theBodyJspWriter has been processed. getReader() has no parameters and throws no exceptions.
It returns this value:
• java.io.Reader
The getString() Methodpublic abstract java.lang.String getString()
The getString() method returns the value of this BodyJspWriter as a string after theBodyJspWriter has been processed. It has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
Appendixes
PART IV522
![Page 542: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/542.jpg)
The writeOut() Methodpublic abstract void writeOut(java.io.Writer out)
The writeOut() method writes the contents of the BodyJspWriter into a writer. It returns novalue and throws no exceptions.
It takes one parameter:
• java.io.Writer
The BodyTagSupport Classpublic class BodyTagSupport extends TagSupport implements BodyTag
The BodyTagSupport class acts as a helper class for custom tags that process body content. Itprovides default implementations for all the methods defined by the BodyTag interface. It hasnine methods.
The BodyTagSupport() Methodpublic BodyTagSupport()
This method is the default constructor. BodyTagSupport() takes no parameters, returns novalue, and throws no exceptions.
The doAfterBody() Methodpublic int doAfterBody() throws JspException
This is the default implementation for the doAfterBody() method defined by the BodyTaginterface. The doAfterBody() method takes no parameters.
It returns this value:
• int
It throws this exception:
• JspException
The doEndTag() Methodpublic int doEndTag() throws JspException
This is the default implementation for the doEndTag() method defined by the BodyTag inter-face. The doEndTag() method takes no parameters.
It returns this value:
• int
It throws this exception:
• JspException
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
523
![Page 543: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/543.jpg)
The doInitBody() Methodpublic void doInitBody() throws JspException
This is the default implementation for the doInitBody() method defined by the BodyTag inter-face. The doInitBody() method takes no parameters and returns no value.
It throws this exception:
• JspException
The doStartTag() Methodpublic int doStartTag() throws JspException
This is the default implementation for the doStartTag() method defined by the BodyTag inter-face. The doStartTag() method takes no parameters.
It returns this value:
• int
It throws this exception:
• JspException
getBodyContent() Methodpublic BodyContent getBodyContent()
This is the default implementation for the getBodyContent() method defined by the BodyTaginterface. The getBodyContent() method takes no parameters and throws no exceptions.
It returns this value:
• BodyContent
The getPreviousOut() Methodpublic JspWriter getPreviousOut()
This is the default implementation for the getPreviousOut() method defined by the BodyTaginterface. The getPreviousOut() method takes no parameters and throws no exceptions.
It returns this value:
• JspWriter
The release() Methodpublic void release()
This is the default implementation for the release() method defined by the BodyTag interface.The release() method takes no parameters, returns no value, and throws no exceptions.
Appendixes
PART IV524
![Page 544: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/544.jpg)
setBodyContent() Methodpublic void setBodyContent(BodyContent b)
This is the default implementation for the setBodyContent() method defined by the BodyTaginterface. The setBodyContent() method returns no values and throws no exceptions.
It takes two parameters:
• BodyContent
The TagSupport Classpublic class TagSupport implements Tag
The TagSupport class acts as a helper class for custom tags that do not process body content.This class has 2 fields and 14 methods. It provides default implementations for all the methodsdefined by the Tag interface.
The id Fieldprotected java.lang.String id
This field is used to hold the id attribute for the defined tag.
The pageContext Fieldprotected PageContext pageContext
This field is used to hold the reference to the tag PageContext object.
The TagSupport() Methodpublic TagSupport()
This is he default constructor. TagSupport() takes no parameters, returns no value, and throwsno exceptions.
The doEndTag() Methodpublic int doEndTag() throws JspException
This is the default implementation for the doEndTag() method defined by the Tag interface.The doEndTag() method takes no parameters.
It returns this value:
• int
It throws this exception:
• JspException
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
525
![Page 545: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/545.jpg)
The doStartTag() Methodpublic int doStartTag() throws JspException
This is the default implementation for the doStartTag() method defined by the Tag interface.The doStartTag() method takes no parameters.
It returns this value:
• int
It throws this exception:
• JspException
The findAncestorWithClass() Methodpublic static final Tag findAncestorWithClass(Tag from, java.lang.Class klass)
The findAncestorWithClass() method finds the instance of a given class type that is closestto a given instance. This class is used for coordination among cooperating tags. This methodthrows no exceptions.
It takes two parameters:
• Tag
• java.lang.Class
It returns this value:
• Tag
The getId() Methodpublic java.lang.String getId()
The getId() method returns the value of the id attribute of this tag, or null. This method takesno parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getParent() Methodpublic Tag getParent()
The getParent() method returns the Tag instance enclosing this tag instance. This methodtakes no parameters and throws no exceptions.
It returns this value:
• Tag
Appendixes
PART IV526
![Page 546: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/546.jpg)
The getValue() Methodpublic java.lang.Object getValue(java.lang.String k)
The getValue() method returns the value associated with the named attribute. It throws noexceptions.
It takes one parameter:
• java.lang.String
It returns this value:
• java.lang.Object
The getValues() Methodpublic java.util.Enumeration getValues()
The getValues() method returns all the attribute values in an Enumeration. It takes no para-meters and throws no exceptions.
It returns this value:
• java.util.Enumeration
The release() Methodpublic void release()
This is the default implementation for the release() method defined by the Tag interface. Therelease() method takes no parameters, returns no value, and throws no exceptions.
The removeValue() Methodpublic void removeValue(java.lang.String k)
The removeValue() method removes the value associated with named attribute. It throws noexceptions and returns no value.
It takes one parameter:
• java.lang.String
The setId() Methodpublic void setId(java.lang.String id)
The setId() method is the basic accessor for setting the tag’s id attribute. It throws no excep-tions and returns no value.
It takes one parameter:
• java.lang.String
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
527
![Page 547: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/547.jpg)
The setPageContext() Methodpublic void setPageContext(PageContext pageContext)
The setPageContext() method is the basic accessor for setting the tag’s PageContext. Itthrows no exceptions and returns no value.
It takes one parameter:
• PageContext
The setParent() Methodpublic void setParent(Tag t)
The setParent() method is the basic accessor for setting the tag’s parent. It throws no excep-tions and returns no value.
It takes one parameter:
• Tag
The setValue() Methodpublic void setValue(java.lang.String k, java.lang.Object o)
The setValue() method is the basic accessor for setting a tag’s named attribute. It throws noexceptions and returns no value.
It takes two parameters:
• java.lang.String
• java.lang.Object
The TagAttributeInfo Classpublic class TagAttributeInfo extends java.lang.Object
This class encapsulates information on Tag attributes. It is instantiated from the Tag LibraryDescriptor (TLD) file. The TagAttributeInfo class has three fields and four methods,described in the following sections.
The ID Fieldpublic static final java.lang.String ID
This field holds a reference to the tag’s ID.
The name Fieldprivate java.lang.String name
This field holds a reference to the tag’s short name.
Appendixes
PART IV528
![Page 548: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/548.jpg)
The reqTime Fieldprivate boolean reqTime
This field holds a reference to the tag’s request time.
The setValue() MethodsetValue(java.lang.String name,
java.lang.String type,boolean reqTime)
This method is the constructor for TagAttributeInfo. There is no public constructor. Thisclass is to be instantiated only from the tag library code under request from some JSP code thatis parsing a TLD. setValue() returns no value and throws no exceptions.
It takes three parameters:
• java.lang.String
• java.lang.String
• boolean
The getIdAttribute() Methodpublic static TagAttributeInfo getIdAttribute(TagAttributeInfo[] a)
This method is a convenient method that goes through an array of TagAttributeInfo objectsand looks for “id”. getIdAttribute() throws no exceptions.
It takes one parameter:
• TagAttributeInfo[]
It returns this value:
• TagAttributeInfo
The getName() Methodpublic java.lang.String getName()
This method returns the name of the attribute for the Tag. getName() has no parameters andthrows no exceptions.
It returns this value:
• java.lang.String
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
529
![Page 549: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/549.jpg)
The getTypeName() Methodpublic java.lang.String getTypeName()
This method returns the type of the attribute for the Tag. getTypeName() has no parameters andthrows no exceptions.
It returns this value:
• java.lang.String
The TagData Classpublic class TagData extends java.lang.Object
implements java.lang.Cloneable
This class encapsulates Tag instance attributes and values. Often, this data is fully static in thecase where none of the attributes have runtime expressions as their values. Thus the TagDataclass is intended to expose an immutable interface to a set of immutable attribute/value pairs.This class implements Cloneable, so that implementations can create a static instance and thenjust clone it before adding the request-time expressions. The TagData class has two fields andfive methods, described in the following sections.
The attributes Fieldprivate java.util.Hashtable attributes
This field holds a reference to a Hashtable of the tag’s attributes.
The REQUEST_TIME_VALUE Fieldpublic static final java.lang.Object REQUEST_TIME_VALUE
This field holds a reference to a distinguished value for an attribute. The value is a request-timeexpression, which is not yet available because this TagData instance is being used at translation-time.
The TagData() Methodpublic TagData(java.lang.Object[][] atts)
This method is the constructor for a TagData object. It takes a single parameter, a two-dimensional array of static attributes and values. TagData() returns no value and throws noexceptions.
It takes one parameter:
• java.lang.Object[][]
Appendixes
PART IV530
![Page 550: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/550.jpg)
The getAttribute() Methodpublic java.lang.Object getAttribute(java.lang.String name)
This method returns the passed-in name’s value. getAttribute() throws no exceptions.
It takes one parameter:
• java.lang.String
It returns this value:
• java.lang.Object
The getAttributeString() Methodpublic java.lang.String getAttributeString(java.lang.String name)
This method returns the value of an attribute as a java.lang.String. getAttributeString()throws no exceptions.
It takes one parameter:
• java.lang.String
It returns this value:
• java.lang.String
Th getId() Methodpublic java.lang.String getId()
This method returns the value of the id attribute or null. getID() has no parameters andthrows no exceptions.
It returns this value:
• java.lang.String
The setAttribute() Methodpublic void setAttribute(java.lang.String name,
java.lang.Object value)
This method sets the value of an attribute/value pair. setAttribute() returns no value andthrows no exceptions.
It takes two parameters:
• java.lang.String
• java.lang.Object
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
531
![Page 551: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/551.jpg)
The TagExtraInfo Classpublic abstract class TagExtraInfo extends java.lang.Object
This class provides extra tag information for a custom tag. It is mentioned in the TLD. Thisclass must be used if the tag defines any scripting variables, or if the tag wants to providetranslation-time validation of the tag attributes. The TagExtraInfo class has one field and fivemethods, described in the following sections.
The tagInfo Fieldprotected TagInfo tagInfo
This field holds a reference to the TagInfo object.
The TagExtraInfo() Methodpublic TagExtraInfo()
This method is the default empty constructor for the TagExtraInfo class. TagExtraInfo() hasno parameters, returns no value, and throws no exceptions.
The getTagInfo() Methodpublic TagInfo getTagInfo()
This method returns the TagInfo object for this class. getTagInfo() has no parameters andthrows no exceptions.
It returns this value:
• TagInfo
The getVariableInfo() Methodpublic VariableInfo[] getVariableInfo(TagData data)
This method returns information on scripting variables defined by this tag. getVariableInfo()throws no exceptions.
It takes one parameter:
• TagData
It returns this value:
• VariableInfo[]
Appendixes
PART IV532
![Page 552: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/552.jpg)
The isValid() Methodpublic boolean isValid(TagData data)
This method performs translation-time validation of the TagData attributes, returning aboolean value indicating validity. isValid() throws no exceptions.
It takes one parameter:
• TagData
It returns this value:
• boolean
The setTagInfo() Methodpublic void setTagInfo(TagInfo info)
This method sets the TagInfo object for this class. setTagInfo() returns no value and throwsno exceptions.
It takes one parameter:
• TagInfo
The TagInfo Classpublic abstract class TagInfo extends java.lang.Object
This class provides Tag information for a tag in a tag library. It is instantiated from the TLD.The TagInfo class has nine fields and eleven methods, described in the following sections.
The attributeInfo Fieldprivate TagAttributeInfo[] attributeInfo
This field holds a reference to an array of TagAttributeInfo objects.
The BODY_CONTENT_JSP Fieldpublic static final java.lang.String BODY_CONTENT_JSP
This field holds a reference to a static constant for getBodyContent(), when it is a JSP.
The BODY_CONTENT_TAG_DEPENDENT Fieldpublic static final java.lang.String BODY_CONTENT_TAG_DEPENDENT
This field holds a reference to a static constant for getBodyContent(), when it is Tag depen-dent.
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
533
![Page 553: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/553.jpg)
The bodyContent Fieldprivate java.lang.String bodyContent
This field holds a reference to a java.lang.String containing information on the body con-tent of these tags.
The infoString Fieldprivate java.lang.String infoString
This field holds a reference to a java.lang.String containing the optional string informationfor this tag.
The tagClassName Fieldprivate java.lang.String tagClassName
This field holds a reference to a java.lang.String containing the name of the tag handlerclass.
The tagExtraInfo Fieldprivate TagExtraInfo tagExtraInfo
This field holds a reference to an instance providing extra tag info.
The tagLibrary Fieldprivate TagLibraryInfo tagLibrary
This field holds a reference to an instance of the tag library that contains this tag.
The tagName Fieldprivate java.lang.String tagName
This field holds a reference to a java.lang.String containing the name of this tag.
The TagInfo() Methodpublic TagInfo(java.lang.String tagName,
java.lang.String tagClassName,java.lang.String bodycontent,java.lang.String infoString,TagLibraryInfo tagLib,TagExtraInfo tagExtraInfo,TagAttributeInfo[] attribInfo)
This method is the constructor for TagInfo. There is no public constructor. This class is to beinstantiated only from the tag library code under request from some JSP code that is parsing aTLD. TagInfo() returns no value and throws no exceptions.
Appendixes
PART IV534
![Page 554: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/554.jpg)
It takes seven parameters:
• java.lang.String
• java.lang.String
• java.lang.String
• java.lang.String
• TagLibraryInfo
• TagExtraInfo
• TagAttributeInfo[]
The getAttributes() Methodpublic TagAttributeInfo[] getAttributes()
This method returns a reference to an array of TagAttributeInfo objects. If a null is returned,then there is no attribute information. getAttributes() has no parameters and throws noexceptions.
It returns this value:
• TagAttributeInfo[]
The getBodyContent() Methodpublic java.lang.String getBodyContent()
This method returns a reference to a java.lang.String containing information on the bodycontent of these tags. getBodyContent() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getInfoString() Methodpublic java.lang.String getInfoString()
This method returns a reference to a java.lang.String containing the optional string informa-tion for this tag. getInfoString() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
535
![Page 555: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/555.jpg)
The getTagClassName() Methodpublic java.lang.String getTagClassName()
This method returns a reference to a java.lang.String containing the name of the tag handlerclass. getTagClassName() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getTagExtraInfo() Methodpublic TagExtraInfo getTagExtraInfo()
This method returns a reference the TagExtraInfo object. getTagExtraInfo() has no parame-ters and throws no exceptions.
It returns this value:
• TagExtraInfo
The getTagLibrary() Methodpublic TagLibraryInfo getTagLibrary()
This method returns a reference the TagLibraryInfo object. getTagLibrary() has no parame-ters and throws no exceptions.
It returns this value:
• TagLibraryInfo
The getTagName() Methodpublic java.lang.String getTagName()
This method returns a reference to a java.lang.String containing the name of this tag.getTagName() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getVariableInfo() Methodpublic VariableInfo[] getVariableInfo(TagData data)
This method returns information on the object created by this tag at runtime. If null is returned,then no such object was created. The default is null if the tag has no id attribute.getVariableInfo() throws no exceptions.
Appendixes
PART IV536
![Page 556: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/556.jpg)
It takes one parameter:
• TagData
It returns this value:
• VariableInfo[]
The isValid() Methodpublic boolean isValid(TagData data)
This method performs translation-time validation of the TagData attributes. isValid() throwsno exceptions.
It takes one parameter:
• TagData
It returns this value:
• boolean
The TagLibraryInfo Classpublic abstract class TagLibraryInfo extends java.lang.Object
The TagLibraryInfo class provides information on the tag library. It is instantiated from theTLD. The TagLibraryInfo class has three fields and nine methods.
The prefix Fieldprivate java.lang.String prefix
This field holds a reference to the prefix actually used by the taglib directive.
The tldis Fieldprotected java.io.InputStream tldis
This field holds a reference to the input stream to the TLD.
The uri Fieldprivate java.net.URL uri
This field holds a reference to the URI actually used by the taglib directive.
The TagLibraryInfo() Methodpublic TagLibraryInfo(java.lang.String prefix,
java.net.URL uri,java.io.InputStream tldis)
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
537
![Page 557: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/557.jpg)
This method is the constructor for the TagLibraryInfo class. It will invoke the constructors forTagInfo and TagAttributeInfo after parsing the TLD file. TagLibraryInfo() returns novalue and throws no exceptions.
It takes three parameters:
• java.lang.String
• java.net.URL
• java.io.InputStream
The getInfoString() Methodpublic java.lang.String getInfoString()
This method returns the information string for this tag library. getInfoString() has no para-meters and throws no exceptions.
It returns this value:
• java.lang.String
The getPrefixString() Methodpublic java.lang.String getPrefixString()
This method returns the prefix assigned to this tag library from the taglib directive.getPrefixString() has no parameters and throws no exceptions.
It returns this value:
• java.lang.String
The getReliableURN() Methodpublic java.lang.String getReliableURN()
This method returns a reliable URN to a TLD. getReliableURN() has no parameters andthrows no exceptions.
It returns this value:
• java.lang.String
The getRequiredVersion() Methodpublic java.lang.String getRequiredVersion()
This method returns the required version for the taglib. getRequiredVersion() has no para-meters and throws no exceptions.
It returns this value:
• java.lang.String
Appendixes
PART IV538
![Page 558: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/558.jpg)
The getShortName() Methodpublic java.lang.String getShortName()
This method returns the preferred short name for the taglib. getShortName() has no parame-ters and throws no exceptions.
It returns this value:
• java.lang.String
The getTag() Methodpublic TagInfo getTag(java.lang.String name)
This method returns the TagInfo for a given tag short name. getTag() throws no exceptions.
It takes one parameter:
• java.lang.String
It returns this value:
• TagInfo
The getTags() Methodpublic TagInfo[] getTags()
This method returns an array of TagInfo objects for the tags defined in this tag library.getTags() has no parameters and throws no exceptions.
It returns this value:
• TagInfo[]
The getURI() Methodpublic java.net.URL getURI()
This method returns the URI from the “<%@” taglib directive for this library. getURI() hasno parameters and throws no exceptions.
It returns this value:
• java.net.URL
The VariableInfo Classpublic class VariableInfo extends java.lang.Object
The VariableInfo class provides information on the scripting variables that are created andmodified by a tag at runtime. This information is provided by TagExtraInfo classes and it isused by the translation phase of JSP. The VariableInfo class has seven fields and five meth-ods, described in the following sections.
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
539
![Page 559: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/559.jpg)
The AT_BEGIN Fieldpublic static final int AT_BEGIN
This field states that the visibility of a variable begins after the start tag.
The AT_END Fieldpublic static final int AT_END
This field states that the visibility of a variable begins after the end tag.
The className Fieldprivate java.lang.String className
This field holds a reference to the name of the scripting variable.
The declare Fieldprivate boolean declare
This field determines if the variable is a new variable.
The NESTED Fieldpublic static final int NESTED
This field states that the visibility of a variable is between the start and end tags.
The scope Fieldprivate int scope
This field indicates the lexical scope of the variable.
The varName Fieldprivate java.lang.String varName
This field represents the name of the scripting variable.
The VariableInfo() Methodpublic VariableInfo(java.lang.String varName,
java.lang.String className,boolean declare,int scope)
This method is the VariableInfo constructor. These objects can be created at translation timeby the TagExtraInfo instances. VariableInfo() returns no value and throws no exceptions.
It takes four parameters:
• java.lang.String
• java.lang.String
Appendixes
PART IV540
![Page 560: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/560.jpg)
• boolean
• int
The getClassName() Methodpublic java.lang.String getClassName()
This method returns the classname of the scripting class. getClassName() has no parametersand throws no exceptions.
It returns this value:
• java.lang.String
The getDeclare() Methodpublic boolean getDeclare()
This method returns a boolean that indicates whether the variable is a new variable.getDeclare() has no parameters and throws no exceptions.
It returns this value:
• boolean
The getScope() Methodpublic int getScope()
This method returns an integer indicating the lexical scope of the variable. getScope() has noparameters and throws no exceptions.
It returns this value:
• int
The getVarName() Methodpublic java.lang.String getVarName()
This method returns the classname of the scripting variable. getVarName() has no parametersand throws no exceptions.
It returns this value:
• java.lang.String
The javax.servlet.jsp.tagext Package
APPENDIX E
E
TH
EJA
VAX.
SERVLET.JSP.TA
GEX
TP
AC
KA
GE
541
![Page 561: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/561.jpg)
![Page 562: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/562.jpg)
APPENDIX
FWML (The Wireless MarkupLanguage)by Bryan Morgan
IN THIS APPENDIX• WML Elements 544
![Page 563: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/563.jpg)
Appendixes
PART IV544
This appendix is a reference to the elements and tags used by Wireless Markup Language(WML). An online version of this WML tag reference (also written by Bryan Morgan) is avail-able from Wireless Developer Network athttp://www.wirelessdevnet.com/channels/refview.phtml?cat=wmltags.
WML ElementsWML uses 36 elements. These elements are described in Table F.1.
TABLE F.1 WML Elements
Element Name Tag Description
A <a> A short form for the <anchor> element. It is recom-mended to use the <a> tag as opposed to the <anchor>tag.
Access <access> Controls access level for the deck (local access only ifaccess control is enabled).
Anchor <anchor> Used to define an anchor, similar to HTML’s <a>element.
Big <big> Causes text to be displayed with a large font.
Bold <b> Used to display text with a bold font.
Break <br> Inserts a new line.
Card <card> Defines a single “Card” in a deck.
Do <do> Used to map an action to a user interface element.
Emphasis <em> Used to display text with emphasis.
Fieldset <fieldset> Allows grouping of related fields and text.
Go <go> Defines an action task used to specify navigation to aURL.
Head <head> Contains information relating to the deck as a whole,including metadata and access control elements.
Italic <i> Renders text with an italic font.
Image <img> Used to display a WBMP image.
Input <input> Specifies a text entry object.
Meta <meta> Contains generic metainformation for the deck.
Noop <noop> “No Operation.” Specifies that nothing should be done.
OnEvent <onevent> Used to create an event handler for the enclosing element.
![Page 564: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/564.jpg)
Option <option> Defines an option input field.
OptionGroup <optgroup> Defines a group of option elements into a hierarchy.
Paragraph <p> Defines a section of text as a paragraph.
Postfield <postfield> Specifies a field name and value to be used in the con-struction of a URL request.
Pre <pre> Signals that text within this tag should be treated aspreformatted text.
Prev <prev> An action task used to force navigation to the previousURL in the stack.
Refresh <refresh> Forces an update of the user agent context.
Select <select> Creates a list of options.
SetVar <setvar> Specifies the variable to set in the user agent after exe-cuting a task.
Small <small> Renders the text in a small font.
Strong <strong> Renders the text with a strong font.
Table <table> Used to format content in a tabular set of rows andcolumns.
TD <td> Defines a cell element of a table.
Template <template> Declares a template for cards in the deck.
Timer <timer> Used to create a card timer, keeping count in tenths of asecond.
TR <tr> Defines a row in a table element.
Underline <u> Used to add an underline effect to text.
WML <wml> Used to define a WML deck and serve as the root forall cards within that deck.
WML (The Wireless Markup Language)
APPENDIX F
F
WM
L (TH
EW
IRELESSM
ARK
UP
LA
NG
UA
GE)
545
TABLE F.1 WML Elements
Element Name Tag Description
![Page 565: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/565.jpg)
![Page 566: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/566.jpg)
APPENDIX
GWMLScriptby Bryan Morgan
IN THIS APPENDIX• Lang Library 548
• Float Library 550
• String Library 551
• URL Library 553
• WMLBrowser Library 556
• Dialogs Library 557
![Page 567: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/567.jpg)
Appendixes
PART IV548
This appendix is a reference to the libraries and functions used by WMLScript. An online ver-sion of this standard library reference (also written by Bryan Morgan) is available fromWireless Developer Network athttp://www.wirelessdevnet.com/channels/coderef.phtml?catid=5.
Lang LibraryThe Lang library contains a set of functions that are closely related to the WMLScript languagecore.
abort()—The abort Functionabort(errorDescription)
Aborts the execution of the current WMLScript bytecode and returns the errorDescriptionvalue back to the caller of the WMLScript interpreter.
abs()—The abs Functionabs(value)
Returns the absolute value of the given number. If the number is a floating-point number, thefunction returns a floating-point value.
characterSet()—The characterSet FunctioncharacterSet()
Returns the character set supported by the WMLScript Interpreter. The possible values returnedcorrespond to values defined by Internet Assigned Numbers Authority (IANA); see documenta-tion at http://www.wapforum.org on Wireless Session Protocol for more information.
exit()—The exit Functionexit(value)
Forces a normal execution of a WMLScript function and returns control back to the caller.
float()—The float Functionfloat()
Returns a boolean value indicating whether floating-point values are supported on this device.
![Page 568: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/568.jpg)
isFloat()—The isFloat FunctionisFloat(value)
Returns a boolean value indicating whether the value is a floating-point number.
isInt()—The isInt FunctionisInt(value)
Returns a boolean value indicating whether the value is an integer number.
max()—The max Functionmax(value1, value2)
Compares two values and returns the maximum value.
maxInt()—The maxInt FunctionmaxInt()
Returns the maximum integer value supported by the operating platform.
min()—The min Functionmin(value1, value2)
Compares two values and returns the minimum value.
minInt()—The minInt FunctionminInt();
Returns the minimum integer value supported by the operating platform.
parseFloat()—The parseFloat FunctionparseFloat(value)
Converts the designated string value into a floating-point value.
parseInt()—The parseInt FunctionparseInt(value)
Converts the designated string value into an integer value.
WMLScript
APPENDIX G
G
WM
LSC
RIPT
549
![Page 569: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/569.jpg)
random()—The random Functionrandom(value)
Returns a random integer value between 0 and the designated value.
seed()—The seed Functionseed(value)
Initializes the random number generator sequence with a seed value.
Float LibraryThe Float library contains a set of typical arithmetic floating-point functions that are fre-quently used by applications. The Float library is optional and is only supported on thoseclients with floating-point capabilities.
ceil()—The ceil Functionceil(value)
Analyzes the designated value and returns the smallest integer value that is greater than orequal to the designated value.
floor()—The floor Functionfloor(value)
Analyzes the designated value and returns the greatest integer value that is less than or equalto the designated value.
int()—The int Functionint(value)
Returns the integer value of a designated value.
maxFloat()—The maxFloat FunctionmaxFloat()
Returns the maximum floating-point value supported by [IEEEE754] single-precision, floating-point format.
Appendixes
PART IV550
![Page 570: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/570.jpg)
minFloat()—The minFloat FunctionminFloat()
Returns the smallest nonzero floating-point value supported by [IEEEE754] single precision,floating-point format.
pow()—The pow Functionpow(value1, value2)
Raises value1 to the value2 power.
round()—The round functionround(value)
Rounds the designated value to the nearest integer.
sqrt()—The sqrt Functionsqrt(value)
Returns the square root of the designated value.
String LibraryThe String library contains a set of functions for performing string operations.
charAt()—The charAt FunctioncharAt(string, index)
Retrieves the character at the index from a specified string.
compare()—The compare Functioncompare(string1, string2)
Returns 0 if string1 equals string2; -1 if string1 is less than string2; and 1 if string1 isgreater than string2.
elementAt()—The elementAt FunctionelementAt(string, n, separator)
Analyzes a string for separator values and returns the nth element after the designated separator value.
WMLScript
APPENDIX G
G
WM
LSC
RIPT
551
![Page 571: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/571.jpg)
elements()—The elements Functionelements(string, separator)
Determines the number of separator values in a given string.
find()—The find Functionfind(string, substring)
Searches a string for the existence of a substring. Returns the index of the first character ifthe substring is found. Returns -1 if substring is not found.
format()—The format Functionformat(format, value)
Performs formatting on a string using a subset of the C language string formatting syntax.
insertAt()—The insertAt FunctioninsertAt(string, element, index, separator)
Inserts an element into an existing string at the specified index.
isEmpty()—The isEmpty FunctionisEmpty(string)
Tests to determine whether a string is of length zero. Returns a boolean true/false based on theresult of this test.
length()—The length Functionlength(string)
Returns the length of the designated string.
removeAt()—The removeAt FunctionremoveAt(string, index, separator)
Removes a string (and separator, if existing) at the indicated index.
Appendixes
PART IV552
![Page 572: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/572.jpg)
replace()—The replace Functionreplace(string, oldSubString, newSubString)
Searches a string, replacing all instances of oldSubString with newSubString.
replaceAt()—The replaceAt FunctionreplaceAt(string, element, index, separator)
Searches a string, replacing the original element with the indicated element.
squeeze()—The squeeze Functionsqueeze(string)
Replaces instances of multiple whitespaces within a string with a single inter-word space.
subString()—The subString FunctionsubString(string, startIndex, length)
Returns a substring from a specified string beginning at the startIndex and traversinglength characters.
toString()—The toString FunctiontoString(value)
Converts any and all WMLScript data types to a string value.
trim()—The trim Functiontrim(string)
Returns a string with all leading and trailing whitespace removed.
URL LibraryThe URL library contains a set of functions for handling both absolute URLs and relative URLs.
WMLScript
APPENDIX G
G
WM
LSC
RIPT
553
![Page 573: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/573.jpg)
escapeString()—The escapeString FunctionescapeString(string)
This function computes a new version of a string value in which special characters have beenreplaced by a hexadecimal escape sequence. The characters to be escaped are
• Control Characters—US-ASCII–coded characters 00-1F and 7F
• Space—US-ASCII–coded character 20 hexadecimal
• Reserved—“;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”
• Unwise—“{” | “}” | “|” | “\” | “^” | “[“ | “]” | “`”
• Delims—“<” | “>” | “#” | “%” | <”>
• Non-US–ASCII—Characters with hex code 8F-FF
The given string is escaped as such; no URL parsing is performed. Non-US–ASCII charactersmust be converted with the character codes used in the native character set.
getBase()—The getBase FunctiongetBase()
Returns the absolute URL of the current WMLScript unit.
getFragment()—The getFragment FunctiongetFragment(url)
Returns the fragment of the indicated url.
getHost()—The getHost FunctiongetHost(url)
Returns the host of the indicated url.
getParameters()—The getParameters FunctiongetParameters(url)
Returns the parameters used in the indicated url.
getPath()—The getPath FunctiongetPath(url)
Returns the path used in the indicated url.
Appendixes
PART IV554
![Page 574: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/574.jpg)
getPort()—The getPort FunctiongetPort(url)
Returns the port used in the indicated url.
getQuery()—The getQuery FunctiongetQuery(url)
Returns the query used in the indicated url.
getReferer()—The getReferer FunctiongetReferer()
Returns the URL of the resource that called the current compilation unit.
getScheme()—The getScheme FunctiongetScheme(url)
Returns the scheme of the indicated url.
isValid()—The isValid FunctionisValid(url)
Checks the indicated url for appropriate URL syntax, returning true if correct, false if not.
loadString()—The loadString FunctionloadString(url, contentType)
Returns the content specified by the url and contentType (for example, text/html).
resolve()—The resolve Functionresolve(baseUrl, embeddedUrl)
Produces an absolute URL from a given baseUrl and embeddedUrl.
unescapeString()—The unescapeString FunctionunescapeString(string)
This function performs the opposite task of the URL.escapeString() function, returning astring with the escape characters replaced by the original characters that these escape charac-ters represent.
WMLScript
APPENDIX G
G
WM
LSC
RIPT
555
![Page 575: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/575.jpg)
WMLBrowser LibraryThe WMLBrowser library contains functions by which WMLScript can access the associatedWML context. These functions must not have any side effects and must return invalid in caseswhere the system does not support WMLBrowser and where the WML Browser does not invokethe interpreter.
getCurrentCard()—The getCurrentCard FunctiongetCurrentCard()
Returns the relative URL of the current card.
getVar()—The getVar FunctiongetVar(name)
Returns the value of the specified variable.
go()—The go Functiongo(url)
Loads and transfers focus to the given url.
newContext()—The newContext FunctionnewContext()
A type of “reset” function; clears all present variables and clears the navigation history stack.
prev()—The prev Functionprev()
Returns focus back to the previous WML card.
refresh()—The refresh Functionrefresh()
Forces a refresh of the WML Browser based on current context and variable values.
setVar()—The setVar FunctionsetVar(name, value)
Sets the value of a local deck variable.
Appendixes
PART IV556
![Page 576: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/576.jpg)
Dialogs LibraryThe Dialogs library contains a set of typical user-interface functions.
alert()—The alert Functionalert(message)
Displays a message for the user and awaits a confirmation.
confirm()—The confirm Functionconfirm(message, ok, cancel)
Displays a message to the user with OK and Cancel buttons on the dialog box.
prompt()—The prompt Functionprompt(message, defaultInput)
Prompts the user to input content before proceeding. defaultInput can be used to populatethe box with a default value.
WMLScript
APPENDIX G
G
WM
LSC
RIPT
557
![Page 577: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/577.jpg)
![Page 578: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/578.jpg)
INDEXSYMBOLS
{} (brackets), 407<?...?> notation, 1522-tier database access model, 86-873-tier database access model, 86-873G, 389
A<a> tag, 400, 544abort() method, 548abs() method, 548<access> tag, 544accessing LDAP (Lightweight Directory Access
Protocol) servers, 184-188actionPerformed() method, 79actions, 240-241, 262
counter exampleBeanCounter.jsp, 265-268Counter.java, 264-265
<jsp:forward>attributes, 274MCPHome.jsp example, 276SamsHome.jsp example, 275-276syntax, 274UseForward.jsp example, 274-275
<jsp:getProperty>, 264<jsp:include>
attributes, 269EmployeeInfo.jsp example, 270-273header.jsp example, 269syntax, 269
<jsp:param>, 268-269<jsp:plugin>, 278-279<jsp:setProperty>, 263-264
![Page 579: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/579.jpg)
actions560
<jsp:useBean>attributes, 262-263scope values, 267-268syntax, 262
activation.jar file, 133Active Server Pages (ASPs), 18Add view (LDAP client),
354-355add() method, 358addCookie() method, 473AddToCart service (movie
catalog application), 341-342ADD_ATTRIBUTE operator,
177alert() method, 557Allaire JRun, 191, 395AllNetDevices Web site, 395alternatives to servlets, 17-18<anchor> tag, 400, 544anchors, 400, 544AnywhereYouGo.com Web site,
396Apache
Cocoon, 414Tomcat server
downloading, 422-423installing, 423-424server.xml file, 424-426
APIs (application programminginterfaces)
JAXP (Java API for XMLProcessing)
downloading, 153SAX API (Simple API for
XML), 153-159JNDI (Java Naming and
Directory Interface), 166adding objects to LDAP
servers, 174-176connecting to LDAP
servers, 168-170modifying LDAP server
information, 177-184removing objects from
LDAP servers, 176searching LDAP servers,
170-174
proprietary, 18Servlet API, 51-58
applets, OrderStatusApplet,74-80
actionPerformed() method, 79code listing, 74-79HTML file, 79-80readOrder() method, 79writeOrder() method, 79
APPLICATION field(PageContext class), 502
application object, 241GetFromApplication servlet,
255-256initializing, 254scope, 254StoreInApplication servlet,
254-255application programming
interfaces. See APIsapplication scope (JavaBeans),
268, 289-291application servers, deploying
EJBs (Enterprise JavaBeans)to, 218
deploying jar files, 220packaging jar files, 218-219viewing deployed beans, 220
ApplicationBean1.jsp (code listing), 289
ApplicationBean2.jsp (code listing), 289-290
applications. See also listingsWeb. See Web applicationswireless development. See
wireless developmentWMLExample
code listing, 401-403input card, 404previous card, 405select card, 405setvar card, 404timer card, 405welcome card, 404
WMLScriptExampleWMLScriptExample.wml,
410-411WMLScriptExample.wmls,
409-410APPLICATION_SCOPE field
(PageContext class), 502arithmetic operators, 407ASPs (Active Server Pages), 18assignment operators, 407Attribute object, 174attribute subelement (<tag>
tag), 304attributeInfo field (TagInfo
class), 533attributes
custom tags, 314-317directories, 165<jsp:forward> action, 274<jsp:getProperty> action, 264<jsp:include> action, 269<jsp:param> action, 268<jsp:plugin> action, 279<jsp:setProperty> action,
263-264<jsp:useBean> action,
262-263Movie object, 322-323page directive, 238-239People object, 348stock object, 364-365taglib directive, 240
attributes field (TagData class),530
AT_BEGIN field (VariableInfoclass), 540
AT_END field (VariableInfoclass), 540
authenticationbasic, 148digest, 148-149HTTP (Hypertext Transfer
Protocol), 42autoFlush field (JspWriter
class), 495autoflush= attribute (page
directive), 239
![Page 580: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/580.jpg)
catalog layout view561
B<b> tag, 399, 544bandwidth, 390BasicServlet
compiling, 426doGet() method, 30-31doPost() method, 30-31getServletInfo() method, 31init() method, 30installing, 426-427servlet framework, 29source code listing, 27-29
BEA WebLogic, 395bean class, 210-215bean object, 193bean-managed persistence, 206BeanCounter.jsp, 265-266
<jsp:getProperty> action, 267<jsp:setProperty> action, 266<jsp:useBean> action,
266-268beanName attribute
(<jsp:useBean> action), 263beans. See JavaBeansbearer service, 388<big> tag, 399, 544binding to LDAP (Lightweight
Directory Access Protocol)servers, 169-170
bitwise operators, 407bodies
tags with, 306example of, 307-311processing, 307TagSupport class, 307
tags withoutBodyTag interface, 311example of, 312-314processing, 311
BodyContent class, 522-523bodyContent field (TagInfo
class), 534bodycontent subelement (<tag>
tag), 304
BodyContent() method, 522bodyOut field (Tag interface),
514BodyTag interface, 311, 520-521BodyTagSupport class
BodyTagSupport() method,523
doAfterBody() method, 523doEndTag() method, 523doInitBody() method, 524doStartTag() method, 524getBodyContent() method,
524getPreviousOut() method, 524release() method, 524setBodyContent() method,
525BodyTagSupport() method, 523BODY_CONTENT_JSP field
(TagInfo class), 533BODY_CONTENT_TAG_
DEPENDENT field (TagInfoclass), 533
boolean parameterprint() method, 495println() method, 498
<br> tag, 399-400, 544braces ({}), 407break statement, 408browsers
PDA WAP browsers, 394WinWAP, 392-394
buffer= attribute (page directive), 239
bufferSize field (JspWriterclass), 495
Building Servlets To OuputWML Content (Web site), 412
Buy service (stock tradingapplication), 377-379
Buy/Sell view (stock tradingapplication), 372, 375
buying stock (stock tradingapplication), 377-379
CcalcMonthlyPayment() method,
196, 200CalculateLoan bean
bean class, 198-200deployment descriptor, 203remote interface, 195-197
calculating loan payments. SeeCalculateLoan bean
calling WMLScript, 406<card> tag, 401, 544cards, 398, 404-405Catalog application
ConnectionPool, 323-325controllers, 338
AddToCart service,341-342
CheckOut service, 343-344EmptyCart service, 343ListMovies service,
338-341index, 332-333listing movies, 334-335,
338-341Movie object, 322-323requirements, 322shopping cart
adding items to, 341-342checking out, 336-338,
343-344displaying contents of,
335-336emptying, 343source code listing,
325-328testing, 344-345title bar, 329views, 328
catalog layout, 328-332Check Out, 336-338Index, 332-333Movie List, 334-335Shopping Cart, 335-336
catalog layout view (movie cata-log application), 328-332
![Page 581: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/581.jpg)
CatalogConnectionPool servlet562
CatalogConnectionPool servlet,323-325
catching errors. See error handling
CDMA (Code Division MultipleAccess), 389
CDPD (Cellular Digital PacketData), 389
ceil() method, 550Cellmania Web site, 395Cellular Digital Packet Data
(CDPD), 389CGI (Common Gateway
Interface), 17-18char parameter
print() method, 496println() method, 498
characters() method, 157characterSet() method, 548charAt() method, 551char[] parameter
print() method, 497println() method, 499
Check Out view (movie catalogapplication), 336-338
checking out (movie catalogapplication), 336-338, 343-344
CheckOut service (movie catalog application), 343-344
class attribute (<jsp:useBean>action), 263
classesbean classes, 210-215BodyContent, 522-523BodyTagSupport
BodyTagSupport() method,523
doAfterBody() method,523
doEndTag() method, 523doInitBody() method, 524doStartTag() method, 524getBodyContent() method,
524getPreviousOut() method,
524
release() method, 524setBodyContent() method,
525Context, 168-170Controller, 8Cookie, 47, 479
clone() method, 483Cookie() method, 480getComment() method,
480getDomain() method, 480getMaxAge() method, 481getName() method, 482getPath() method, 481getSecure() method, 482getValue() method, 482getVersion() method, 483setComment() method,
480setDomain() method, 480setMaxAge() method, 481setPath() method, 481setSecure() method, 482setValue() method, 482setVersion() method, 483
DirContext, 170GenericServlet, 20-22
destroy() method, 449GenericServlet() method,
449getInitParameter()
method, 449getInitParameterNames()
method, 449getServletConfig() method,
450getServletContext()
method, 450getServletInfo() method,
450init() method, 450-451log() method, 451service() method, 451-452
HttpServlet, 20-22doDelete() method, 484doGet() method, 484
doOptions() method, 485doPost() method, 484doPut() method, 484doTrace() method, 485getModifiedTime() method,
485HttpServlet() method, 483service() method, 485-486
HttpSession, 51-52HttpSessionBindingEvent,
486-487HttpUtils, 487-488JspEngineInfo, 492JSPError, 512JSPException, 512JspFactory
deflt field, 492getDefaultFactory()
method, 493getEngineInfo() method,
494getPageContext() method,
493-494JspFactory() method, 493releasePageContext()
method, 494setDefaultFactory()
method, 493JspWriter, 494
fields, 495methods, 495-502
LDAPInsertData, 184-186LDAPManager, 178-184MimeMessage, 136-137Model, 8PageContext
fields, 502-504methods, 504-511
ServletException, 456-458ServletInputStream, 452ServletOutputStream, 452
print() method, 453-454println() method, 455-456ServletOutputStream()
method, 453Session, 135-136
![Page 582: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/582.jpg)
contexts563
ShoppingCart, 325-328TagAttributeInfo
fields, 528-529methods, 529-530
TagData, 530-531TagExtraInfo, 532-533TagInfo
fields, 533-534methods, 534-537
TagLibraryInfofields, 537methods, 538-539
TagSupport, 307fields, 525methods, 525-528
UnavailableException,458-459
VariableInfo, 539-541View, 8
className field (VariableInfoclass), 540
clear() method, 500clearBody() method, 522clearBuffer() method, 500clients
EJB (Enterprise JavaBeans)clients, 191servlets as EJB clients,
220-224HTTP tunneling, 66-71LDAP (Lightweight Directory
Access Protocol) client, 348controllers, 356-360deleting directory objects,
359-360displaying directory server
contents, 352-353home page, 351-352HTML form, 354-355inserting directory objects,
358-359models, 348navigation, 350-351running, 360-361searching directory server,
356-357
title bar, 349-350views, 349-355
clone() method, 483close() method, 501Cocoon (Apache), 414code attribute (<jsp:plugin>
action), 279Code Division Multiple Access
(CDMA), 389code listings. See listingscodebase attribute
(<jsp:plugin> action), 279Common Gateway Interface
(CGI), 17-18communication, inter-servlet
ConnectionPoolServletexample, 123-126
TitleListGlobalPooledServletexample, 127-130
compare() method, 551compiling BasicServlet, 426components (JSPs), 237
actions, 240-241directives
defined, 238include, 239page, 238-239syntax, 238taglib, 240
implicit objects. See implicitobjects
JSP scriptingdeclarations, 242-243expressions, 243-244scriplets, 244-246
CONFIG field (PageContextclass), 503
config object, 241, 258-259configuring
MIME types, 412-413ODBC data sources, 92-93
confirm() method, 557connecting to LDAP
(Lightweight Directory AccessProtocol) servers, 168-170
binding, 169-170Context class, 168-170DirContext class, 170
connection pools (JDBC), 112ConnectionPool object
code listing, 112-118initializing, 118-120requirements, 112
emptying, 122getting connections from,
121-122inter-servlet communication
ConnectionPoolServlet,123-126
TitleListGlobalPooled-Servlet, 127-130
movie catalog application,323-325
PooledConnection object,120-121
releasing connections, 122requirements, 112stock trading application,
365-367ConnectionPool object
code listing, 112-118initializing, 118-120movie catalog application,
323-325requirements, 112
ConnectionPoolServlet, 365-367code listing, 123-125destroy() method, 125-126init() method, 125preloading, 126
containerscontainer-managed
persistence, 206LDAPObject, 172
containsHeader() method, 473contentType= attribute (page
directive), 239Context class, 168-170contexts
PageContext classfields, 502-504methods, 504-511
![Page 583: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/583.jpg)
contexts564
pageContext object, 241, 251ServletContext object,
254-255continue statement, 408Controller class, 8Controllers, 8
creatingcode listing, 226-228execute() method, 229forward() method, 229
defined, 226LDAP (Lightweight Directory
Access Protocol) clientLDAPDelete service,
359-360LDAPDirectory service,
356-357LDAPInsert service,
358-359movie catalog application
AddToCart service,341-342
CheckOut service, 343-344EmptyCart service, 343ListMovies service,
338-341sample service, 230
ExampleService.java,230-231
ExampleView.java,231-232
Service interface, 229-230servlets as, 9-10stock trading application
Buy service, 377-379GetQuote service, 375-377Sell service, 380-382
Cookie class, 47, 479clone() method, 483Cookie() method, 480getMaxAge() method, 481getName() method, 482getPath() method, 481getSecure() method, 482getValue() method, 482getVersion() method, 483
setMaxAge() method, 481setPath() method, 481setSecure() method, 482setValue() method, 482setVersion() method, 483
Cookie() method, 480cookies, 46
Cookie class, 47, 479clone() method, 483Cookie() method, 480getComment() method,
480getDomain() method, 480getMaxAge() method, 481getName() method, 482getPath() method, 481getSecure() method, 482getValue() method, 482getVersion() method, 483setComment() method,
480setDomain() method, 480setMaxAge() method, 481setPath() method, 481setSecure() method, 482setValue() method, 482setVersion() method, 483
CookieServlet example, 47-49definition of, 46support for, 46
CookieServlet, 47-49Counter JavaBean, 264-265
code listing, 282scope
application, 289-291page, 283request, 284-286session, 286-288
counters, 264BeanCounter.jsp, 265-266
<jsp:getProperty> action,267
<jsp:setProperty> action,266
<jsp:useBean action>,266-268
Counter JavaBean, 264-265code listing, 282scope, 283-291
CREATE statement (SQL),95-97
create() method, 196createStatement() method, 94CreateTablesApp.java (code
listing), 95-97creating servlets. See writing
servletscurly brackets ({}), 407custom tags
attributes, 314-317deploying
tag handlers, 304taglib directive, 304-306tld files, 302-304
example, 302tags with bodies
BodyTag interface, 311example of, 312-314processing, 311
tags without bodies, 306example of, 307-311processing, 307TagSupport class, 307
Ddata sources (ODBC), 92-93database connections (JDBC),
93-94databases
compared to directories, 164JDBC (Java Database
Connectivity). See JDBCtables
creating, 95-97deleting data from, 107inserting data into, 97-101selecting data in, 101-105updating, 105-107
decks, 398declarations (JSP), 242-243
![Page 584: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/584.jpg)
downloading565
declare field (VariableInfoclass), 540
DEFAULT_BUFFER field(JspWriter class), 495
deflt field (JspFactory class),492
DELETE statement, 107deleting
directory server objects,359-360
objects from LDAP(Lightweight DirectoryAccess Protocol) servers,176
table data, 107deploying
EJB (Enterprise JavaBeans)deploying jar files, 220packaging jar files,
218-219viewing deployed beans,
220jar files, 220tag handlers, 304tag libraries
tag handlers, 304taglib directive, 304-305adding to JSPs, 305-306tld files, 302-304
deployment descriptors, 421-422entity beans, 215-217session beans, 200-204
design patterns, MVC (ModelView Controller)
classes, 8server-side implementation, 8advantages, 9JSPs as Views, 10servlets as MVC controllers,
9-10step-by-step process, 9
destroy() method, 20, 27,125-126, 433, 449
destroying servlets, 27developer tools (WAP), 394
Dialogs library, 409, 557DirContext class, 170directives
defined, 238include, 239page, 238-239syntax, 238taglib
adding to JSPs, 305-306adding to Web applica-
tions, 304-305attributes, 240
directoriesaccessing. See LDAP
(Lightweight DirectoryAccess Protocol)
attributes, 165compared to relational
databases, 164DNs (distinguished names),
165Web applications, 420-421
directory application, 348controllers
LDAPDelete service,359-360
LDAPDirectory service,356-357
LDAPInsert service,358-359
running, 360-361deleting directory objects,
359-360displaying directory server
contents, 352-353home page, 351-352HTML form, 354-355inserting directory objects,
358-359models, 348navigation, 350-351searching directory server,
356-357title bar, 349-350
viewsAdd, 354-355Directory, 352-353Directory Layout, 349-351Index, 351
Directory Layout view (LDAPclient), 349-351
Directory view (LDAP client),352-353
displaying shopping cart contents, 335-336
distinguished names (DNs), 165DNs (distinguished names), 165<do> tag, 544doAfterBody() method, 311,
516, 521-523doBeforeBody() method, 516DoCoMo i-Mode, 388document tree structure (XML),
152doDelete() method, 484doEndTag() method, 307, 517,
523-525does not exist state
entity beans, 217session beans, 205
doGet() method, 484BasicServlet example, 30-31HiddenFieldServlet, 43
doInitBody() method, 311, 521,524
doOptions() method, 485doPost() method, 121-122, 484
BasicServlet example, 30-31HiddenFieldServlet, 43
doPut() method, 484doStartTag() method, 307, 517,
524-526doTrace() method, 485double parameter
print() method, 497println() method, 499
downloadingJavaMail, 133JAXP (Java API for XML
Processing), 153
![Page 585: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/585.jpg)
downloading566
Netscape Directory Server,167
Tomcat server, 422-423drivers, JDBC (Java Database
Connectivity), 87installing, 92-93JDBC-Net, 89-91JDBC-ODBC Bridge, 88-89,
92-93loading, 94native-API, 88, 90native-protocol, 90-91
Ee-commerce
order status tool, 73Order object, 73-74OrderStatusApplet, 74-80OrderStatusServlet, 80-83
shopping cartsadding items to, 341-342checking out, 336-338,
343-344displaying contents of,
335-336emptying, 343source code listing,
325-328e-mail, JavaMail
downloading, 133sending messages, 133-141store service, 132transport service, 132
editing LDAP (LightweightDirectory Access Protocol)server information
ADD_ATTRIBUTE operator,177
LDAPManager class, 178-184REMOVE_ATTRIBUTE
operator, 177REPLACE_ATTRIBUTE
operator, 177efficiency of servlets, 19
EJB (Enterprise JavaBeans),190
application servers, 191bean object, 193clients, 191, 220-224deployment
deploying jar files, 220packaging jar files,
218-219viewing deployed beans,
220ejb-jar.xml file, 200-201
code listing, 203<ejb-class> tag, 201<ejb-jar> tag, 201<ejb-name> tag, 201<enterprise-beans> tag,
201<entity> tag, 216<home> tag, 201<reentrant> tag, 216<remote> tag, 201<session-type> tag, 201<transaction-type> tag,
201entity beans, 192
bean class, 210-215client view of, 217deployment descriptors,
215-217home interface, 208-209lifecycle, 217-218persistence, 206-207primary keys, 209-210remote interface, 207-208
interfaces, 192JRun, 191naming conventions, 193primary keys, 193session beans, 192-194
bean class, 197-200client view of, 204deployment descriptors,
200-204home interface, 196-197lifecycle, 205-206
passivation, 205-206remote interface, 195-196stateful, 194stateless, 194
<ejb-class> tag, 201<ejb-jar> tag, 201ejb-jar.xml file, 200-201
code listing, 203<ejb-class> tag, 201<ejb-jar> tag, 201<ejb-name> tag, 201<enterprise-beans> tag, 201<entity> tag, 216<home> tag, 201<reentrant> tag, 216<remote> tag, 201<session-type> tag, 201<transaction-type> tag, 201
<ejb-name> tag, 201ejbActivate() method, 206ejbCreate() method, 211ejbFind() method, 211ejbLoad() method, 215, 218ejbPassivate() method, 206ejbPostCreate() method, 211ejbStore() method, 215, 218EJBTestServlet, 221-224electronic mail. See e-mailelementAt() method, 551elements() method, 552elements. See tagselse clause, 407<em> tag, 544EmployeeInfo JSP (JavaServer
Page)code listing, 270-271jspService() method, 272-273
EmptyCart service (movie catalog application), 343
emptyingconnection pools, 122shopping carts, 343
emptyPool() method, 122emulators, WAP (Wireless
Application Protocol), 392-394enabling serialized objects, 60
![Page 586: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/586.jpg)
fields567
encodeRedirectURL() method,51, 474
encodeURL() method, 473endElement() method, 157-158Enhydra Hava/XML application
server, 395Enterprise JavaBeans. See EJB<enterprise-beans> tag, 201entity beans, 192
bean class, 210-215client view of, 217deployment descriptors,
215-217home interface, 208-209lifecycle, 217-218persistence, 206-207primary keys, 209-210remote interface, 207-208
<entity> tag, 216equality testing operators, 407error handling (JSPs)
error pagescatching errors in,
297-300creating, 294-297errorpage.jsp example,
294-295generated server code,
295-297testerror.jsp example, 297
request time errors, 294translation time errors, 294
error pagescatching errors in, 297-300creating, 294-297errorpage.jsp example,
294-295generated server code,
295-297testerror.jsp example, 297
errorpage.jsp (code listing),294-295
errorPage= attribute (pagedirective), 239
escapeString() method, 554
EVAL_BODY field (Tag interface), 515
EVAL_BODY_TAG field(BodyTag interface), 521
EVAL_PAGE field (Tag interface), 515
event handlers,SAXHandler.java, 155, 157,159
events, WML (Wireless MarkupLanguage), 400-401
ExampleService.java, 230-231ExampleView.java, 231-232EXCEPTION field
(PageContext class), 503exception object, 241, 260exceptions
exception object, 260JSPError, 512JSPException, 512ServletException class,
456-458UnavailableException class,
458-459execute() method, 229executeQuery() method, 103executeUpdate() method, 97,
101exit() method, 548expressions (JSP), 243-244extends= attribute (page
directive), 238extensibility of servlets, 20Extensible Markup Language.
See XML
Ffields
BodyTag interface, 521hidden form fields
HiddenFieldServlet, 43-46sample HTML listing,
42-43
HttpServletResponse interfaceSC_ACCEPTED, 469SC_BAD_GATEWAY, 472SC_BAD_REQUEST, 470SC_CONFLICT, 471SC_CONTINUE, 468SC_CREATED, 468SC_FORBIDDEN, 470SC_GATEWAY_
TIMEOUT, 473SC_GONE, 471SC_HTTP_VERSION_
NOT_SUPPORTED, 473SC_INTERNAL_SERVER_
ERROR, 472SC_LENGTH_REQUIRED,
472SC_MOVED_
PERMANENTLY, 469SC_MOVED_
TEMPORARILY, 469SC_MULTIPLE_
CHOICES, 469SC_NON_
AUTHORITATIVE_INFORMATION, 469
SC_NOT_ACCEPTABLE,471
SC_NOT_ALLOWED, 471SC_NOT_FOUND, 471SC_NOT_
IMPLEMENTED, 472SC_NOT_MODIFIED,
470SC_NO_CONTENT, 469SC_OK, 468SC_PARTIAL_CONTENT,
469SC_PAYMENT_
REQUIRED, 470SC_PRECONDITION_
FAILED, 472SC_PROXY_AUTHENTI-
CATION_REQUIRED,471
SC_REQUEST_ENTITY_TOO_LARGE, 472
![Page 587: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/587.jpg)
fields568
SC_REQUEST_TIMEOUT, 471
SC_REQUEST_URI_TOO_LONG, 472
SC_RESET_CONTENT,469
SC_SEE_OTHER, 470SC_SERVICE_
UNAVAILABLE, 473SC_SWITCHING_
PROTOCOLS, 468SC_UNAUTHORIZED,
470SC_UNSUPPORTED_
MEDIA_TYPE, 472SC_USE_PROXY, 470
JspFactory class, 492JspWriter class, 495PageContext class
APPLICATION, 502APPLICATION_SCOPE,
502CONFIG, 503EXCEPTION, 503OUT, 503PAGE, 503PAGECONTEXT, 503PAGE_SCOPE, 503REQUEST, 503REQUEST_SCOPE, 503RESPONSE, 504SESSION, 504SESSION_SCOPE, 504
Tag interfacebodyOut, 514EVAL_BODY, 515EVAL_PAGE, 515libraryPrefix, 515pageContext, 515parent, 515previousOut, 515SKIP_BODY, 515SKIP_PAGE, 515tagData, 515tagID, 516
tagName, 516values, 516
TagAttributeInfo class,528-529
TagData class, 530TagInfo class, 533-534TagLibraryInfo class, 537TagSupport class, 525VariableInfo class, 540
<fieldset> tag, 544file extensions, 412files
activation.jar, 133ejb-jar.xml, 200-201
code listing, 203<ejb-class> tag, 201<ejb-jar> tag, 201<ejb-name> tag, 201<enterprise-beans> tag,
201<entity> tag, 216<home> tag, 201<reentrant> tag, 216<remote> tag, 201<session-type> tag, 201<transaction-type> tag,
201jar files
deploying, 220deploying tag handlers as,
304packaging, 218-219
jaxp.jar, 153mail.jar, 133parser.jar, 153server.xml, 424, 426tld files, 302-304WAR (Web Archive), 422
find() method, 552findAncestorWithClass()
method, 517, 526findAttribute() method, 504findByName() method, 208findByPrimaryKey() method,
208, 217
Float library, 408, 550-551float parameter
print() method, 497println() method, 499
float() method, 548floor() method, 550flush attribute (<jsp:include>
action), 269flush() method, 500flushBuffer() method, 446format() method, 552formatting text, 399forms
hidden form fieldsHiddenFieldServlet, 43-46sample HTML listing,
42-43mail forms, 137-138retrieving data from
FormServlet example,34-39
GET method, 34-36getParameter() method, 34getParameterNames()
method, 34getParameterValues()
method, 34POST method, 36-38
FormServlet, 34-39forName() method, 94forward action. See
<jsp:forward> actionforward() method, 229, 431,
504-505forwarding requests, 277-278
<jsp:forward> action, 274MCPHome.jsp, 276SamsHome.jsp, 275-276UseForward.jsp, 274-275
methods. See methodsfuture of WAP (Wireless
Application Protocol), 387-388
![Page 588: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/588.jpg)
getRemaining() method569
Ggateways, 388Gelon.net Web site, 392, 395General Packet Radio Service
(GPRS), 389GenericServlet class, 20-22
destroy() method, 449GenericServlet() method, 449getInitParameter() method,
449getInitParameterNames()
method, 449getServletConfig() method,
450getServletContext() method,
450getServletInfo() method, 450init() method, 450-451log() method, 451service() method, 451-452
GenericServlet() method, 449GET method, 34-38Get Quote view (stock trading
application), 371-372getAttrib() method, 439getAttribute() method, 51, 125,
440, 476, 505, 531getAttributeName() method, 476getAttributeNames() method,
439-440getAttributeNamesInScope()
method, 505-506getAttributes() method, 535getAttributesScope() method,
506getAttributeString() method,
531getAuthType() method, 463getBase() method, 554getBodyContent() method, 524,
535getBodyOut() method, 518getBufferSize() method, 446, 501getCharacterEncoding()
method, 440, 446
getClassName() method, 541getComment() method, 480getConnection() method, 94,
121, 127getContentLength() method,
441getContentType() method, 441getContext() method, 435getContextPath() method, 463getCookies() method, 463getCreationTime() method, 477getCurrentCard() method, 556getCurrentInterestRate()
method, 200getDateHeader() method, 463getDeclare() method, 541getDefaultFactory() method,
493getDomain() method, 480getEngineInfo() method, 494getException() method, 506getFragment() method, 554GetFromApplication servlet,
255-256getHeader() method, 464getHeaderNames() method, 464getHeaders() method, 464getHost() method, 554getId() method, 477, 526, 531getIdAttribute() method, 529getImplementationVersion()
method, 492getInfoString() method, 535,
538getInitParameter() method,
434-435, 449getInitParameterNames()
method, 434-435, 449getInputStream() method, 441getIntHeader() method, 464getLastAccessedTime() method,
477getLibraryPrefix() method, 518getLocale() method, 441, 446getLocales() method, 442
getMajorVersion() method, 435getMaxAge() method, 481getMaxIntervalTime() method,
477getMethod() method, 465getMimeType() method, 436getMinorVersion() method, 436getModifiedTime() method, 485getName() method, 482, 487,
529getNamedDispatcher() method,
436getOut() method, 506getOutputStream() method,
446-447getPage() method, 506getPageContext() method, 299,
493-494, 518getParameter() method, 34, 442getParameterNames() method,
34, 442getParameters() method, 554getParameterValues() method,
34, 442getParent() method, 518, 526getPath() method, 481 , 554getPathInfo() method, 465getPathTranslated() method,
465getPort() method, 555getPrefixString() method, 538getPreviousOut() method, 518,
524getProperty action. See
<jsp:getProperty> actiongetProtocol() method, 443getQuery() method, 555getQueryString() method, 465GetQuote service (stock trading
application), 375-377getReader() method, 444, 522getRealPath() method, 438getReferer() method, 555getReliableURN() method, 538getRemaining() method, 501
![Page 589: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/589.jpg)
getRemoteAddress() method570
getRemoteAddress() method,444
getRemoteHost() method, 444getRemoteUser() method, 466getRequest() method, 507getRequestDispatcher() method,
437, 443getRequestedSessionId()
method, 466getRequestURI() method, 466,
488getRequiredVersion() method,
538getResource() method, 436-437getResourceAsStream() method,
437getResponse() method, 507getRootCause() method, 458getScheme() method, 443, 555getScope() method, 541getSecure() method, 482getServerInfo() method, 438getServerName() method, 443getServerPort() method, 444getServletConfig() method, 432,
450, 507getServletContext() method,
433, 450, 507getServletInfo() method, 31,
433, 450getServletName() method, 434getServletPath() method, 466getSession() method, 56, 467,
487, 507getShortName() method, 539getString() method, 522getStudentList() method, 65getTable() method, 158getTag() method, 539getTagClassName() method, 536getTagData() method, 519getTagExtraInfo() method, 536getTagID() method, 519getTagInfo() method, 532getTagLibrary() method, 536getTagName() method, 519, 536
getTags() method, 539getTypeName() method, 530getUnavailableSeconds()
method, 459getURI() method, 539getUserPrincipal() method, 466getValue() method, 482, 519,
527getValues() method, 527getVar() method, 556getVariableInfo() method, 532,
536getVarName() method, 541getVersion() method, 483getWriter() method, 30, 447Global System for Mobile
Communication (GSM), 389<go> tag, 400, 544Go Wireless Web site, 412go() method, 556GPRS (General Packet Radio
Service), 389GSM (Global System for
Mobile Communication), 389
HHandheld Device Markup
Language (HDML), 386handlePageException method,
300handlePageException() method,
508handlers
SAXHandler.java, 155-159tag handlers, 304
handling errors. See error handling
handling sessions. See sessiontracking
HDML (Handheld DeviceMarkup Language), 386
<head> tag, 544HELLO JSP WORLD scriptlet,
245-246
Hello World! application,398-399, 413-414
Hello.jsp, 310-311HelloAttributeTag (tag with
attributes), 314HelloAttribute.jsp, 316-317HelloAttributeTag.java,
315-316HelloBodyTag (tag with body)
HelloBody.jsp, 313-314HelloBodyTag.jsp, 312-313
HelloTag (tag without body)Hello.jsp, 310-311HelloTag.java, 307-308taglib.tld, 309
hidden form fieldsHiddenFieldServlet, 43-46sample HTML listing, 42-43
HiddenFieldServlet, 43-46history of WAP (Wireless
Application Protocol), 386-387home interfaces
defined, 192entity beans, 208-209session beans, 196-197
home pages. See Web sites<home> tag, 201HtmlSessionServlet, 54-55HTTP (Hypertext Transport
Protocol) authentication, 42HttpJspPage interface,
490-491HttpServlet class, 20-22,
484-486HttpServletRequest interface,
462-468HttpServletResponse
interface, 469-476HttpSession class, 51-52HttpSessionBindingEvent
class, 486-487HttpSessionServlet, 52-54HttpUtils class, 487-488
![Page 590: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/590.jpg)
HttpServletResponse interface571
tunneling, 59advantages and
disadvantages, 83-84clients, 66-71defined, 60OrderStatus example,
73-83serialized objects, 60-66servlets, 71-73
HTTP (Hypertext TransportProtocol) authentication, 42
HTTP (Hypertext TransportProtocol) tunneling, 59
advantages and disadvantages,83-84
clients, 66-71defined, 60OrderStatus example
Order object, 73-74OrderStatusApplet, 74-80OrderStatusServlet, 80-83
serialized objects, 60-66servlets, 71-73
HttpJspPage interface, 490-491HttpServlet class, 20-22
doDelete() method, 484doGet() method, 484doOptions() method, 485doPost() method, 484doPut() method, 484doTrace() method, 485getModifiedTime() method,
485HttpServlet() method, 483service() method, 485-486
HttpServlet() method, 483HttpServletRequest interface,
462getAuthType() method, 463getContextPath() method, 463getCookies() method, 463getDateHeader() method, 463getHeader() method, 464getHeaderNames() method,
464getHeaders() method, 464
getIntHeader() method, 464getMethod() method, 465getPathInfo() method, 465getPathTranslated() method,
465getQueryString() method, 465getRemoteUser() method, 466getRequestedSessionId()
method, 466getRequestURI() method, 466getServletPath() method, 466getSession() method, 467getUserPrincipal() method,
466isRequestedSessionFrom
Cookie() method, 467isRequestedSessionIdFrom
URL() method, 468isRequestedSessionValid()
method, 467HttpServletResponse interface
fieldsSC_ACCEPTED, 469SC_BAD_GATEWAY, 472SC_BAD_REQUEST, 470SC_CONFLICT, 471SC_CONTINUE, 468SC_CREATED, 468SC_FORBIDDEN, 470SC_GATEWAY_
TIMEOUT, 473SC_GONE, 471SC_HTTP_VERSION_
NOT_SUPPORTED, 473SC_INTERNAL_SERVER_
ERROR, 472SC_LENGTH_
REQUIRED, 472SC_MOVED_
PERMANENTLY, 469SC_MOVED_
TEMPORARILY, 469SC_MULTIPLE_
CHOICES, 469SC_NON_
AUTHORITATIVE_INFORMATION, 469
SC_NOT_ACCEPTABLE,471
SC_NOT_ALLOWED, 471SC_NOT_FOUND, 471SC_NOT_
IMPLEMENTED, 472SC_NOT_MODIFIED,
470SC_NO_CONTENT, 469SC_OK, 468SC_PARTIAL_CONTENT,
469SC_PAYMENT_
REQUIRED, 470SC_PRECONDITION_
FAILED, 472SC_PROXY_
AUTHENTICATION_REQUIRED, 471
SC_REQUEST_ENTITY_TOO_LARGE, 472
SC_REQUEST_TIMEOUT, 471
SC_REQUEST_URI_TOO_LONG, 472
SC_RESET_CONTENT,469
SC_SEE_OTHER, 470SC_SERVICE_
UNAVAILABLE, 473SC_SWITCHING_
PROTOCOLS, 468SC_UNAUTHORIZED,
470SC_UNSUPPORTED_
MEDIA_TYPE, 472SC_USE_PROXY, 470
methodsaddCookie(), 473containsHeader(), 473encodeRedirectURL(), 474encodeURL(), 473sendError(), 474sendRedirect(), 475setDateHeader(), 475setIntHeader(), 475setStatus(), 476
![Page 591: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/591.jpg)
HttpSession class572
HttpSession class, 51-52HttpSessionBindingEvent class,
486-487HttpSessionBindingEvent()
method, 487HttpSessionServlet, 52-54HttpUtils class, 487-488HttpUtils() method, 487
I<i> tag, 399i-Mode, 388id attribute (<jsp:useBean>
action), 262ID field (TagAttributeInfo
class), 528id field (TagSupport class), 525ID/password security model
LoginScreen.html, 146-148RollYourOwnSecurityServlet,
144-146if statement, 407<img> tag, 544implicit objects, 241-242,
248-249application
GetFromApplicationservlet, 255-256
initializing, 254scope, 254StoreInApplication servlet,
254-255config, 258-259exception, 260out, 257-258page, 260pageContext, 251request, 249-250response, 250session, 252-253
import= attribute (page directive), 238
include action. See<jsp:include> action
include directive, 239include() method, 431, 508including resources in JSPs
(JavaServer Pages), 269-274Index view
LDAP client, 351-352movie catalog application,
332-333stock trading application,
370-371info subelement (<tag> tag), 304info= attribute (page directive),
239infoString field (TagInfo class),
534init() method, 26, 432, 450-451
BasicServlet example, 30ConnectionPool object, 119ConnectionPoolServlet, 125
initialize() method, 509, 520initializePool() method, 119-120initializing
application object, 254ConnectionPool object,
118-120servlets, 26
input card (WMLExample), 404input streams,
ServletInputStream class, 452<input> tag, 400, 544INSERT statement (SQL), 97,
99-101insertAt() method, 552inserting
directory server objects,358-359
table data, 97-101installing
BasicServlet, 426-427JDBC-ODBC Bridge, 92-93JRun, 191Netscape Directory Server,
167-168Tomcat server, 423-424
instance pooling, 205
int parameterprint() method, 496println() method, 498
int() method, 550inter-servlet communications
ConnectionPoolServletexample
code listing, 123-125destroy() method, 125-126init() method, 125preloading, 126
TitleListGlobalPooledServletexample, 127-130
interfacesBodyTag, 311, 520-521EJB (Enterprise JavaBeans),
192home, 192
entity beans, 208-209session beans, 196-197
HttpJspPage, 490-491HttpServletRequest, 462
getAuthType() method, 463getContextPath() method,
463getCookies() method, 463getDateHeader() method,
463getHeader() method, 464getHeaderNames()
method, 464getHeaders() method, 464getIntHeader() method,
464getMethod() method, 465getPathInfo() method, 465getPathTranslated()
method, 465getQueryString() method,
465getRemoteUser() method,
466getRequestedSessionId()
method, 466getRequestURI() method,
466
![Page 592: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/592.jpg)
isCommitted() method573
getServletPath() method,466
getSession() method, 467getUserPrincipal()
method, 466isRequestedSessionFrom
Cookie() method, 467isRequestedSessionIdFrom
URL() method, 468isRequestedSessionValid()
method, 467HttpServletResponse
fields, 468-473methods, 473-476
HttpSessiongetAttribute() method, 476getAttributeName()
method, 476getCreationTime() method,
477getId() method, 477getLastAccessedTime()
method, 477getMaxIntervalTime()
method, 477invalidate() method, 477isNew() method, 478removeAttribute() method,
478setAttribute() method, 478setMaxIntervalTime()
method, 478HttpSessionBindingListener,
479JspPage, 491remote, 192
entity beans, 207-208session beans, 195-196
RequestDispatcher, 431Service, 229-230Servlet, 20, 432-433ServletConfig, 433-434ServletContext, 434
getAttrib() method, 439getAttributeNames()
method, 439
getContext() method, 435getInitParameter()
method, 435getInitParameterNames()
method, 435getMajorVersion() method,
435getMimeType() method,
436getMinorVersion() method,
436getNamedDispatcher()
method, 436getRealPath() method, 438getRequestDispatcher()
method, 437getResource() method,
436-437getResourceAsStream()
method, 437getServerInfo() method,
438log() method, 437-438removeAttribute() method,
439setAttribute() method, 439
ServletRequestgetAttribute() method, 440getAttributeNames()
method, 440getCharacterEncoding()
method, 440getContentLength()
method, 441getContentType() method,
441getInputStream() method,
441getLocale() method, 441getLocales() method, 442getParameter() method,
34, 442getParameterName()
method, 34getParameterNames()
method, 442
getParameterValues()method, 34, 442
getProtocol() method, 443getReader() method, 444getRemoteAddress()
method, 444getRemoteHost() method,
444getRequestDispatcher()
method, 443getScheme() method, 443getServerName() method,
443getServerPort() method,
444isSecure() method, 445removeAttribute() method,
445setAttribute() method, 445
ServletResponse, 445flushBuffer() method, 446getBufferSize() method,
446getCharacterEncoding()
method, 446getLocale() method, 446getOutputStream() method,
446-447getWriter() method, 447isCommitted() method, 447reset() method, 447setBufferSize() method,
447setContentLength()
method, 448setContentType() method,
448
setLocale() method, 448SingleThreadModel, 448Tag
fields, 514-516methods, 516-520
Internet e-mail. See e-mailinvalidate() method, 477isAutoFlush() method, 502isCommitted() method, 447
![Page 593: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/593.jpg)
isEmpty() method574
isEmpty() method, 552isErrorPage= attribute (page
directive), 239isFloat() method, 549isInt() method, 549isNew() method, 478isPermanent() method, 459isRequestedSessionFrom
Cookie() method, 467isRequestedSessionIdFrom
URL() method, 468isRequestedSessionValid()
method, 467isSecure() method, 445isThreadSafe= attribute (page
directive), 239isValid() method, 533, 537, 555<italic> tag, 544item.xml (code listing), 152
Jjar files
deploying, 220deploying tag handlers as, 304packaging, 218-219
Java API for XML Processing(JAXP)
downloading, 153SAX API (Simple API for
XML)SAXHandler.java handler,
155-159XMLTest.java document,
153-155Java Beans. See JavaBeansJava Database Connectivity.
See JDBCJava Naming and Directory
Interface. See JNDIJava Server Pages. See JSPsJava servlets. See servletsjava.lang.Object parameter
print() method, 498println() method, 500
java.lang.String parameterprint() method, 497println() method, 500
JavaBeans, 282BeanCounter.jsp, 265-266
<jsp:getProperty> action,267
<jsp:setProperty> action,266
<jsp:useBean> action,266-268
Counter, 264-265, 282EJB (Enterprise JavaBeans).
See EJBproperties
referencing, 264setting, 263-264
scopeapplication, 289-291page, 283request, 284-286session, 286-288
JavaMaildownloading, 133sending messages
HTML mail forms,137-138
MailServlet example,138-141
SimpleSendMessage example, 133-137
store service, 132transport service, 132
JavaScript, 18JavaServer Pages. See JSPsJavaSoft Web site, 422javax.servlet package, 20,
429-430. See also servletsGenericServlet class
destroy() method, 449GenericServlet() method,
449getInitParameter()
method, 449getInitParameterNames()
method, 449
getServletConfig() method,450
getServletContext()method, 450
getServletInfo() method,450
init() method, 450-451log() method, 451service() method, 451-452
RequestDispatcher interface,431
Servlet interface, 432-433ServletConfig interface,
433-434ServletContext interface, 434
getAttrib() method, 439getAttributeNames()
method, 439getContext() method, 435getInitParameter() method,
435getInitParameterNames()
method, 435getMajorVersion() method,
435getMimeType() method,
436getMinorVersion() method,
436getNamedDispatcher()
method, 436getRealPath() method, 438getRequestDispatcher()
method, 437getResource() method,
436-437getResourceAsStream()
method, 437getServerInfo() method,
438log() method, 437-438removeAttribute() method,
439setAttribute() method, 439
![Page 594: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/594.jpg)
javax.servlet.http package575
ServletException class, 456getRootCause() method,
458ServletException() method,
457ServletInputStream class, 452ServletOutputStream class,
452print() method, 453-454println() method, 455-456ServletOutputStream()
method, 453ServletRequest interface
getAttribute() method, 440getAttributeNames()
method, 440getCharacterEncoding()
method, 440getContentLength()
method, 441getContentType() method,
441getInputStream() method,
441getLocale() method, 441getLocales() method, 442getParameter() method,
442getParameterNames()
method, 442getParameterValues()
method, 442getProtocol() method, 443getReader() method, 444getRemoteAddress()
method, 444getRemoteHost() method,
444getRequestDispatcher()
method, 443getScheme() method, 443getServerName() method,
443getServerPort() method,
444isSecure() method, 445
removeAttribute() method,445
setAttribute() method, 445ServletResponse interface,
445flushBuffer() method, 446getBufferSize() method,
446getCharacterEncoding()
method, 446getLocale() method, 446getOutputStream()
method, 446-447getWriter() method, 447isCommitted() method,
447reset() method, 447setBufferSize() method,
447setContentLength()
method, 448setContentType() method,
448setLocale() method, 448
SingleThreadModel interface,448
UnavailableException class,458-459
javax.servlet.http package, 20,462. See also servlets
Cookie class, 479clone() method, 483Cookie() method, 480getComment() method,
480getMaxAge() method, 481getName() method, 482getPath() method, 481getSecure() method, 482getValue() method, 482getVersion() method, 483setComment() method,
480setDomain() method, 480setMaxAge() method, 481setPath() method, 481
setSecure() method, 482setValue() method, 482setVersion() method, 483
HttpServlet classdoDelete() method, 484doGet() method, 484doOptions() method, 485doPost() method, 484doPut() method, 484doTrace() method, 485getModifiedTime() method,
485HttpServlet() method, 483service() method, 485-486
HttpServletRequest interface,462
getAuthType() method, 463getContextPath() method,
463getCookies() method, 463getDateHeader() method,
463getHeader() method, 464getHeaderNames()
method, 464getHeaders() method, 464getIntHeader() method,
464getMethod() method, 465getPathInfo() method, 465getPathTranslated()
method, 465getQueryString() method,
465getRemoteUser() method,
466getRequestedSessionId()
method, 466getRequestURI() method,
466getServletPath() method,
466getSession() method, 467getUserPrincipal()
method, 466
isRequestedSessionFrom-Cookie() method, 467
![Page 595: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/595.jpg)
javax.servlet.http package576
isRequestedSessionIdFrom-URL() method, 468
isRequestedSessionValid()method, 467
HttpServletResponse interfacefields, 468-473methods, 473-476
HttpSession interfacegetAttribute() method, 476getAttributeName()
method, 476getCreationTime() method,
477getId() method, 477getLastAccessedTime()
method, 477getMaxIntervalTime()
method, 477invalidate() method, 477isNew() method, 478removeAttribute() method,
478setAttribute() method, 478setMaxIntervalTime()
method, 478HttpSessionBindingEvent
class, 486-487HttpSessionBindingListener
interface, 479HttpUtils class, 487-488
javax.servlet.jsp package, 490HttpJspPage interface,
490-491JspEngineInfo class, 492JSPError exception, 512JSPException exception, 512JspFactory class
deflt field, 492getDefaultFactory()
method, 493getEngineInfo() method,
494getPageContext() method,
493-494JspFactory() method, 493
releasePageContext()method, 494
setDefaultFactory()method, 493
JspPage interface, 491JspWriter class, 494
fields, 495methods, 495-502
PageContext classfields, 502-504methods, 504-511
javax.servlet.jsp.tagext package,514
BodyContent class, 522-523BodyTag interface, 520-521BodyTagSupport class,
523-525Tag interface
fields, 514-516methods, 516-520
TagAttributeInfo classfields, 528-529methods, 529-530
TagData class, 530-531TagExtraInfo class, 532-533TagInfo class
fields, 533-534methods, 534-537
TagLibraryInfo class, 537-539TagSupport class
fields, 525methods, 525-528
VariableInfo class, 539-541JAXP (Java API for XML
Processing)downloading, 153SAX API (Simple API for
XML), 153SAXHandler.java handler,
155-159XMLTest.java document,
153-155jaxp.jar file, 153
JDBC (Java DatabaseConnectivity), 86
connection poolsConnectionPool object,
112-120emptying, 122getting connections from,
121-122inter-servlet communica-
tion, 123-130PooledConnection object,
120-121releasing connections, 122requirements, 112
database connections, 93-94drivers, 87
installing, 92-93JDBC-Net, 89-91JDBC-ODBC Bridge,
88-89, 92-93loading, 94native-API, 88-90native-protocol, 90-91
inter-servlet communicationsConnectionPoolServlet
example, 123-126TitleListGlobalPooled-
Servlet example,127-130
ODBC data sources, 92-93Statement objects, 94tables
creating, 95-97deleting data from, 107inserting data into, 97-101selecting data in, 101-105updating, 105-107
three-tier database accessmodel, 86-87
TitleListServlet example,107-111
two-tier database accessmodel, 86-87
JDBC-Net drivers, 89, 91JDBC-ODBC Bridge, 88-89,
92-93
![Page 596: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/596.jpg)
<jsp:forward> action577
jjbCreate() method, 197-198JNDI (Java Naming and
Directory Interface), 166adding objects to LDAP
servers, 174-176connecting to LDAP servers,
168-170modifying LDAP server
informationADD_ATTRIBUTE
operator, 177LDAPManager class,
178-184REMOVE_ATTRIBUTE
operator, 177REPLACE_ATTRIBUTE
operator, 177removing objects from LDAP
servers, 176searching LDAP servers,
170-174client code, 173LDAPObject container
object, 172sample code listing,
170-171scope, 170search base, 170
JRun, 191, 395jspDestroy() method, 491JspEngineInfo class, 492JspEngineInfo() method, 492JSPError class, 512JspError() method, 512JSPException class, 512JspException() method, 512JspFactory class
deflt field, 492getDefaultFactory() method,
493getEngineInfo() method, 494getPageContext() method,
493-494JspFactory() method, 493
releasePageContext() method,494
setDefaultFactory() method,493
JspFactory() method, 493jspInit() method, 491JspPage interface, 491JSPs (JavaServer Pages)
actions. See actionscustom tags
attributes, 314-317deploying, 302-306example, 302tags with bodies, 311-314tags without bodies,
306-311definition of, 236directives
defined, 238include, 239page, 238-239syntax, 238taglib, 240
EmployeeInfocode listing, 270-271jspService() method,
272-273error handling
error pages, 294-300request time errors, 294translation time errors,
294implicit objects, 241-242,
248-249application, 254-256config, 258-259exception, 260out, 257-258page, 260pageContext, 251request, 249-250response, 250session, 252-253
including additional resourcesin, 269-274
javax.servlet.jsp package, 490HttpJspPage interface,
490-491JspEngineInfo class, 492JSPError exception, 512JSPException exception,
512JspFactory class, 492-494JspPage interface, 491JspWriter class, 494-502PageContext class,
502-511MCPHome, 276as MVC (Model View
Controller) Views, 10SamsHome, 275-276scripting
declarations, 242-243expressions, 243-244scriplets, 244-246
simple example, 236-237tags
<tag>, 303-304<taglib>, 304-306
testing, 256UseForward, 274-275
jspservice() method, 248-249,272-273, 491
JspWriter class, 494fields, 495methods
clear(), 500clearBuffer(), 500close(), 501flush(), 500getBufferSize(), 501getRemaining(), 501isAutoFlush(), 502JspWriter(), 495newLine(), 495print(), 495-498println(), 498-500
JspWriter() method, 495<jsp:forward> action, 240
attributes, 274MCPHome.jsp example, 276
![Page 597: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/597.jpg)
<jsp:forward> action578
SamsHome.jsp example,275-276
syntax, 274UseForward.jsp example,
274-275<jsp:getProperty> action, 240,
264<jsp:include> action, 240
attributes, 269EmployeeInfo.jsp example
code listing, 270-271jspService() method,
272-273header.jsp example, 269syntax, 269
<jsp:param> action, 241,268-269
<jsp:plugin> action, 241,278-279
<jsp:setProperty> action, 240,263-264
<jsp:useBean> action, 240attributes, 262-263scope values, 267-268syntax, 262
K-Lkeys, primary, 193, 209-210
Lang library, 408abort() method, 548abs() method, 548characterSet() method, 548exit() method, 548float() method, 548isFloat() method, 549isInt() method, 549max() method, 549maxInt() method, 549min() method, 549minInt() method, 549parseFloat() method, 549parseInt() method, 549
random() method, 550seed() method, 550
language= attribute (page directive), 238
LDAP (Lightweight DirectoryAccess Protocol) clients, 348
controllersLDAPDelete service,
359-360LDAPDirectory service,
356-357LDAPInsert service,
358-359deleting directory objects,
359-360displaying directory server
contents, 352-353home page, 351-352HTML form, 354-355inserting directory objects,
358-359models, 348navigation, 350-351running, 360-361searching directory server,
356-357title bar, 349-350views
Add, 354-355Directory, 352-353Directory Layout, 349-351Index, 351-352
LDAP (Lightweight DirectoryAccess Protocol) servers,165-166
accessing from servletsLDAPInsertData class,
184-186LDAPTestServlet example,
186-188adding objects to, 174-176connecting to
binding, 169-170Context class, 168-170DirContext class, 170
modifying information inADD_ATTRIBUTE
operator, 177LDAPManager class,
178-184REMOVE_ATTRIBUTE
operator, 177REPLACE_ATTRIBUTE
operator, 177removing objects from, 176searching, 170-174
client code, 173LDAPObject container
object, 172sample code listing,
170-171scope, 170search base, 170
LDAPDelete service, 359-360LDAPDirectory service, 356-357LDAPInsert service, 358-359LDAPInsertData class, 184-186LDAPManager class, 178-184LDAPObject container object,
172LDAPTestServlet, 186-188length() method, 552libraries
Dialogs, 557Float, 550-551Lang
abort() method, 548abs() method, 548characterSet() method,
548exit() method, 548float() method, 548isFloat() method, 549isInt() method, 549max() method, 549maxInt() method, 549min() method, 549minInt() method, 549parseFloat() method, 549parseInt() method, 549random() method, 550seed() method, 550
![Page 598: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/598.jpg)
listings579
StringcharAt() method, 551compare() method, 551elementAt() method, 551elements() method, 552find() method, 552format() method, 552insertAt() method, 552isEmpty() method, 552length() method, 552removeAt() method, 552replace() method, 553replaceAt() method, 553squeeze() method, 553subString() method, 553toString() method, 553trim() method, 553
tag librariestag handlers, 304taglib directive, 304-306tld files, 302-304
URL, 553-555WMLBrowser, 556WMLScript, 408-409
libraryPrefix field (Tag interface), 515
life cyclesentity beans, 217-218servlets
destroy() method, 27init() method, 26service() method, 26-27
session beans, 205-206Lightweight Directory Access
Protocol. See LDAP clients;LDAP servers
listingsApplicationBean1.jsp, 289ApplicationBean2.jsp,
289-290BasicServlet.java, 27-29BeanCounter.jsp, 265-266CalculateLoan bean
CalculateLoan.java, 195CalculateLoanBean.java,
198-200
CalculateLoanHome.java,196-197
ejb-jar.xml file, 203remote interface, 195
Catalog applicationAddToCart.java, 341-342CatalogConnectionPool,
323-325CheckOut.java, 344CheckOut.jsp, 338EmptyCart.java, 343index.jsp, 333ListMovies.java, 339, 341ListMovies.jsp, 334-335ListShoppingCart.jsp,
335-336navigation.jsp, 330-332ShoppingCart.java,
325-328titlebar.jsp, 329
ConnectionPool.java, 112-118ConnectionPoolServlet.java,
123-125Controller.java, 226-229CookieServlet.java, 47-49Counter.java, 264-265, 282CreateTablesApp.java, 95-97EJBTestServlet.java, 221-224EmployeeInfo.jsp, 270-271errorpage.jsp, 294-295ExampleService.java, 230-231ExampleView.java, 231Form.html, 36-37FormServlet.java, 34-37GetFromApplication.jsp,
255-256header.jsp, 269HelloAttributeTag
HelloAttribute.jsp,316-317
HelloAttributeTag.java,315-316
HelloBodyTagHelloBody.jsp, 314HelloBodyTag.java,
312-313, 316-317
HelloTagHello.jsp, 310HelloTag.java, 308taglib.tld, 309
helloworld WML card, 399HelloWorld! servlet, 413HiddenFieldServlet.java,
43-45HtmlSessionServlet.html,
54-55HttpSessionServlet.java, 52-54InsertDataApp.java, 98-103item.xml, 152LDAP client application
directory.jsp, 352-353index.jsp, 352insert.jsp, 354-355LDAPDelete.java, 359-360LDAPDirectory.java, 357LDAPInsert.java, 358-359navigation.jsp, 350-351titlebar.jsp, 350
LDAPInsert.java, 184-186LDAPManager.java, 178-184LDAPObject.java, 172LDAPTestServlet.java,
187-188LoginScreen.html, 146-147MailForm.html, 137-140MailServlet.html, 138-140MCPHome.jsp, 276Order.java, 73-79OrderStatusApplet.html, 80OrderStatusApplet.java, 75-79OrderStatusServlet.java, 81-82PageBean.jsp, 283PooledConnection.java,
120-121Quote bean
Quote.java, 207QuoteBean.java, 211-215QuoteHome.java, 208-209QuotePk.java, 209-210
RequestBean1.jsp, 284-285RequestBean2.jsp, 285RollYourOwnSecurityServlet,
144-147
![Page 599: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/599.jpg)
listings580
SamsHome.jsp, 275-276SAXHandler.java, 155, 157SelectDataApp.java, 101-103Service.java, 229-231SessionBean1.jsp, 287SessionBean2.jsp, 287SimpleSendMessage.java,
134-135stock trading application
Buy.java, 377-379GetQuote.java, 375-377getquote.jsp, 371-372index.jsp, 371navigation.jsp, 369-370Sell.java, 380-382titlebar.jsp, 368-369tradeform.jsp, 374-375TraderConnectionPool,
365-367StoreInApplication.jsp,
254-255StudentList.java, 61StudentListApplication.java,
62-64StudentListTunnelApp.java,
66-69StudentListTunnelServlet,
72-73testerror.jsp, 297TitleListGlobalPooledServlet.
java, 127-130TitleListServlet.java, 107-110UpdateDataApp.java, 105-106URLRewritingServlet, 50-51UseForward.jsp, 275UseOut.jsp, 258UseRequest.jsp, 250UseSession.jsp, 252WMLExample.wml, 402-403XMLServlet.java, 159-161XMLTest.java, 153-157,
160-161WMLScriptExample.wml,
410-411WMLScriptExample.wmls,
409-411
ListMovies service, 338-341lists, movie catalog application,
334-335, 338-341loading JDBC (Java Database
Connectivity) drivers, 94loadString() method, 555loan payments, calculating.
See CalculateLoan beanlog() method, 437-438, 451logical operators, 407login screens, 146-148LoginScreen.html, 146-148long parameter
print() method, 496println() method, 499
Mmail. See e-mailmail.jar file, 133MailForm.html (code listing),
137-138MailServlet, 138-141max() method, 549maxFloat() method, 550maxInt() method, 549MCPHome JSP (JavaServer
Page), 276messages (e-mail), sending
HTML mail forms, 137-138MailServlet example, 138-141SimpleSendMessage program,
133-137<meta> tag, 544method ready state (session
beans), 205method-ready pool state
(session beans), 205methods
abort(), 548abs(), 548actionPerformed(), 79add(), 358addCookie(), 473alert(), 557
BodyContent(), 522BodyTagSupport(), 523calcMonthlyPayment(), 196,
200ceil(), 550characters(), 157characterSet(), 548charAt(), 551clear(), 500clearBody(), 522clearBuffer(), 500clone(), 483close(), 501compare(), 551confirm(), 557containsHeader(), 473Cookie(), 480create(), 196createStatement(), 94destroy(), 20, 27, 125-126,
433, 449doAfterBody(), 311, 516,
521-523doBeforeBody(), 516doDelete(), 484doEndTag(), 307, 517,
523-525doGet(), 484
BasicServlet example,30-31
HiddenFieldServlet, 43doInitBody(), 311, 521, 524doOptions(), 485doPost(), 121-122, 484
BasicServlet example,30-31
HiddenFieldServlet, 43doPut(), 484doStartTag(), 307, 517,
524-526doTrace(), 485ejbActivate(), 206ejbCreate(), 197-198, 211ejbFind(), 211ejbLoad(), 215, 218ejbPassivate(), 206
![Page 600: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/600.jpg)
methods581
ejbPostCreate(), 211ejbStore(), 215, 218elementAt(), 551elements(), 552emptyPool(), 122encodeRedirectURL(), 51, 474encodeURL(), 473endElement(), 157-158escapeString(), 554execute(), 229executeQuery(), 103executeUpdate(), 97, 101exit(), 548find(), 552findAncestorWithClass(), 517,
526findAttribute(), 504findByName(), 208findByPrimaryKey(), 208, 217float(), 548floor(), 550flush(), 500flushBuffer(), 446format(), 552forName(), 94forward(), 229, 431, 504-505GenericServlet(), 449GET, 34-36getAttrib(), 439getAttribute(), 51, 125, 440,
476, 505, 531getAttributeName(), 476getAttributeNames(), 439-440getAttributeNamesInScope(),
505-506getAttributes(), 535getAttributesScope(), 506getAttributeString(), 531getAuthType(), 463getBase(), 554getBodyContent(), 524, 535getBodyOut(), 518getBufferSize(), 446, 501getCharacterEncoding(), 440,
446getClassName(), 541
getComment(), 480getConnection(), 94, 121, 127getContentLength(), 441getContentType(), 441getContext(), 435getContextPath(), 463getCookies(), 463getCreationTime(), 477getCurrentCard(), 556getCurrentInterestRate(), 200getDateHeader(), 463getDeclare(), 541getDefaultFactory(), 493getDomain(), 480getEngineInfo(), 494getException(), 506getFragment(), 554getHeader(), 464getHeaderNames(), 464getHeaders(), 464getHost(), 554getId(), 477, 526, 531getIdAttribute(), 529getImplementationVersion(),
492getInfoString(), 535, 538getInitParameter(), 434-435,
449getInitParameterNames(),
434-435, 449getInputStream(), 441getIntHeader(), 464getLastAccessedTime(), 477getLibraryPrefix(), 518getLocale(), 441, 446getLocales(), 442getMajorVersion(), 435getMaxAge(), 481getMaxIntervalTime(), 477getMethod(), 465getMimeType(), 436getMinorVersion(), 436getModifiedTime(), 485getName(), 482, 487, 529getNamedDispatcher(), 436getOut(), 506
getOutputStream(), 446-447getPage(), 506getPageContext(), 299,
493-494, 518getParameter(), 34, 442getParameterNames(), 34, 442getParameterValues(), 34, 442getParameters(), 554getParent(), 518, 526getPath(), 481, 554getPathInfo(), 465getPathTranslated(), 465getPort(), 555getPrefixString(), 538getPreviousOut(), 518, 524getProtocol(), 443getQuery(), 555getQueryString(), 465getReader(), 444, 522getRealPath(), 438getReferer(), 555getReliableURN(), 538getRemaining(), 501getRemoteAddress(), 444getRemoteHost(), 444getRemoteUser(), 466getRequest(), 507getRequestDispatcher(), 437,
443getRequestedSessionId(), 466getRequestURI(), 466getRequestURL(), 488getRequiredVersion(), 538getResource(), 436-437getResourceAsStream(), 437getResponse(), 507getRootCause(), 458getScheme(), 443, 555getScope(), 541getSecure(), 482getServerInfo(), 438getServerName(), 443getServerPort(), 444getServletConfig(), 432, 450,
507getServletContext(), 433, 450,
507
![Page 601: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/601.jpg)
methods582
getServletInfo(), 31, 433, 450getServletName(), 434getServletPath(), 466getSession(), 56, 467, 487,
507getShortName(), 539getString(), 522getStudentList(), 65getTable(), 158getTag(), 539getTagClassName(), 536getTagData(), 519getTagExtraInfo(), 536getTagID(), 519getTagInfo(), 532getTagLibrary(), 536getTagName(), 519, 536getTags(), 539getTypeName(), 530getUnavailableSeconds(), 459getURI(), 539getUserPrincipal(), 466getValue(), 482, 519, 527getValues(), 527getVar(), 556getVariableInfo(), 532, 536getVarName(), 541getVersion(), 483getWriter(), 30, 447go(), 556handlePageException(), 300,
508HttpServlet(), 483HttpSessionBindingEvent(),
487HttpUtils(), 487include(), 431, 508init(), 26, 432, 450-451
BasicServlet example, 30ConnectionPool object,
119ConnectionPoolServlet,
125initialize(), 509, 520initializePool(), 119-120insertAt(), 552
int(), 550invalidate(), 477isAutoFlush(), 502isCommitted(), 447isEmpty(), 552isFloat(), 549isInt(), 549isNew(), 478isPermanent(), 459isRequestedSessionFrom
Cookie(), 467isRequestedSessionIdFrom-
URL(), 468isRequestedSessionValid(),
467isSecure(), 445isValid(), 533, 537, 555jspDestroy() method, 491JspEngineInfo(), 492JspError(), 512JspException, 512JspFactory(), 493jspInit() method, 491jspservice(), 248-249,
272-273, 491JspWriter(), 495length(), 552loadString(), 555log(), 437-438, 451max(), 549maxFloat(), 550maxInt(), 549min(), 549minFloat(), 551minInt(), 549narrow(), 204newContext(), 556newInstance(), 155newLine(), 495newSAXParser(), 155next(), 104openConnection(), 69PageContext(), 504parse(), 155parseFloat(), 549parseInt(), 549
parsePostData(), 488parseQueryString(), 488popBody(), 509POST, 36-38pow(), 551prev(), 556print(), 453-454, 495-498println(), 455-456, 498-500prompt(), 557pushBody(), 510putStudentList(), 64-65random(), 550readLine(), 452readOrder(), 79readStudentList(), 70-71refresh(), 556release(), 307, 510, 520, 524,
527releaseConnection(), 122, 127releasePageContext(), 494remove(), 359removeAt(), 552removeAttribute(), 52, 439,
445, 478, 510removeValue(), 527replace(), 553replaceAt(), 553reset(), 447resolve(), 555round(), 551seed(), 550sendError(), 474sendRedirect(), 51, 475service(), 20-22, 26-27,
432-433, 451-452, 485-486ServletException(), 457ServletInputStream(), 452ServletOutputStream(), 453setAttribute(), 51, 126, 439,
445, 478, 511, 531setBodyContent(), 311, 521,
525setBodyOut(), 520setBufferSize(), 447setComment(), 480setContentLength(), 448
![Page 602: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/602.jpg)
native-protocol drivers583
setContentType(), 448setDateHeader(), 475setDefaultFactory(), 493setDomain(), 480setId(), 527setIntHeader(), 475setLocale(), 448setMaxAge(), 481setMaxIntervalTime(), 478setPageContext(), 307, 528setParent(), 307, 528setPath(), 481setSecure(), 482setStatus(), 476setTagInfo(), 533setValue(), 482, 520, 528-529setVar(), 556setVersion(), 483sqrt(), 551squeeze(), 553startElement(), 157subString(), 553Tag(), 516TagData(), 530TagExtraInfo(), 532TagInfo(), 534-535TagLibraryInfo(), 538TagSupport(), 525toString(), 553trim(), 553UnavailableException(), 458unescapeString(), 555valueBound(), 479valueUnBound(), 479VariableInfo(), 540writeOrder(), 79writeOut(), 523writeStudentList(), 70
Microsoft ASPs (Active ServerPages), 18
MIME types, 412-413MimeMessage class, 136-137min() method, 549minFloat() method, 551minInt() method, 549
Model class, 8Model View Controller design
pattern. See MVC design pattern
modelsdatabase access models, 86-87LDAP (Lightweight Directory
Access Protocol) client, 348stock trading application,
364-367modifying LDAP (Lightweight
Directory Access Protocol)server information
ADD_ATTRIBUTE operator,177
LDAPManager class, 178-184REMOVE_ATTRIBUTE
operator, 177REPLACE_ATTRIBUTE
operator, 177movie catalog application
ConnectionPool, 323-325controllers, 338
AddToCart service,341-342
CheckOut service,343-344
EmptyCart service, 343ListMovies service,
338-341index, 332-333listing movies, 334-335,
338-341Movie object, 322-323requirements, 322shopping cart
adding items to, 341-342checking out, 336-338,
343-344displaying contents of,
335-336emptying, 343source code listing,
325-328testing, 344-345
title bar, 329views
catalog layout, 328-332Check Out, 336, 338Index, 332-333Movie List, 334-335Shopping Cart, 335-336
movie list (movie catalog application), 334-335, 338-341
Movie List view (movie catalogapplication), 334-335
Movie object, 322-323multiple device support, 414MVC (Model View Controller)
design patternclasses, 8server-side implementation, 8
advantages, 9JSPs as Views, 10servlets as MVC
Controllers, 9-10step-by-step process, 9
Nname attribute
<jsp:getProperty> action, 264<jsp:param action>, 269<jsp:setProperty action>, 263
name field (TagAttributeInfoclass), 528
name subelement (<tag> tag),303
namesDNs (distinguished names),
165EJB (Enterprise JavaBeans),
193file extension, 412
narrow() method, 204native-API drivers, 88, 90native-protocol drivers, 90-91
![Page 603: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/603.jpg)
navigation584
navigationLDAP (Lightweight Directory
Access Protocol) client,350-351
stock trading application,369-370
NESTED field (VariableInfoclass), 540
Netscape Directory Server,167-168
newContext() method, 556newInstance() method, 155newLine() method, 495newSAXParser() method, 155next() method, 104nonces, 149<noop> tag, 544NO_BUFFER field (JspWriter
class), 495
OobjectClass attribute, 174objects
adding to LDAP (LightweightDirectory Access Protocol)servers, 174-176
Attribute, 174bean, 193ConnectionPool
code listing, 112-118initializing, 118-120requirements, 112
deleting from directory server,359-360
implicit, 241-242, 248-249application, 254-256config, 258-259exception, 260out, 257-258page, 260pageContext, 251request, 249-250response, 250session, 252-253
inserting into directory server,358-359
LDAPObject, 172Movie, 322-323Order, 73-74People, 348PooledConnection, 120-121removing from LDAP
(Lightweight DirectoryAccess Protocol) servers,176
serializedcreating, 60enabling, 60reading, 60StudentList example, 61StudentListApplication
example, 61-66ServletContext, 254-255ServletRequest, 21ServletResponse, 21Statement, 94stock, 364-365storing in ServletContexts,
254-255StudentList, 61
OBJECT_SCOPE searches(LDAP), 170
ODBC (Open DatabaseConnectivity) data sources,92-93
ONELEVEL_SCOPE searches(LDAP), 170
<onevent> tag, 400-401, 544online directory application,
348controllers
LDAPDelete service,359-360
LDAPDirectory service,356-357
LDAPInsert service,358-359
running, 360-361deleting directory objects,
359-360
displaying directory servercontents, 352-353
home page, 351-352HTML form, 354-355inserting directory objects,
358-359models, 348navigation, 350-351searching directory server,
356-357title bar, 349-350views
Add, 354-355Directory, 352-353Directory Layout, 349-351Index, 351
online emulators, WAP(Wireless ApplicationProtocol), 392-394
openConnection() method, 69Open Database Connectivity
(ODBC) data sources, 92-93operators
ADD_ATTRIBUTE, 177REMOVE_ATTRIBUTE, 177REPLACE_ATTRIBUTE, 177WMLScript, 407
<optgroup> tag, 545<option> tag, 400, 545Order object, 73-74OrderStatus tool
Order object, 73-74OrderStatusApplet, 74-80
actionPerformed() method, 79
code listing, 74-79HTML file, 79-80readOrder() method, 79writeOrder() method, 79
OrderStatusServlet, 80-83OrderStatusApplet, 74-80
actionPerformed() method, 79code listing, 74-79HTML file, 79-80readOrder() method, 79writeOrder() method, 79
![Page 604: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/604.jpg)
PageContext class585
OrderStatusServlet, 80-83OUT field (PageContext class),
503out object, 241, 257-258output streams,
ServletOutputStream class,452
print() method, 453-454println() method, 455-456ServletOutputStream()
method, 453
P<p> tag, 399, 545packages
javax.servlet, 20, 429-430GenericServlet class,
449-452RequestDispatcher
interface, 431Servlet interface, 432-433ServletConfig interface,
433-434ServletContext interface,
434-439ServletException class,
456-458ServletInputStream class,
452ServletOutputStream class,
452-456ServletRequest interface,
440-445ServletResponse interface,
445-448SingleThreadModel
interface, 448UnavailableException
class, 458-459javax.servlet.http, 20
Cookie class, 479-483HttpServlet class, 483-486HttpServletRequest
interface, 462-468
HttpServletResponseinterface, 468-476
HttpSession interface,476-478
HttpSessionBindingEventclass, 486-487
HttpSessionBindingListener interface, 479
HttpUtils class, 487-488javax.servlet.jsp
HttpJspPage interface,490-491
JspEngineInfo class, 492JSPError exception, 512JSPException exception,
512JspFactory class, 492-494JspPage interface, 491JspWriter class, 494-502PageContext class,
502-511javax.servlet.jsp.tagext
BodyContent class,522-523
BodyTag interface,520-521
BodyTagSupport class,523-525
Tag interface, 514-520TagAttributeInfo class,
528-530TagData class, 530-531TagExtraInfo class,
532-533TagInfo class, 533-537TagLibraryInfo class,
537-539TagSupport class, 525-528VariableInfo class,
539-541packaging jar files, 218-219page attribute
<jsp:forward> action, 274<jsp:include> action, 269
page directive, 238-239
PAGE field (PageContext class),503
page object, 241, 260page scope (<jsp:useBean>
action), 267page scope (JavaBeans), 283PageBean.jsp (code listing), 283pageContent object, 241PageContext class, 251, 502
fieldsAPPLICATION, 502APPLICATION_SCOPE,
502CONFIG, 503EXCEPTION, 503OUT, 503PAGE, 503PAGECONTEXT, 503PAGE_SCOPE, 503REQUEST, 503REQUEST_SCOPE, 503RESPONSE, 504SESSION, 504SESSION_SCOPE, 504
methodsfindAttribute(), 504forward(), 504-505getAttribute(), 505getAttributeNamesIn-
Scope(), 505-506getAttributesScope(), 506getException(), 506getOut(), 506getPage(), 506getRequest(), 507getResponse(), 507getServletConfig(), 507getServletContext(), 507getSession(), 507handlePageException(),
508include(), 508initialize(), 509PageContext(), 504popBody(), 509pushBody(), 510
![Page 605: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/605.jpg)
PageContext class586
release(), 510removeAttribute(), 510setAttribute(), 511
pageContext fieldPageContext class, 503Tag interface, 515TagSupport class, 525
PageContext() method, 504PAGE_SCOPE field
(PageContext class), 503param action. See <jsp:param>
actionparam attribute
(<jsp:setProperty> action),264
parent field (Tag interface), 515parse() method, 155parseFloat() method, 549parseInt() method, 549parsePostData() method, 488parseQueryString() method, 488parser.jar file, 153parsing XML (Entensible
Markup Language) files,153-155
passivation, 205-206passwords, ID/password
security modelLoginScreen.html, 146-148RollYourOwnSecurityServlet,
144-146patterns. See design patternsPDAs (Personal Digital
Assistants), 394People object, 348persistence
entity beans, 206-207LDAP (Lightweight Directory
Access Protocol). See LDAPservers
servlets, 19sessions. See session tracking
plugin action. See <jsp:plugin>action
PooledConnection object,120-121
pooling (instance), 205popBody() method, 509portability of servlets, 19<postfield> tag, 545pow() method, 551<pre> tag, 545prefix attribute (taglib
directive), 240prefix field (TagLibraryInfo
class), 537preloading servlets, 126<prev> tag, 400, 545prev() method, 556previous card (WMLExample),
405previousOut field (Tag
interface), 515primary keys, 193, 209-210print() method, 453-454,
495-498println() method, 455-456,
498-500processing instructions (XML),
152program listings. See listingsprompt() method, 557properties of JavaBeans,
263-264property attribute
<jsp:getProperty> action, 264<jsp:setProperty> action, 263
proprietary APIs (applicationprogramming interfaces), 18
protocolsHTTP (Hypertext Transport
Protocol). See HTTPLDAP (Lightweight Directory
Access Protocol). See LDAPclients; LDAP servers
SSL (Secure Sockets Layer),149-150
stateless, 42WAP (Wireless Application
Protocol)application servers, 395architecture, 391-392
bandwidth considerations,390
developer tools, 394emulators, 392-394future of, 387-388history and development,
386-387network considerations,
390online resources, 395-396PDA WAP browsers, 394screen size considerations,
389-390version 1.2, 388WinWAP browser, 392,
394WDP (Wireless Datagram
Protocol), 391WTP (Wireless Transaction
Protocol), 391pushBody() method, 510putStudentList() method, 64-65
Q-RQuote bean
bean class, 211-215home interface, 208-209primary key class, 209-210remote interface, 207
random() method, 550reading serialized objects, 60readLine() method, 452readOrder() method, 79readStudentList() method,
70-71ready state (entity beans), 218reentrance, 216<reentrant> tag, 216referencing JavaABeans, 264<refresh> tag, 400, 545refresh() method, 556regTime field (TagAttributeInfo
class), 529
![Page 606: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/606.jpg)
response object587
relational databases, 164release() method, 307, 510, 520,
524, 527releaseConnection() method,
122, 127releasePageContext() method,
494remote interfaces
defined, 192entity beans, 207-208session beans, 195-196
<remote> tag, 201remove() method, 359removeAt() method, 552removeAttribute() method, 52,
439, 445, 478, 510removeValue() method, 527REMOVE_ATTRIBUTE
operator, 177removing objects from LDAP
(Lightweight Directory AccessProtocol) servers, 176
replace() method, 553replaceAt() method, 553REPLACE_ATTRIBUTE
operator, 177REQUEST field (PageContext
class), 503request object, 241, 249-250request scope (JavaBeans), 268,
284-286request time errors, 294RequestBean1.jsp (code listing),
284-285RequestBean2.jsp (code listing),
285RequestDispatcher interface,
431requests
forwarding, 277-278<jsp:forward> action, 274MCPHome.jsp, 276SamsHome.jsp, 275-276UseForward.jsp, 274-275
GenericServlet, 21HttpServlet, 22
HttpServletRequest interface,462
getAuthType() method,463
getContextPath() method,463
getCookies() method, 463getDateHeader() method,
463getHeader() method, 464getHeaderNames()
method, 464getHeaders() method, 464getIntHeader() method,
464getMethod() method, 465getPathInfo() method, 465getPathTranslated()
method, 465getQueryString() method,
465getRemoteUser() method,
466getRequestedSessionId()
method, 466getRequestURI() method,
466getServletPath() method,
466getSession() method, 467getUserPrincipal()
method, 466isRequestedSessionFrom-
Cookie() method, 467isRequestedSessionIdFrom-
URL() method, 468isRequestedSessionValid()
method, 467request object, 241, 249-250RequestDispatcher interface,
431ServletRequest interface,
440-445getAttribute() method, 440getAttributeNames()
method, 440
getCharacterEncoding()method, 440
getContentLength()method, 441
getContentType() method,441
getInputStream() method,441
getLocale() method, 441getLocales() method, 442getParameter() method,
34, 442getParameterName()
method, 34getParameterNames()
method, 442getParameterValues()
method, 34, 442getProtocol() method, 443getReader() method, 444getRemoteAddress()
method, 444getRemoteHost() method,
444getRequestDispatcher()
method, 443getScheme() method, 443getServerName() method,
443getServerPort() method,
444isSecure() method, 445removeAttribute() method,
445setAttribute() method, 445
REQUEST_SCOPE field(PageContext class), 503
REQUEST_TIME_VALUE field(TagData class), 530
reset() method, 447resolve() method, 555RESPONSE field (PageContext
class), 504response object, 242, 250
![Page 607: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/607.jpg)
responses588
responsesHttpServletResponse interface
fields, 468-473methods, 473-476
response object, 242, 250ServletResponse interface,
445flushBuffer() method, 446getBufferSize() method,
446getCharacterEncoding()
method, 446getLocale() method, 446getOutputStream() method,
446-447getWriter() method, 447isCommitted() method,
447reset() method, 447setBufferSize() method,
447setContentLength()
method, 448setContentType() method,
448setLocale() method, 448
retrieving form data, 34FormServlet example, 34-39GET method, 34-36getParameter() method, 34getParameterNames()
method, 34getParameterValues()
method, 34POST method, 36-38
rewriting URLs (UniformResource Locators), 50-51
robustness of servlets, 19RollYourOwnSecurityServlet,
144-146round() method, 551running
LDAP (Lightweight DirectoryAccess Protocol) client,360-361
stock trading application,382-383
SSamsHome JSP (JavaServer
Page), 275-276SAX API (Simple API for
XML)SAXHandler.java handler,
155-159XMLTest.java document,
153-155SAXHandler.java handler, 155,
157, 159scope
application object, 254JavaBeans
application, 289-291page, 283request, 284-286session, 286-288
<JSP:useBean> action,267-268
LDAP (Lightweight DirectoryAccess Protocol) searches,170
scope attribute (<jsp:useBean>action), 263
scope field (VariableInfo class),540
scriptingdeclarations, 242-243expressions, 243-244scriplets
HELLO JSP WORLDexample, 245-246
syntax, 244WMLScript, 405
calling, 406Dialogs library, 557Float library, 550-551Lang library, 548-550operators, 407standard libraries,
408-409statements, 407-408String library, 551-553syntax, 406
URL library, 553-555WMLBrowser library, 556WMLScriptExample
application, 409-411scriptlets
HELLO JSP WORLD example, 245-246
syntax, 244SC_ACCEPTED field
(HttpServletResponse), 469SC_BAD_GATEWAY field
(HttpServletResponse), 472SC_BAD_REQUEST field
(HttpServletResponse), 470SC_CONFLICT field
(HttpServletResponse), 471SC_CONTINUE field
(HttpServletResponse), 468SC_CREATED field
(HttpServletResponse), 468SC_FORBIDDEN field
(HttpServletResponse), 470SC_GATEWAY_TIMEOUT
field (HttpServletResponse),473
SC_GONE field(HttpServletResponse), 471
SC_HTTP_VERSION_NOT_SUPPORTED field(HttpServletResponse), 473
SC_INTERNAL_SERVER_ERROR field(HttpServletResponse), 472
SC_LENGTH_REQUIREDfield (HttpServletResponse),472
SC_MOVED_PERMANENTLYfield (HttpServletResponse),469
SC_MOVED_TEMPORARILYfield (HttpServletResponse),469
SC_MULTIPLE_CHOICESfield (HttpServletResponse),469
![Page 608: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/608.jpg)
servers589
SC_NON_AUTHORITATIVE_INFORMATION field(HttpServletResponse), 469
SC_NOT_ACCEPTABLE field(HttpServletResponse), 471
SC_NOT_ALLOWED field(HttpServletResponse), 471
SC_NOT_FOUND field(HttpServletResponse), 471
SC_NOT_IMPLEMENTEDfield (HttpServletResponse),472
SC_NOT_MODIFIED field(HttpServletResponse), 470
SC_NO_CONTENT field(HttpServletResponse), 469
SC_OK field(HttpServletResponse), 468
SC_PARTIAL_CONTENT field(HttpServletResponse), 469
SC_PAYMENT_REQUIREDfield (HttpServletResponse),470
SC_PRECONDITION_FAILEDfield (HttpServletResponse),472
SC_PROXY_AUTHENTICATION_REQUIRED field(HttpServletResponse), 471
SC_REQUEST_ENTITY_TOO_LARGE field(HttpServletResponse), 472
SC_REQUEST_TIMEOUTfield (HttpServletResponse),471
SC_REQUEST_URI_TOO_LONG field(HttpServletResponse), 472
SC_RESET_CONTENT field(HttpServletResponse), 469
SC_SEE_OTHER field(HttpServletResponse), 470
SC_SERVICE_UNAVAILABLEfield (HttpServletResponse),473
SC_SWITCHING_PROTOCOLS field(HttpServletResponse), 468
SC_UNAUTHORIZED field(HttpServletResponse), 470
SC_UNSUPPORTED_MEDIA_TYPE field(HttpServletResponse), 472
SC_USE_PROXY field(HttpServletResponse), 470
searching LDAP (LightweightDirectory Access Protocol)servers, 170-174, 356-357
client code, 173LDAPObject container object,
172sample code listing, 170-171scope, 170search base, 170
Secure Sockets Layer (SSL),149-150
securitybasic authentication, 148digest authentication, 148-149ID/password combinations
LoginScreen.html,146-148
RollYourOwnSecurityServlet, 144-146
servlets, 20SSL (Secure Sockets Layer),
149-150seed() method, 550select card (WMLExample),
405SELECT statement (SQL),
101-104<select> tag, 400-401, 545selecting table data, 101-105Sell service (stock trading
application), 380-382selling stock (stock trading
application), 380-382sendError() method, 474
sending e-mail messages(JavaMail)
HTML mail forms, 137-138MailServlet example, 138-141SimpleSendMessage example,
133-137sendRedirect() method, 51, 475serialized objects
creating, 60enabling, 60reading, 60StudentList example, 61StudentListApplication
example, 61-66server pages. See JSPs
(JavaServer Pages)server-side Java, 16server-side JavaScript, 18server-side MVC (Model View
Controller) implementationadvantages, 9JSPs as Views, 10servlets as MVC Controllers,
9-10step-by-step process, 9
server.xml file, 424, 426servers
application servers, 191,218-220, 395
LDAP (Lightweight DirectoryAccess Protocol), 165-166
accessing from servlets,184-188
adding objects to, 174-176connecting to, 168-170modifying information in,
177-184removing objects from,
176searching, 170-174
MIME types, 412-413Netscape Directory Server,
167-168Tomcat
downloading, 422-423installing, 423-424server.xml file, 424-426
![Page 609: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/609.jpg)
Service interface590
Service interface, 229-230service() method, 20-22, 26-27,
432-433, 451-452, 485-486services
JavaMail, 132LDAP (Lightweight Directory
Access Protocol) clientLDAPDelete service,
359-360LDAPDirectory service,
356-357LDAPInsert service,
358-359movie catalog application
AddToCart, 341-342CheckOut, 343-344EmptyCart, 343ListMovies, 338-341
stock trading applicationBuy, 377-379GetQuote, 375-377Sell, 380-382
Servlet API, tracking sessionswith
getAttribute() method, 51HtmlSessionServlet example,
54-55HttpSessionServlet example,
52-54removeAttribute() method, 52setAttribute() method, 51Shopping Cart screen, 55-56Thank You screen, 57-58
Servlet interface, 20, 432-433ServletConfig interface, 433-434ServletContext class, 420ServletContext interface, 434
getAttrib() method, 439getAttributeNames() method,
439getContext() method, 435getInitParameter() method,
435getInitParameterNames()
method, 435getMajorVersion() method,
435
getMimeType() method, 436getMinorVersion() method,
436getNamedDispatcher()
method, 436getRealPath() method, 438getRequestDispatcher()
method, 437getResource() method,
436-437getResourceAsStream()
method, 437getServerInfo() method, 438log() method, 437-438removeAttribute() method,
439setAttribute() method, 439
ServletContext object, 254-255ServletException class, 456-458ServletException() method, 457ServletInputStream class, 452ServletInputStream() method,
452ServletOutputStream class, 452
print() method, 453-454println() method, 455-456ServletOutputStream()
method, 453ServletOutputStream() method,
453ServletRequest interface
getAttribute() method, 440getAttributeNames() method,
440getCharacterEncoding()
method, 440getContentLength() method,
441getContentType() method, 441getInputStream() method, 441getLocale() method, 441getLocales() method, 442getParameter() method, 34,
442getParameterName()
method, 34
getParameterNames() method,442
getParameterValues() method,34, 442
getProtocol() method, 443getReader() method, 444getRemoteAddress() method,
444getRemoteHost() method, 444getRequestDispatcher()
method, 443getScheme() method, 443getServerName() method, 443getServerPort() method, 444isSecure() method, 445removeAttribute() method,
445setAttribute() method, 445
ServletRequest object, 21ServletResponse interface, 445
flushBuffer() method, 446getBufferSize() method, 446getCharacterEncoding()
method, 446getLocale() method, 446getOutputStream() method,
446-447getWriter() method, 447isCommitted() method, 447reset() method, 447setBufferSize() method, 447setContentLength() method,
448setContentType() method, 448setLocale() method, 448
ServletResponse object, 21servlets. See also listings; Web
applicationsadvantages, 19-20alternatives to, 17-18architecture, 20-22BasicServlet example
compiling, 426doGet() method, 30-31doPost() method, 30-31getServletInfo()
method, 31
![Page 610: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/610.jpg)
sessions591
init() method, 30installing, 426-427servlet framework, 29source code listing, 27-29
CatalogConnectionPool,323-325
ConnectionPool, 365-367ConnectionPoolServlet
code listing, 123-125destroy() method, 125-126init() method, 125preloading, 126
Controllerscreating, 226-229defined, 226sample service, 230-232service interface, 229-230
CookieServlet, 47-49definition of, 16destroying, 27as EJB (Enterprise JavaBeans)
clients, 220-224EJBTestServlet, 221-224FormServlet example, 34-39HelloWorld!, 413-414HiddenFieldServlet, 43-46HtmlSessionServlet, 54-55HTTP tunneling, 71-73HttpSessionServlet, 52-54incorporating XML
(Extensible MarkupLanguage) into, 159-161
initializing, 26inter-servlet communications
ConnectionPoolServletexample, 123-126
TitleListGlobalPooledServlet example, 127-130
JSPs (JavaServer Pages). SeeJSPs
LDAPTestServlet , 186-188life cycle of, 26-27MailServlet, 138-141as MVC (Model View
Controller) Controllers, 9-10OrderStatusServlet, 80-83
packages. See packagesreal-world applications, 16-17retrieving form data in
FormServlet example,34-39
GET method, 34-36getParameter() method, 34getParameterNames()
method, 34getParameterValues()
method, 34POST method, 36-38
RollYourOwnSecurityServlet,144-146
securitybasic authentication, 148digest authentication,
148-149ID/password
combinations, 144-148SSL (Secure Sockets
Layer), 149-150Servlet interface, 20, 432-433StudentListTunnelServlet,
72-73TitleListGlobalPooledServlet,
127-130TitleListServlet, 107-111URLRewritingServlet, 50-51writing, 422XMLServlet, 159-161
session beans, 192-194bean class, 197-200client view of, 204deployment descriptors,
200-204home interface, 196-197lifecycle, 205-206passivation, 205-206remote interface, 195-196stateful, 194stateless, 194
Session class, 135-136SESSION field (PageContext
class), 504
session object, 242, 252-253session scope (JavaBeans), 268,
286-288session tracking, 42
cookiesCookie class, 47CookieServlet example,
47-49definition of, 46support for, 46
hidden form fieldsHiddenFieldServlet, 43-46sample HTML listing,
42-43HTTP authentication, 42Servlet API
getAttribute() method, 51HtmlSessionServlet
example, 54-55HttpSessionServlet
example, 52-54removeAttribute() method,
52setAttribute() method, 51Shopping Cart screen,
55-56Thank You screen, 57-58
URL (Uniform ResourceLocator) rewriting, 50-51
session-type tag, 201session= attribute (page
directive), 239SessionBean1.jsp (code listing),
287SessionBean2.jsp (code listing),
287sessions
HttpSession interfacegetAttribute() method, 476getAttributeName()
method, 476getCreationTime() method,
477getId() method, 477getLastAccessedTime()
method, 477
![Page 611: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/611.jpg)
sessions592
getMaxIntervalTime()method, 477
invalidate() method, 477isNew() method, 478removeAttribute() method,
478setAttribute() method, 478setMaxIntervalTime()
method, 478HttpSessionBindingEvent
class, 486-487HttpSessionBindingListener
interface, 479session object, 242, 252-253tracking
cookies, 46-49hidden form fields, 42-46HTTP authentication, 42Servlet API, 51-58URL (Uniform Resource
Locator) rewriting,50-51
SESSION_SCOPE field(PageContext class), 504
setAttribute() method, 51, 126,439, 445, 478, 511, 531
setBodyContent() method, 311,521, 525
setBodyOut() method, 520setBufferSize() method, 447setComment() method, 480setContentLength() method, 448setContentType() method, 448setDateHeader() method, 475setDefaultFactory() method, 493setDomain() method, 480setId() method, 527setIntHeader() method, 475setLocale() method, 448setMaxAge() method, 481setMaxIntervalTime() method,
478setPageContext() method, 307,
528setParent() method, 307, 528
setPath() method, 481setProperty action. See
<jsp:setProperty> actionsetSecure() method, 482setStatus() method, 476setTagInfo() method, 533setValue() method, 482, 520,
528-529setvar card (WMLExample),
404<setvar> tag, 545setVar() method, 556setVersion() method, 483Shopping Cart screen
(HttpSessionServlet), 55-56Shopping Cart view (movie
catalog application), 335-336shopping carts
adding items to, 341-342checking out, 336-338,
343-344displaying contents of,
335-336emptying, 343source code listing, 325-328
ShoppingCart class, 325-328Simple API for XML. See SAX
APISimpleSendMessage program,
133code listing, 134-135MimeMessage class, 136-137Session class, 135-136
SingleThreadModel interface,448
sites. See Web sitesSKIP_BODY field (Tag
interface), 515SKIP_PAGE field (Tag
interface), 515<small> tag, 545sockets, SSL (Secure Sockets
Layer), 149-150source code listings. See listings
SQL (Standard QueryLanguage) statements
CREATE, 95-97DELETE, 107INSERT, 97-101SELECT, 101-104UPDATE, 105-107
sqrt() method, 551squeeze() method, 553SSL (Secure Sockets Layer),
149-150standard actions, 240, 262
counter example, 264BeanCounter.jsp, 265-268Counter.java, 264-265
<jsp:forward>, 240attributes, 274MCPHome.jsp example,
276SamsHome.jsp example,
275-276syntax, 274UseForward.jsp example,
274-275<jsp:getProperty>, 240, 264<jsp:include>, 240
attributes, 269EmployeeInfo.jsp example,
270-273header.jsp example, 269syntax, 269
<jsp:param>, 241, 268-269<jsp:plugin>, 241, 278-279<jsp:setProperty>, 240,
263-264<jsp:useBean>, 240
attributes, 262-263scope values, 267-268syntax, 262
standard libraries. See librariesStandard Query Language.
See SQL statementsstartElement() method, 157state maintenance. See session
tracking
![Page 612: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/612.jpg)
Tag interface593
stateful session beans, 194,205-206
stateless protocols, 42stateless session beans, 194, 205Statement objects (JDBC), 94statements (SQL)
CREATE, 95-97DELETE, 107INSERT, 97-101SELECT, 101-104UPDATE, 105-107WMLScript, 407-408
stock object, 364-365stock quotes, getting (stock
trading application), 375-377stock trading application, 364
buying stock, 377-379ConnectionPool servlet,
365-367controllers
Buy service, 377-379GetQuote service, 375-377Sell service, 380-382
getting stock quotes, 371-372,375-377
home page, 370-371models, 364-367navigation, 369-370running, 382-383selling stock, 380-382stock object, 364-365title bar, 367, 369views
Buy/Sell, 372, 375Get Quote, 371-372Index, 370-371Trader Layout, 367-370
store front applications, 17store service (JavaMail), 132StoreInApplication servlet,
254-255storing objects in
ServletContexts, 254-255
streamsServletInputStream class, 452ServletOutputStream class,
452print() method, 453-454println() method, 455-456ServletOutputStream()
method, 453String library, 408
charAt() method, 551compare() method, 551elementAt() method, 551elements() method, 552find() method, 552format() method, 552insertAt() method, 552isEmpty() method, 552length() method, 552removeAt() method, 552replace() method, 553replaceAt() method, 553squeeze() method, 553subString() method, 553toString() method, 553trim() method, 553
<strong> tag, 545StudentList object, 61StudentListApplication, 61-66StudentListTunnelApp client
code listing, 66-69openConnection() method, 69readStudentList() method,
70-71writeStudentList() method, 70
StudentListTunnelServlet, 72-73subelements (<tag> tag),
303-304subString() method, 553SUBTREE_SCOPE searches
(LDAP), 170
T<table> tag, 545tables
creating, 95-97deleting data from, 107inserting data into, 97, 99-101selecting data in, 101-105updating, 105-107
tag handlers, 304Tag interface
fieldsbodyOut, 514EVAL_BODY, 515EVAL_PAGE, 515libraryPrefix, 515pageContext, 515parent, 515previousOut, 515SKIP_BODY, 515SKIP_PAGE, 515tagData, 515tagID, 516tagName, 516values, 516
methodsdoAfterBody(), 516doBeforeBody(), 516doEndTag(), 517doStartTag(), 517findAncestorWithClass(),
517getBodyOut(), 518getLibraryPrefix(), 518getPageContext(), 518getParent(), 518getPreviousOut(), 518getTagData(), 519getTagID(), 519getTagName(), 519getValue(), 519initialize(), 520release(), 520setBodyOut(), 520setValue(), 520Tag(), 516
![Page 613: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/613.jpg)
tag libraries594
tag librariestag handlers, 304taglib descriptors, 302-304taglib directive
adding to JSPs, 305-306adding to Web applica-
tions, 304-305tag library descriptor (tld) files,
302-304<tag> tag, 303-304Tag() method, 516TagAttributeInfo class
fields, 528-529method, 529-530
tagclass subelement (<tag> tag),303
tagClassName field (TagInfoclass), 534
TagData class, 530-531tagData field (Tag interface),
515TagData() method, 530TagExtraInfo class, 532-533tagExtraInfo field (TagInfo
class), 534TagExtraInfo() method, 532tagID field (Tag interface), 516TagInfo class
fields, 533-534methods
getAttributes(), 535getBodyContent(), 535getInfoString(), 535getTagClassName(), 536getTagExtraInfo(), 536getTagLibrary(), 536getTagName(), 536getVariableInfo(), 536isValid(), 537TagInfo(), 534-535
tagInfo field (TagInfo class), 532TagInfo() method, 534-535taglib directive
adding to JSPs, 305-306adding to Web applications,
304-305attributes, 240
<taglib> tagadding to JSPs, 305-306adding to Web applications,
304-305taglib.tld, 309tagLibrary field (TagInfo class),
534TagLibraryInfo class
fields, 537methods, 538-539
TagLibraryInfo() method, 538tagName field (
Tag interface, 516TagInfo class, 534
tags<a>, 400, 544<access>, 544<anchor>, 400, 544<b>, 399, 544<big>, 399, 544<br>, 399-400, 544<card>, 401, 544custom tags
attributes, 314-317deploying, 302-306example, 302tags with bodies, 311-314tags without bodies,
306-311<do>, 544<ejb-class>, 201<ejb-jar>, 201<ejb-name>, 201<em>, 544<enterprise-beans>, 201<entity>, 216<fieldset>, 544<go>, 400, 544<head>, 544<home>, 201<i>, 399<img>, 544<input>, 400, 544<italic>, 544<meta>, 544<noop>, 544
<onevent>, 400-401, 544<optgroup>, 545<option>, 400, 545<p>, 399, 545<postfield>, 545<pre>, 545<prev>, 400, 545<refresh>, 400, 545<reentrant>, 216<remote>, 201<select>, 400-401, 545<session-type>, 201<setvar>, 545<small>, 545<strong>, 545<table>, 545<tag>, 303-304tag libraries
tag handlers, 304taglib directive, 304-306tld files, 302-304
<taglib>adding to JSPs, 305-306adding to Web
applications, 304-305<td>, 545<template>, 545<timer>, 401, 545<tr>, 545<transaction-type>, 201<u>, 399, 545<wml>, 545
TagSupport class, 307fields, 525methods
doEndTag(), 525doStartTag(), 526findAncestorWithClass(),
526getId(), 526getParent(), 526getValue(), 527getValues(), 527release(), 527removeValue(), 527setId(), 527
![Page 614: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/614.jpg)
UseSession.jsp595
setPageContext(), 528setParent(), 528setValue(), 528TagSupport(), 525
TagSupport() method, 525<td> tag, 545teiclass subelement (<tag> tag),
303<template> tag, 545testerror.jsp (code example), 297testing
JSPs (JavaServer Pages), 256movie catalog application,
344-345text formatting, 399Thank You screen
(HttpSessionServlet), 57-58three-tier database access
model, 86-87timer card (WMLExample), 405<timer> tag, 401, 545timers, 401title bars
LDAP (Lightweight DirectoryAccess Protocol) client,349-350
movie catalog application, 329stock trading application,
367-369TitleListGlobalPooledServlet,
127-130TitleListServlet, 107-111tld files, 302-304tldis field (TagLibraryInfo
class), 537Tomcat server
downloading, 422-423installing, 423-424server.xml file, 424-426
toolsorder status tool
Order object, 73-74OrderStatusApplet, 74-80OrderStatusServlet, 80-83
WAP (Wireless ApplicationProtocol) developer tools,394
toString() method, 553<tr> tag, 545tracking sessions
cookies, 46Cookie class, 47CookieServlet example,
47-49definition of, 46support for, 46
hidden form fieldsHiddenFieldServlet
example, 43-46sample HTML listing,
42-43HTTP authentication, 42Servlet API
getAttribute() method, 51HtmlSessionServlet
example, 54-55HttpSessionServlet
example, 52-54removeAttribute()
method, 52setAttribute() method, 51Shopping Cart screen,
55-56Thank You screen, 57-58
URL (Uniform ResourceLocator) rewriting, 50-51
trader application. See stocktrading application
Trader Layout view (stock trading application), 367-370
transaction-type tag, 201translation time errors, 294transport service (JavaMail),
132trim() method, 553tunneling (HTTP), 59
advantages and disadvantages,83-84
clients, 66-71defined, 60OrderStatus example
Order object, 73-74OrderStatusApplet, 74-80OrderStatusServlet, 80-83
serialized objectscreating, 60enabling, 60reading, 60StudentList example, 61StudentListApplication
example, 61-66servlets, 71-73
two-tier database access model,86-87
type attribute<jsp:plugin> action, 279<jsp:useBean> action, 263
typeof operator, 407
U<u> tag, 399, 545UnavailableException class,
458-459UnavailableException() method,
458unescapeString() method, 555Uniform Resource Locators.
See URLsUPDATE statement, 105-107updating tables, 105-107uri attribute (taglib directive),
240uri field (TagLibraryInfo class),
537URL library, 409, 553-555URLRewritingServlet, 50-51URLs (Uniform Resource
Locators)rewriting, 50-51URL library, 409, 553-555
useBean action. See<jsp:useBean> action
UseForward JSP (JavaServerPage), 274-275
UseOut.jsp (code listing), 258UseRequest.jsp (code listing),
250UseSession.jsp (code listing),
252
![Page 615: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/615.jpg)
value attribute596
Vvalue attribute
<jsp:param> action, 269<jsp:setProperty> action, 264
valueBound() method, 479values field (Tag interface), 516valueUnBound() method, 479VariableInfo class, 539-541VariableInfo() method, 540variables (WML), 401varName field (VariableInfo
class), 540View class, 8viewing
deployed beans, 220shopping cart contents,
335-336views, 8
JSPs (JavaServer Pages) as, 10LDAP (Lightweight Directory
Access Protocol) clientAdd, 354-355Directory, 352-353Directory Layout, 349-351Index, 351-352
movie catalog applicationcatalog layout, 328-332Check Out, 336-338Index, 332-333Movie List, 334-335Shopping Cart, 335-336
stock trading applicationBuy/Sell, 372, 375Get Quote, 371-372Index, 370-371Trader Layout, 367-370
WWAA (Wireless Advertising
Association), 388WAE (Wireless Application
Environment), 392
WAP (Wireless ApplicationProtocol), 386
application servers, 395architecture, 391-392bandwidth considerations, 390developer tools, 394emulators, 392-394future of, 387-388history and development,
386-387network considerations, 390online resources, 395-396PDA WAP browsers, 394screen size considerations,
389-390version 1.2, 388WAP Forum Web site, 396WinWAP browser, 392-394
WAP Forum Web site, 396WAR (Web Archive) files, 422.wbmp file extension, 412WDP (Wireless Datagram
Protocol), 391Web applications. See also
applications; servletsdeployment descriptors,
421-422directory structure, 420-421LDAP (Lightweight Directory
Access Protocol) clientcontrollers, 356-360deleting directory objects,
359-360displaying directory server
contents, 352-353home page, 351-352HTML form, 354-355inserting directory objects,
358-359models, 348navigation, 350-351running, 360-361searching directory server,
356-357title bar, 349-350views, 349-355
movie catalogConnectionPool, 323-325controllers, 338-344index, 332-333listing movies, 334-335,
338-341Movie object, 322-323requirements, 322shopping cart, 325-328,
335-338, 341-344testing, 344-345title bar, 329views, 328-338
online directory, 348controllers, 356-360deleting directory objects,
359-360displaying directory server
contents, 352-353home page, 351-352HTML form, 354-355inserting directory objects,
358-359models, 348navigation, 350-351running, 360-361searching directory server,
356-357title bar, 349-350views, 349-355
server.xml file configuration,424-426
ServletContexts, 420stock trading application, 364
buying stock, 377-379ConnectionPool servlet,
365-367controllers, 375-382getting stock quotes,
371-372, 375-377home page, 370-371models, 364-367navigation, 369-370running, 382-383selling stock, 380-382stock object, 364-365
![Page 616: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/616.jpg)
WirelessDevNet WAP Channel597
title bar, 367-369views, 367-372, 375
WAR (Web Archive) files, 422Web Archive (WAR) files, 422Web browsers
PDA WAP browsers, 394WinWAP, 392-394
Web sitesAllNetDevices, 395AnywhereYouGo.com, 396Apache Cocoon, 414Cellmania, 395DoCoMo, 388Gelon.net, 392, 395JavaSoft, 422SSL (Secure Sockets Layer)
specifications, 150WAP Forum, 396Wireless Developer Network,
395, 544wireless development
resources, 412Wireless Week, 395WirelessDevNet WAP
Channel, 391WMLScript.com, 395YoSpace, 392
WebLogic, 395welcome card (WMLExample),
404while loops, 408WinWAP browser, 392, 394Wireless Advertising Association
(WAA), 388Wireless Application
Environment (WAE), 392Wireless Application Protocol.
See WAPWireless Datagram Protocol
(WDP), 391Wireless Developer Network,
395, 544wireless development
3G, 389bearer service, 388
CDMA (Code DivisionMultiple Access), 389
CDPD (Cellular DigitalPacket Data), 389
gateways, 388GPRS (General Packet Radio
Service), 389GSM (Global System for
Mobile Communication),389
i-Mode, 388servlets
HelloWorld! servlet,413-414
maintaining in XML(Extensible MarkupLanguage), 414
multiple device support,414
server MIME types,412-413
Web sites, 412WAA (Wireless Advertising
Association), 388WAP (Wireless Application
Protocol)application servers, 395architecture, 391-392bandwidth considerations,
390developer tools, 394emulators, 392-394future of, 387-388history and development,
386-387network considerations,
390online resources, 395-396PDA WAP browsers, 394screen size considerations,
389-390version 1.2, 388WinWAP browser, 392-394
WML (Wireless MarkupLanguage)
anchors, 400cards, 398decks, 398DTD (Document Type
Definition), 398events, 400-401Hello World! application,
398-399tags, 544-545text-formatting tags, 399timers, 401user input, 400variables, 401WMLExample application,
401-405WMLScript, 405
calling, 406Dialogs library, 557Float library, 550-551Lang library, 548-550operators, 407standard libraries,
408-409statements, 407-408String library, 551-553syntax, 406URL library, 553-555WMLBrowser library, 556WMLScriptExample
application, 409-411WTAI (Wireless Telephony
Applications Interface), 388Wireless Markup Language.
See WMLWireless Session Layer (WSP),
392Wireless Telephony Applications
Interface (WTAI), 388Wireless Transaction Protocol
(WTP), 391Wireless Transport Layer
Security (WTLS), 391Wireless Week Web site, 395WirelessDevNet WAP Channel,
391
![Page 617: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/617.jpg)
WML598
WML (Wireless MarkupLanguage)
anchors, 400cards, 398decks, 398DTD (Document Type
Definition), 398events, 400-401Hello World! application,
398-399tags, 399, 544-545timers, 401user input, 400variables, 401WMLExample application
code listing, 401-403input card, 404previous card, 405select card, 405setvar card, 404timer card, 405welcome card, 404
WMLScript, 405calling, 406Dialogs library, 557Float library, 550-551Lang library, 548-550operators, 407standard libraries,
408-409statements, 407-408String library, 551-553syntax, 406URL library, 553-555WMLBrowser library, 556WMLScriptExample
application, 409-411.wml file extension, 412<wml> tag, 545WMLBrowser library, 409, 556.wmlc file extension, 412WMLExample application
code listing, 401-403input card, 404previous card, 405select card, 405
setvar card, 404timer card, 405welcome card, 404
.wmls file extension, 412
.wmlsc file extension, 412WMLScript, 405, 548
calling, 406Dialogs library, 557Float library, 550-551Lang library
abort() method, 548abs() method, 548characterSet() method,
548exit() method, 548float() method, 548isFloat() method, 549isInt() method, 549max() method, 549maxInt() method, 549min() method, 549minInt() method, 549parseFloat() method, 549parseInt() method, 549random() method, 550seed() method, 550
operators, 407standard libraries, 408-409statements, 407-408String library
charAt() method, 551compare() method, 551elementAt() method, 551elements() method, 552find() method, 552format() method, 552insertAt() method, 552isEmpty() method, 552length() method, 552removeAt() method, 552replace() method, 553replaceAt() method, 553squeeze() method, 553subString() method, 553toString() method, 553trim() method, 553
syntax, 406URL library, 553-555WMLBrowser library, 556WMLScriptExample
applicationWMLScriptExample.wml,
410-411WMLScriptExample.wmls,
409-410WMLScript.com Web site, 395WMLScriptExample
applicationWMLScriptExample.wml,
410-411WMLScriptExample.wmls,
409-410writeOrder() method, 79writeOut() method, 523writeStudentList() method, 70writing servlets, 422WSP (Wireless Session Layer),
392WTAI (Wireless Telephony
Applications Interface), 388WTLS (Wireless Transport
Layer Security), 391WTP (Wireless Transaction
Protocol), 391
X-ZXHTML, 388XML (Extensible Markup
Language)combining with Java, 153document tree structure, 152incorporating into servlets,
159-161JAXP (Java API for XML
Processing), 153maintaining wireless
applications in, 414parsing files, 153-155processing instructions, 152
![Page 618: Developing Java Servlets](https://reader034.vdocuments.net/reader034/viewer/2022042906/57ade2721a28abbe3a980b7e/html5/thumbnails/618.jpg)
YoSpace599
SAX API (Simple API forXML)
SAXHandler.java handler,155-159
XMLTest.java document,153-155
simple example, 152-153XMLServlet, 159-161XMLTest.java (code listing),
153-155
YoSpace, 392