Upload
api-3834494
View
481
Download
0
Embed Size (px)
Citation preview
The J2EETM Tutorial
Stephanie BodoffDale Green
Eric JendrockMonica Pawlan
Beth Stearns
nt is
nts, or
stemsvaOS,irectory
Com-.
Copyright © 2001 by Sun Microsystems, Inc.901 San Antonio Road, Palo Alto, California 94303 U.S.A.All rights reserved.
RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Governmesubject to the restrictions set forth in DFARS 252.227-7013(c)(1)(iii) and FAR 52.227-19.
The release described in this book may be protected by one or more U.S. patents, foreign patepending applications.
Sun, Sun Microsystems, Sun Microsystems Computer Corporation, the Sun logo, the Sun MicrosyComputer Corporation logo, Java, JavaSoft, Java Software, JavaScript, JDBC, JDBC Compliant, JaJavaBeans, Enterprise JavaBeans, JavaServer Pages, J2EE, J2SE, JavaMail, Java Naming and DInterface, EJB, and JSP are trademarks or registered trademarks of Sun Microsystems, Inc. UNIX® is aregistered trademark in the United States and other countries, exclusively licensed through X/Openpany, Ltd. All other product names mentioned herein are the trademarks of their respective owners
THIS PUBLICATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHEREXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICALERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESECHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUNMICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PROD-UCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.
iii
Contentsxviixviiixviiixviiiviii
. xxxxi
. xxixxii
24. 25. 2626
. 26
. 26
. 27
. 27
. 28 . 28 . 2930
. 30 . 30 . 32. . 33
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Who Should Use This Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .About the Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Prerequisites for the Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Where to Find the Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .How to Build and Run the Examples . . . . . . . . . . . . . . . . . . . . . . . . . x
Related Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .How to Print This Tutorial. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Typographical Conventions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 1: Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Distributed Multitiered Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .J2EE Application Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Client Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Application Clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web Browsers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . JavaBeans™ Component Architecture . . . . . . . . . . . . . . . . . . . . J2EE Server Communications. . . . . . . . . . . . . . . . . . . . . . . . . . .
Thin Clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Web Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Business Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Enterprise Information System Tier . . . . . . . . . . . . . . . . . . . . . . . . . . .
J2EE Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Containers and Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Container Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Packaging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
iv
. .34. .34. .34 .35. .35 .35.35 .35.36 . .36 . .37. . .37. .37. .37.38. .38 . .38. .39 .39 .39 .3939 .4040. .4040. .42
. .44. .44 .44 .45. .455
. .46 . .46. .46 .46 .47. .47. .48 . .48
Development Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .J2EE Product Provider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tool Provider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Application Component Provider . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Enterprise Bean Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Web Component Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .J2EE Application Client Creation. . . . . . . . . . . . . . . . . . . . . . . . .
Application Assembler. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Application Deployer and Administrator. . . . . . . . . . . . . . . . . . . . . . .
Reference Implementation Software. . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Database Access. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . J2EE APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Enterprise JavaBeans Technology 2.0 . . . . . . . . . . . . . . . . . . . . JDBC™ 2.0 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Java Servlet Technology 2.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . JavaServer Pages (JSP) Technology 1.2. . . . . . . . . . . . . . . . . . .Java Message Service (JMS) 1.0 . . . . . . . . . . . . . . . . . . . . . . . . Java Transaction API (JTA) 1.0 . . . . . . . . . . . . . . . . . . . . . . . . . .JavaMail™ Technology 1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .JavaBeans Activation Framework 1.0 . . . . . . . . . . . . . . . . . . . . .Java API for XML (JAXP) 1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . .J2EE Connector API 1.0. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Java Authentication and Authorization Service (JAAS) 1.0 . . . . .
Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Application Deployment Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . .Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 2: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .43
Setting Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Getting the Example Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Building the Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Checking the Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . .Starting the J2EE™ Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Starting thedeploytool. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4
Creating the J2EE™ Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating the Enterprise Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Coding the Enterprise Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Coding the Remote Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . .Coding the Home Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Coding the Enterprise Bean Class . . . . . . . . . . . . . . . . . . . . . . .
Compiling the Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Packaging the Enterprise Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
v
495050
. 5151
51525253
. 53. 5355
. 55. 56. 565758
. 595959
. 606060
. 61 . 616161
. 616162626262636363
. 63636364
. 64
Creating the J2EE™ Application Client . . . . . . . . . . . . . . . . . . . . . . . . . . .Coding the J2EE Application Client . . . . . . . . . . . . . . . . . . . . . . . . . .
Locating the Home Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating an Enterprise Bean Instance . . . . . . . . . . . . . . . . . . . . .Invoking a Business Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . .ConverterClient Source Code . . . . . . . . . . . . . . . . . . . . . . . .
Compiling the Application Client . . . . . . . . . . . . . . . . . . . . . . . . . . . .Packaging the J2EE Application Client . . . . . . . . . . . . . . . . . . . . . . . .Specifying the Application Client’s Enterprise Bean Reference . . . . .
Creating the Web Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Coding the Web Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Compiling the Web Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Packaging the Web Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specifying the Web Client’s Enterprise Bean Reference. . . . . . . . . .
Specifying the JNDI Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying the J2EE™ Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Running the J2EE™ Application Client . . . . . . . . . . . . . . . . . . . . . . . . . . .Running the Web Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modifying the J2EE™ Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Modifying a Class File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Adding a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modifying the Web Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Modifying a Deployment Setting . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Common Problems and Their Solutions . . . . . . . . . . . . . . . . . . . . . . . . . .Cannot Start the J2EE Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Naming and Directory Service Port Conflict . . . . . . . . . . . . . . . .Web Service Port Conflict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Compilation Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ant Cannot Locate the Build File . . . . . . . . . . . . . . . . . . . . . . . . .The Compiler Cannot Resolve Symbols . . . . . . . . . . . . . . . . . . . .
J2EE Application Client Runtime Errors . . . . . . . . . . . . . . . . . . . . . . .The Client Cannot Find ConverterApp.ear . . . . . . . . . . . . . . . . . .The Client Cannot Find the ConverterClient Component. . . . . . .The Login Failed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The J2EE Application Has Not Been Deployed . . . . . . . . . . . . . .The JNDI Name is Incorrect . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Web Client Runtime Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Web Context in the URL is Incorrect . . . . . . . . . . . . . . . . . .The J2EE Application Has Not Been Deployed . . . . . . . . . . . . . .The JNDI Name is Incorrect . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Deployment Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
vi
. .66. . .668
68. .69 .70. .71 . .72. . .72 . .72. . .73. . .73 . .74. .74 . .75. . .76. .76. .77 . .78
. .82 . .82 . .82. .82 . .83. .83
Chapter 3: Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65
A Session Bean Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Session Bean Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
TheSessionBean Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . .6TheejbCreate Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Business Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Home Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Remote Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Helper Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .State Management Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Stateful Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Stateless Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Choosing Between Stateful and Stateless Session Beans . . . . . . . .
The Life Cycle of a Session Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The Stateful Session Bean Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . The Stateless Session Bean Life Cycle . . . . . . . . . . . . . . . . . . . . . . .
Other Enterprise Bean Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Accessing Environment Entries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Comparing Enterprise Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Passing an Enterprise Bean’s Object Reference . . . . . . . . . . . . . . . .
Chapter 4: Entity Beans. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81
Characteristics of Entity Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bean-Managed Persistence. . . . . . . . . . . . . . . . . . . . . . . . . . . . .Container-Managed Persistence . . . . . . . . . . . . . . . . . . . . . . . . .
Shared Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Primary Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
vii
. . 83 . 84. 848567
7. 88. 90 . 92. 92 . 94
. 94959596
. . 96 . 97
10001
04
108
. 111
. 111111112113
. 113114
114115
116
120
A Bean-Managed Persistence Example. . . . . . . . . . . . . . . . . . . . . . . . . . Entity Bean Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The EntityBean Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
TheejbCreate Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .TheejbPostCreate Method . . . . . . . . . . . . . . . . . . . . . . . . . . 8TheejbRemove Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8TheejbLoad andejbStore Methods . . . . . . . . . . . . . . . . . . . 8The Finder Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Business Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Database Calls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Home Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Remote Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tips for Running theAccountEJB Example . . . . . . . . . . . . . . 94
Setting Up the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Running the New Enterprise Bean Wizard . . . . . . . . . . . . . . . . . .Deploying the J2EE Application. . . . . . . . . . . . . . . . . . . . . . . . . .Running the J2EE Application . . . . . . . . . . . . . . . . . . . . . . . . . . .
Mapping Table Relationships For Bean-Managed Persistence. . . . . . . . One-to-One Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tips for Running theStorageBinEJB Example . . . . . . . . . . . . 99One-to-Many Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A Helper Class for the Child Table. . . . . . . . . . . . . . . . . . . . . . . 1 Tips for Running theOrderEJB Example: . . . . . . . . . . . . . . . 104An Entity Bean for the Child Table . . . . . . . . . . . . . . . . . . . . . . 1Tips for Running theSalesRepEJB Example: . . . . . . . . . . . . 107
Many-to-Many Relationships. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tips for running theEnrollerEJB example: . . . . . . . . . . . . . . . 110
About Container-Managed Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . A Container-Managed Persistence Example . . . . . . . . . . . . . . . . . . . . . . Primary Key Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating a Primary Key Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Class Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Bean-Managed Persistence and the Primary Key Class. . . . . . . . . . Container-Managed Persistence and the Primary Key Class . . . . . . .Getting the Primary Key. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Handling Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The Life Cycle of an Entity Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 5: Web Components . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Web Component Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
viii
.122.12223
123.1242512525.125 En-
.126
.126126127128128128.129 .129 .129
.134 .135.138.13940
140141.142.142 .142.143.145.145146 .148. .151152155
Packaging Web Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating a WAR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding a WAR to a J2EE Application . . . . . . . . . . . . . . . . . . . . . . . .1Adding a Web Component to a WAR . . . . . . . . . . . . . . . . . . . . . . . . .
Configuring Web Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Application-Level Configuration. . . . . . . . . . . . . . . . . . . . . . . . . . . . .1
Context Root . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .WAR-Level Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1
Context Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . References to Environment Entries, Enterprise Beans, Resourcevironment Entries, or Resources. . . . . . . . . . . . . . . . . . . . . . . . . Event Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Error Mapping. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Filter Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Component-Level Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Initialization Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Specifying an Alias Path. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Deploying Web Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Executing Web Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Updating Web Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 6: Java Servlet Technology . . . . . . . . . . . . . . . . . . . . . .133
What is a Servlet? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The Example Servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Servlet Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Monitoring Servlet Life Cycle Events . . . . . . . . . . . . . . . . . . . . . . . . .1Defining The Listener Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Specifying Event Listener Classes . . . . . . . . . . . . . . . . . . . . . . . .
Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Sharing Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Scope Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Controlling Concurrent Access to Shared Resources . . . . . . . . . . . .
Initializing a Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Writing Service Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Getting Information From Requests . . . . . . . . . . . . . . . . . . . . . . . . . .Constructing Responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Filtering Requests and Responses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining the Filter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Specifying Filter Mappings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ix
156157
158159
160. 16016161
. 162162163164165166
. 168 . 171. 173174175
1751751761781791797980181181182182184
. 185186186186. 189
Invoking Other Web Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Including the Content of Another Resource in the Response . . . . . .Transferring a Control to Another Web Component . . . . . . . . . . . . .
Accessing the Web Context. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Maintaining Client State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Accessing a Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Associating Attributes with a Session . . . . . . . . . . . . . . . . . . . . . . . .
Notifying Objects That Are Added To a Session . . . . . . . . . . . . 1Session Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Session Tracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Finalizing a Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tracking Service Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Providing a Clean Shutdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating Polite Long-Running Methods . . . . . . . . . . . . . . . . . . . . . .
Chapter 7: JavaServer Pages™ Technology. . . . . . . . . . . . . . . 167
What is a JSP Page?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The Example JSP Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The Life Cycle of a JSP Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Translation and Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Buffering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Handling Errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Initializing and Finalizing a JSP Page . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating Static Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating Dynamic Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Objects Within JSP Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . .Implicit Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Application-Specific Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Shared Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
JSP Scripting Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Declarations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Scriptlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Including Content in a JSP Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Transferring Control to Another Web Component . . . . . . . . . . . . . . . . . .
Param Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Including an Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Extending the JSP Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
x
. .192. .193. .194. .194. .197
.200 .200 .204204.205.20520520707
207.208.208.209210211.211.212.2122132131321415.216.216218218.2189
.222
Chapter 8: JavaBeans™ Components in JSP™ Pages . . . . . . .191
JavaBeans Component Design Conventions. . . . . . . . . . . . . . . . . . . . . . Why Use a JavaBeans Component? . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating and Using a JavaBeans Component . . . . . . . . . . . . . . . . . . . . . Setting JavaBeans Component Properties. . . . . . . . . . . . . . . . . . . . . . . . Retrieving JavaBeans Component Properties . . . . . . . . . . . . . . . . . . . . .
Chapter 9: Custom Tags in JSP™ Pages . . . . . . . . . . . . . . . . . . .199
What is a Custom Tag? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The Example Tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Using Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Declaring Tag Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Types of Tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simple Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tags With Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tags With Bodies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Choosing Between Passing Information as Attributes or Body . .2Tags That Define Scripting Variables . . . . . . . . . . . . . . . . . . . . .Cooperating Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Defining Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tag Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tag Library Descriptors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Listener Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tag Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simple Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tag Handlers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Body-content Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tags With Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Defining Attributes in a Tag Handler . . . . . . . . . . . . . . . . . . . . . .2Attribute Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Attribute Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2
Tags With Bodies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tag Handlers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Body-content Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tags That Define Scripting Variables . . . . . . . . . . . . . . . . . . . . . . . . .Tag Handlers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Providing Information About the Scripting Variable . . . . . . . . . .21
Cooperating Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xi
. 224224224
225227227
228229233
. 236
. 236237
23823823823823923923939
24024124243
. 24324424546
247247248249250
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . An Iteration Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
JSP Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tag Handler. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tag Extra Info Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A Template Tag Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .JSP Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tag Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How Is a Tag Handler Invoked? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 10: Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
What is a Transaction? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Container-Managed Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Transaction Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Transaction Attribute Values . . . . . . . . . . . . . . . . . . . . . . . . . . .Required . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .RequiresNew. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Mandatory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NotSupported . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Supports. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Never . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Summary of Transaction Attributes . . . . . . . . . . . . . . . . . . . . . . 2Setting Transaction Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . .
Rolling Back a Container-Managed Transaction . . . . . . . . . . . . . . . .Synchronizing a Session Bean’s Instance Variables . . . . . . . . . . . . .Methods Not Allowed in Container-Managed Transactions . . . . . . . 2
Bean-Managed Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . JDBC Transactions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .JTA Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Returning Without Committing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Methods Not Allowed in Bean-Managed Transactions . . . . . . . . . . .
Summary of Transaction Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Transaction Timeouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Isolation Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Updating Multiple Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xii
.254 .255.256.25757
588
.259259259.260260261261.2616161262262262262263.264.264.265.265.266 .266.267267267nts
. .268.268268268
Chapter 11: Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .253
Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . J2EE Users, Realms, and Groups . . . . . . . . . . . . . . . . . . . . . . . . . . .
Managing J2EE Users and Groups . . . . . . . . . . . . . . . . . . . . . . . Authentication Mechanisms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Web-Tier Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2Configuring A Web Component’s Authentication Mechanism . .2Using Hybrid Authentication to Enhance Confidentiality . . . . . .25
Controlling Access to J2EE Resources . . . . . . . . . . . . . . . . . . . . . . . Controlling Access to Web Resources . . . . . . . . . . . . . . . . . . . . .Controlling Access to Enterprise Beans . . . . . . . . . . . . . . . . . . . .Unprotected Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Client Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Auto-Registration of Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Web Client Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Data Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Developing a Custom Web Tier User Authentication Interface. .2
Application Client Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . .2Setting Component Security Identities . . . . . . . . . . . . . . . . . . . . . . . .
Capturing a Security Context (Servlet). . . . . . . . . . . . . . . . . . . . .Container Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Setting Up a Server Certificate . . . . . . . . . . . . . . . . . . . . . . . . . . .Configuring EJB Target Security Requirements . . . . . . . . . . . . . . . . .Configuring Resource Signon (Connectors) . . . . . . . . . . . . . . . . . . .
Authorization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Declaring Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Declaring Method Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Declaring Role References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Mapping Roles to J2EE Users and Groups . . . . . . . . . . . . . . . . . . . .Linking Role References to Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring J2SE Security Policy Files . . . . . . . . . . . . . . . . . . . . . . .Determining the Caller Identity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Making Portable Access Decisions Programmatically from Compone267
Protecting Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Application Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
J2EE Application Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web Browser Client. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xiii
. 270270270271
. 271271
2712722732732732747527677
. 282282
283285285286878787288288288289
Chapter 12: Resource Connections. . . . . . . . . . . . . . . . . . . . . . . 269
JNDI Names and Resource References . . . . . . . . . . . . . . . . . . . . . . . . . .Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Specifying a Resource Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . .Mapping a Resource Reference to a JNDI Name. . . . . . . . . . . . . . . .
Database Connections for Enterprise Beans . . . . . . . . . . . . . . . . . . . . . . Coded Connections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How to Connect. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .When To Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Specifying Database Users and Passwords . . . . . . . . . . . . . . . . .
Container-Managed Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . .Connection Pooling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Mail Session Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tips for Running the ConfirmerEJB Example . . . . . . . . . . . . . . . . . . 2
URL Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tips for Running the HTMLReaderEJB Example . . . . . . . . . . . . . . . 2
Chapter 13: J2EE™Connector Technology . . . . . . . . . . . . . . . . . 281
About Resource Adapters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Resource Adapter Contracts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Administering Resource Adapters . . . . . . . . . . . . . . . . . . . . . . . . . . .
The Black Box Resource Adapters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Transaction Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Configuring JDBC™ Drivers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
The Non-XA Black Box Adapters . . . . . . . . . . . . . . . . . . . . . . . 2The XA Black Box Adapters . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Resource Adapter Tutorial. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Setting Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Deploying the Resource Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . .Testing the Resource Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xiv
291291293 .295.296 .298.300302302.302 .303304.306
.307. .308
310 .311. .311 .311.31212.313. .314.314
Common Client Interface (CCI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Overview of the CCI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Programming with the CCI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Database Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . .Mapping to Stored Procedure Parameters . . . . . . . . . . . . . . . . . Reading Database Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Inserting Database Records . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Writing a CCI Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .CCI Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Deploy the Resource Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . Set Up the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Create the J2EE Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . .Test the Resource Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 14: HTTP Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .307
HTTP Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .HTTP Responses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 15: J2EE™SDK Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . .309
J2EE Administration Tool. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Cleanup Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Cloudscape Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Starting and Stopping Cloudscape . . . . . . . . . . . . . . . . . . . . . . . . . . .Cloudscape Server Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . Cloudscapeij Tool. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3
Deployment Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . J2EE Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Key Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xv
. 3153153153151631616163161731731717317
31818319319319320320
32021
Packager. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . EJB JAR File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Web Application WAR File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Example: Creating a Simple WAR File . . . . . . . . . . . . . . . . . . . 3Example: Specifying Individual Content Files . . . . . . . . . . . . . . 3Example: Specifying Servlets and JSP Files. . . . . . . . . . . . . . . .
Application Client JAR File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
J2EE Application EAR File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Example: Creating an EAR File . . . . . . . . . . . . . . . . . . . . . . . . .Example: Specifying the Runtime Deployment Descriptor . . . . 3
Resource Adapter RAR File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Realm Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Runclient Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Verifier. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Command-Line Verifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Stand-Alone GUI Verifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
xvi
xvii
merssametionhe
ingthe
them
lainthen be
Preface
THE Java Tutorial has been an indispensable resource for many programlearning the Java programming language. This tutorial hopes to serve therole for developers encountering the Java™ 2 Platform, Enterprise Edi(J2EE™) for the first time. It follows an example-oriented focus similar to tJava Tutorial.
Who Should Use This Tutorial xviiAbout the Examples xviiiRelated Information xxHow to Print This Tutorial xxiTypographical Conventions xxiAcknowledgments xxii
Who Should Use This TutorialThis tutorial is intended for programmers interested in developing and deployJ2EE applications. It covers the main component technologies comprisingJ2EE platform and describes how to develop J2EE components and deployon the J2EE SDK.
This tutorial is not intended for J2EE server or tools vendors. It does not exphow to implement the J2EE architecture, nor does it explain the internals ofJ2EE SDK. The J2EE specifications describe the J2EE architecture and cadownloaded from:
http://java.sun.com/j2ee/docs.html#specs
xviii
pro-top-
ou
thealso
About the ExamplesThis tutorial includes many complete, working examples.
Prerequisites for the ExamplesTo understand the examples you will need a good knowledge of the Javagramming language, SQL, and relational database concepts. The followingics in the Java Tutorial are particularly relevant:
Where to Find the ExamplesIf you are viewing this online, and you want to build and run the examples, yneed to download the tutorial bundle from:
http://java.sun.com/j2ee/download.html#tutorial
Once you have installed the bundle, the example code is in theexamples/src
directory, with subdirectoriesejb for enterprise bean technology examples,web
for web technology examples, andconnector for connector technology exam-ples.
How to Build and Run the ExamplesThis tutorial documents the J2EE SDK version 1.3. To build, deploy, and runexamples you need a copy of the J2EE SDK 1.3 and the J2SE™ SDK 1.3,known as a JDK. You can download the J2EE SDK from:
http://java.sun.com/j2ee/download.html#sdk
Topic Java Tutorial
JDBC™ http://java.sun.com/docs/books/tutorial/jdbc
Threads http://java.sun.com/docs/books/tutorial/essential/threads
JavaBeans™ http://java.sun.com/docs/books/tutorial/javabeans
Security http://java.sun.com/docs/books/tutorial/security1.2
xix
re
vi-ble.
-
and the J2SE 1.3 from:
http://java.sun.com/j2se/1.3/
The examples are distributed with a configuration file forant version 1.2. A por-table make tool,ant is hosted by the Jakarta project at the Apache SoftwaFoundation. You can downloadant from:
http://jakarta.apache.org/builds/jakarta-ant/release/v1.2/bin
To build the examples:
1. Download and install the J2SE SDK 1.3, J2EE SDK 1.3, andant.
2. The installation instructions for the J2SE SDK, J2EE SDK, andant
explain how to set the required environment variables. Verify that the enronment variables have been set to the values noted in the following ta
3. Go to theexamples/src directory.
4. Open the filebuild.xml in a text editor. Edit the line:
<property name="j2ee-home" value="C:\j2sdkee1.3" />
and set the value of thej2ee-home property to be the J2EE SDK installation directory.
5. Executeant target. For example, to build all the examples, executeant
all or to build the web layer examples, executeant web. The build processdeposits the output into the directoryexamples/build.
Environment Variable Value
JAVA_HOME The location of the J2SE SDK installation.
J2EE_HOME The location of the J2EE SDK installation.
ANT_HOME The location of theant installation.
PATHShould include thebin directory of the J2EE SDK andantinstallation.
xx
entolo-
fly
Related InformationThis tutorial provides a concise overview of how to use the central compontechnologies in the J2EE platform. For more information about these techngies, see:
The J2EE platform includes a wide variety of APIs that this tutorial only brietouches on. Some of these technologies have their own tutorials:
For complete information on these topics see:
Component Technology Web Site
Enterprise JavaBeans™ (EJB™) http://java.sun.com/products/ejb
Java Servlet http://java.sun.com/products/servlets
JavaServer Pages™ (JSP™) http://java.sun.com/products/jsp
API Tutorial
Java Message Service (JMS) http://java.sun.com/products/jms/tutorial/
Java Naming and DirectoryInterface™ (JNDI)
http://java.sun.com/products/jndi/tutorial/
Extensible Markup Language(XML)
http://java.sun.com/xml/tutorial_intro.html
API Web Site
XML http://java.sun.com/xml
J2EE Connector http://java.sun.com/j2ee/connector
xxi
thisns.rac-2EE
Once you have become familiar with the J2EE technologies described intutorial, you may be interested in guidelines for architecting J2EE applicatioThe J2EE Blueprints is a book and sample application that illustrate best ptices for developing and deploying J2EE applications. You can obtain the JBlueprints from:
http://java.sun.com/j2ee/blueprints
How to Print This TutorialTo print this tutorial, follow these steps:
• Ensure that Adobe Acrobat Reader is installed on your system.
• Using your browser, access the PDF version of this book.
• Click the printer icon in Adobe Acrobat Reader.
Typographical ConventionsThe following table lists the typographical conventions used in this tutorial.
JavaMail™ http://java.sun.com/products/javamail
JMS http://java.sun.com/products/jms
JNDI http://java.sun.com/products/jndi
JDBC™ http://java.sun.com/products/jdbc
Font Style Uses
italic Emphasis, titles, first occurrence of terms
monospace URLs, code examples, file names, commandnames, programming language keywords
italic monospace Programming variables, variable file names
API Web Site
xxii
ni-
ady-
t firsttags
AcknowledgmentsThe J2EE tutorial team would like to thank the J2EE SDK team for their techcal advice and enthusiasm.
We would also like to thank our manager Jim Inscore for his support and steing influence.
The chapters on web components use an example and some material thaappeared in the servlet trail of the Java Tutorial. The chapter on customdescribes a template tag library that first appeared in the J2EE Blueprints.
nality oft inch-less
ent,om-ent oftedandlu-po-
or.
s andr anpany-nter-
e topor-pro-
Overviewby Monica Pawlan
TODAY, more and more developers want to write distributed transactioapplications for the enterprise and leverage the speed, security, and reliabilserver-side technology. If you are already working in this area, you know thatoday’s fast-moving and demanding world of e-commerce and information tenology, enterprise applications have to be designed, built, and produced formoney, faster, and with fewer resources than ever before.
To reduce costs and fast-track enterprise application design and developmthe Java™ 2 Platform, Enterprise Edition (J2EE™) technology provides a cponent-based approach to the design, development, assembly, and deploymenterprise applications. The J2EE platform gives you a multitiered distribuapplication model, the ability to reuse components, a unified security model,flexible transaction control. Not only can you deliver innovative customer sotions to market faster than ever, but your platform-independent J2EE comnent-based solutions are not tied to the products and APIs of any one vend
This tutorial takes an examples-based approach to describing the featurefunctionalities available in J2EE SDK version 1.3. Whether you are a new oexperienced enterprise developer, you should find the examples and accoming text a valuable and accessible knowledge base for creating your own eprise solutions.
If you are new to J2EE applications development, this chapter is a good placstart. Here you will learn the J2EE architecture, become acquainted with imtant terms and concepts, and find out how to approach J2EE applicationsgramming, assembly, and deployment.
23
24 OVERVIEW
ansari-
dif-entpli-
ica-
ver
e 1,ppli-lient
Distributed Multitiered Applications 24J2EE Application Components 25Client Components 26Thin Clients 28Web Components 28Business Components 29Enterprise Information System Tier 30
J2EE Architecture 30Containers and Services 30Container Types 32
Packaging 33Development Roles 34
J2EE Product Provider 34Tool Provider 34Application Component Provider 35Application Assembler 35Application Deployer and Administrator 36
Reference Implementation Software 36Web Server 37Database Access 37J2EE APIs 37Tools 40
Distributed Multitiered ApplicationsThe J2EE platform uses a multitiered distributed application model. This meapplication logic is divided into components according to function, and the vous application components that make up a J2EE application are installed onferent machines depending on which tier in the multitiered J2EE environmthe application component belongs. Figure 1 shows two multitiered J2EE apcations divided into the tiers described in the bullet list below. The J2EE appltion parts shown in Figure 1 are presented inJ2EE ApplicationComponents (page 25).
• Client tier components run on the client machine
• Web tier components run on the J2EE server
• Business tier components run on the J2EE server
• Enterprise information system (EIS) tier software runs on the EIS ser
While a J2EE application can consist of the three or four tiers shown in FigurJ2EE multitiered applications are generally considered to be three-tiered acations because they are distributed over three different locations: c
DISTRIBUTED MULTITIERED APPLICATIONS 25
at thetwo-rver
-con-its
J2EE
ts are
busi-
piledenceinto
machines, J2EE server machine, and the database or legacy machinesback-end. Three-tiered applications that run in this way extend the standardtiered client and server model by placing a multithreaded application sebetween the client application and back-end storage.
Figure 1 Multitiered Applications
J2EE Application ComponentsJ2EE applications are made up of components. A J2EE component is a selftained functional software unit that is assembled into a J2EE application withrelated classes and files and communicates with other components. Thespecification defines the following J2EE components:
• Application clients and applets are client components.
• Java Servlet and JavaServer Pages™ (JSP™) technology componenweb components.
• Enterprise JavaBeans™ (EJB™) components (enterprise beans) areness components.
J2EE components are written in the Java programming language and comin the same way as any Java programming language program. The differwhen you work with the J2EE platform, is J2EE components are assembled
Application Client
Enterprise Beans
Dynamic HTML pages
JSP pages
Enterprise Beans
Database
Client tier
Web tier
Business tier
EIS tier
Client Machine
J2EE Server Machine
Database Server Machine
Database
J2EE Application 1
J2EE Application 2
26 OVERVIEW
ithman-
lientwebased
s toas alkit
tier.ionvlet
an-pner-pages)
t. Anagesys-let
causeJSProvideeans
a J2EE application, verified that they are well-formed and in compliance wthe J2EE specification, and deployed to production where they are run andaged by the J2EE server.
Client ComponentsA J2EE application can be web-based or non-web-based. An application cexecutes on the client machine for a non-web-based J2EE application, and abrowser downloads web pages and applets to the client machine for a web-bJ2EE application.
Application Clients
An application client runs on a client machine and provides a way for userhandle tasks such as J2EE system or application administration. It typically hgraphical user interface created from Project Swing or Abstract Window Too(AWT) APIs, but a command-line interface is certainly possible.
Application clients directly access enterprise beans running in the businessHowever, if the J2EE application client requirements warrant it, an applicatclient can open an HTTP connection to establish communication with a serrunning in the web tier.
Web Browsers
The user’s web browser downloads static or dynamic Hypertext Markup Lguage (HTML), Wireless Markup Language (WML), or Extensible MarkuLanguage (XML) web pages from the web tier. Dynamic web pages are geated by servlets or pages created with JavaServer Pages technology (JSPrunning in the web tier.
Applets
A web page downloaded from the web tier can include an embedded appleapplet is a small client application written in the Java programming languthat executes in the Java VM installed in the web browser. However, clienttems will likely need Java Plug-in and possibly a security policy file so the appcan successfully execute in the web browser.
JSP pages are the preferred API for creating a web-based client program beno plug-ins or security policy files are needed on the client systems. Also,pages enable cleaner and more modular application design because they pa way to separate applications programming from web page design. This m
DISTRIBUTED MULTITIERED APPLICATIONS 27
ram-
or carJSP
overs as the2EEWAP
com-en anava-cifica-
blesava-ple-d in
lientctly,
es or
personnel involved in web page design do not need to understand Java progming language syntax to do their jobs.
Applets that run in other network-based systems such as handheld devicesphones can render Wireless Markup Language (WML) pages generated by apage or servlet running on the J2EE server. The WML page is deliveredWireless Application Protocol (WAP) and the network configuration requiregateway to translate WAP to HTTP and back again. The gateway translateWAP request coming from the handheld device to an HTTP request for the Jserver, and then translates the HTTP server response and WML page to aserver response and WML page for display on the handheld device.
JavaBeans™ Component Architecture
The client tier might also include a component based on the JavaBeans™ponent architecture (JavaBeans component) to manage the data flow betweapplication client or applet and components running on the J2EE server. JBeans components are not considered J2EE components by the J2EE spetion.
JavaBeans components written for the J2EE platform have instance variaandget andset methods for accessing the data in the instance variables. JBeans components used in this way are typically simple in design and immentation, but should conform to the naming and design conventions outlinethe JavaBeans component architecture.
J2EE Server Communications
Figure 2 shows the various elements that can make up the client tier. The ccommunicates with the business tier running on the J2EE server either direor as in the case of a client running in a browser, by going through JSP pagservlets running in the web tier.
28 OVERVIEW
thebusi-hesehere-side
va pro-structut allow
ppli-ifica-and
va-eans
Figure 2 Server Communications
Thin ClientsJ2EE applications use a thin client. A thin client is a lightweight interface toapplication that does not do things like query databases, execute complexness rules, or connect to legacy applications. Heavyweight operations like tare off-loaded to web or enterprise beans executing on the J2EE server wthey can leverage the security, speed, services, and reliability of J2EE servertechnologies.
Web ComponentsJ2EE web components can be either JSP pages or servlets. Servlets are Jagramming language classes that dynamically process requests and conresponses. JSP pages are text-based documents that execute as servlets, ba more natural approach to creating static content.
Static HTML pages and applets are bundled with web components during acation assembly, but are not considered web components by the J2EE spection. Server-side utility classes can also be bundled with web components,like HTML pages, are not considered web components.
Like the client tier and as shown in Figure 3, the web tier might include a JaBeans object to manage the user input and send that input to enterprise brunning in the business tier for processing.
Web Browser Web pages, applets,
and optional JavaBeans class
Application Client and optional
JavaBeans class
Client Tier
Web TierBusiness
Tier
J2EE Server
DISTRIBUTED MULTITIERED APPLICATIONS 29
busi-eansdata
prisefrom.
d mes-a cli-
ne. Intabaseices
essageJMS
beans.Tuto-
Figure 3 Web Tier and J2EE Application
Business ComponentsBusiness code, which is logic that solves or meets the needs of a particularness domain such as banking, retail, or finance, is handled by enterprise brunning in the business tier. Figure 4 shows how an enterprise bean receivesfrom client programs, processes it (if necessary), and sends it to the enterinformation system tier for storage. An enterprise bean also retrieves datastorage, processes it (if necessary), and sends it back to the client program
There are three kinds of enterprise beans: session beans, entity beans, ansage-driven beans. A session bean represents a transient conversation withent. When the client finishes executing, the session bean and its data are gocontrast, an entity bean represents persistent data stored in one row of a datable. If the client terminates or if the server shuts down, the underlying servensure the entity bean data is saved.
A message-driven bean combines features of a session bean and a Java MService (JMS) message listener, allowing a business component to receivemessages asynchronously. This tutorial describes entity beans and sessionFor information on message-driven beans, see the Java Message Servicerial, which is online at:
http://java.sun.com/products/jms/tutorial/index.html
Web Browser Web pages, applet,
and optional JavaBeans class
Application Client and optional
JavaBeans class
JavaBeans Class
(optional)
JSP Pages Servlets Business
Tier
Web Tier
J2EE Server
30 OVERVIEW
temrprisetems,
needple.
eyent,
om-plica-nentsr foryour-
nter-thatlient
Figure 4 Business and EIS Tiers
Enterprise Information System TierThe enterprise information system tier handles enterprise information syssoftware, and includes enterprise infrastructure systems such as enteresource planning (ERP), mainframe transaction processing, database sysand other legacy information systems. J2EE application components mightaccess to enterprise information systems for database connectivity, for exam
J2EE ArchitectureNormally, thin-client multitiered applications are hard to write because thinvolve many lines of intricate code to handle transaction and state managemmultithreading, resource pooling, and other complex low-level details. The cponent-based and platform-independent J2EE architecture makes J2EE aptions easy to write because business logic is organized into reusable compoand the J2EE server provides underlying services in the form of a containeevery component type. Because you do not have to develop these servicesself, you are free to concentrate on solving the business problem at hand.
Containers and ServicesComponent are installed in their containers during deployment and are the iface between a component and the low-level platform-specific functionalitysupports the component. Before a web, enterprise bean, or application c
Web Browser Web pages, applets,
and optional JavaBeans class
Application Client and optional
JavaBeans class
JavaBeans Class
(optional)
JSP Pages Servlets
Entity Beans Session Beans
Message-Driven Beans
Business Tier
Database &
Legacy Systems
EIS Tier
J2EE Server
J2EE ARCHITECTURE 31
n and
nentngsudectory
igh-
rise
odsare
ndcess
onsted, a
thatntlyhavepro-ction
beanence,
ctureriatethant useor to
component can be executed, it must be assembled into a J2EE applicatiodeployed into its container.
The assembly process involves specifying container settings for each compoin the J2EE application and for the J2EE application itself. Container setticustomize the underlying support provided by the J2EE Server, which inclservices such as security, transaction management, Java Naming and DireInterface™ (JNDI) lookups, and remote connectivity. Here are some of the hlights:
• The J2EE security model lets you configure a web component or enterpbean so system resources are accessed only by authorized users.
• The J2EE transaction model lets you specify relationships among meththat make up a single transaction so all methods in one transactiontreated as a single unit.
• JNDI lookup services provide a unified interface to multiple naming adirectory services in the enterprise so application components can acnaming and directory services.
• The J2EE remote connectivity model manages low-level communicatibetween clients and enterprise beans. After an enterprise bean is creaclient invokes methods on it as if it were in the same virtual machine.
The fact that the J2EE architecture provides configurable services meansapplication components within the same J2EE application can behave differebased on where they are deployed. For example, an enterprise bean cansecurity settings that allow it a certain level of access to database data in oneduction environment and another level of database access in another produenvironment.
The container also manages non-configurable services such as enterpriseand servlet life cycles, database connection resource pooling, data persistand access to the J2EE platform APIs described inJ2EE APIs (page 37).Although data persistence is a non-configurable service, the J2EE architelets you override container-managed persistence by including the appropcode in your enterprise bean implementation when you want more controlthe default container-managed persistence provides. For example, you mighbean-managed persistence to implement your own finder (search) methodscreate a customized database cache.
32 OVERVIEW
ingin this
f allcon-
om-r run
ioneir
un-
Container TypesThe deployment process installs J2EE application components in the followtypes of J2EE containers. The J2EE components and container addressedtutorial are shown in Figure 5.
• An Enterprise JavaBeans (EJB) container manages the execution oenterprise beans for one J2EE application. Enterprise beans and theirtainer run on the J2EE server.
• A web container manages the execution of all JSP page and servlet cponents for one J2EE application. Web components and their containeon the J2EE server.
• An application client container manages the execution of all applicatclient components for one J2EE application. Application clients and thcontainer run on the client machine.
• An applet container is the web browser and Java Plug-in combination rning on the client machine.
Figure 5 J2EE Server and Containers
J2EE Server
Database
EJB Container
Enterprise Bean
Enterprise Bean
Web Container
JSP PageServlet
Application Client Container
Application Client
Client Machine
Browser
PACKAGING 33
cations or
intod of
. Theo or
ptor.edgs.
rans-auseoutploy-
ive
ARinehivein
the
ted
the
ffer-ng isAR
PackagingJ2EE components are packaged separately and bundled into a J2EE applifor deployment. Each component, its related files such as GIF and HTML fileserver-side utility classes, and a deployment descriptor (DD), are assembleda module and added to the J2EE application. A J2EE application is composeone or more enterprise bean, web, or application client component modulesfinal enterprise solution can use one J2EE application or be made up of twmore J2EE applications depending on design requirements
A J2EE application and each of its modules has its own deployment descriA deployment descriptor is an Extensible Markup Language (XML) text-basfile with an .xml extension that describes a component’s deployment settinAn enterprise bean module deployment descriptor, for example, declares taction attributes and security authorizations for an enterprise bean. Becdeployment descriptor information is declarative, it can be changed withmodifying the bean source code. At run time, the J2EE server reads the dement descriptor and acts upon the component accordingly.
A J2EE application with all of its modules is delivered in an Enterprise ARch(EAR) file. An EAR file is a standard JAR file with an.ear extension. In theGUI version of the J2EE SDK application deployment tool, you create an Efile first and add JAR and WAR files to the EAR. If you use the command lpackager tools, however, you create the Java ARchive (JARs) and Web ARc(WAR) files first and create the EAR. The J2EE SDK tools are describedTools (page 40).
• Each EJB JAR file contains its deployment descriptor, related files, and.class files for the enterprise bean.
• Each application client JAR file contains its deployment descriptor, relafiles, and the.class files for the application client.
• Each WAR file contains its deployment descriptor, related files, and.class files for the servlet or.jsp files for a JSP page.
Using modules and EAR files makes it possible to assemble a number of dient J2EE applications using some of the same components. No extra codineeded; it is just a matter of assembling various J2EE modules into J2EE Efiles.
34 OVERVIEW
andper-
ols.ed byand
rolesrkssub-e, antion2EEys-
ppli-
r ayou
le forpeci-tem,orm
bly,yers.r-
Development RolesReusable modules make it possible to divide the application developmentdeployment process into distinct roles so different people or companies canform different parts of the process.
The first two roles involve purchasing and installing the J2EE product and toOnce software is purchased and installed, J2EE components can be developapplication component providers, assembled by application assemblers,deployed by application deployers. In a large organization, each of thesemight be executed by different individuals or teams. This division of labor wobecause each of the earlier roles outputs a portable file that is the input for asequent role. For example, in the application component development phasenterprise bean software developer delivers EJB JAR files. In the applicaassembly role, another developer combines these EJB JAR files into a Japplication and saves it in an EAR file. In the application deployment role, a stem administrator at the customer site uses the EAR file to install the J2EE acation into a J2EE server.
The different roles are not always executed by different people. If you work fosmall company, for example, or if you are prototyping a sample application,might perform the tasks in every phase.
J2EE Product ProviderThe J2EE product provider is the company that designs and makes availabpurchase the J2EE platform, APIs, and other features defined in the J2EE sfication. Product providers are typically operating system, database sysapplication server, or web server vendors who implement the J2EE platfaccording to the Java 2 Platform, Enterprise Edition Specification.
Tool ProviderThe tool provider is the person or company who makes development, assemand packaging tools used by component providers, assemblers, and deploSeeTools (page 40) for information on the tools available with J2EE SDK vesion 1.3.
DEVELOPMENT ROLES 35
web2EE
file
le
fol-
in-
om-2EEentac-
Application Component ProviderThe application component provider is the company or person who createscomponents, enterprise beans, applets, or application clients for use in Japplications.
Enterprise Bean Creation
A software developer performs the following tasks to deliver an EJB JARthat contains the enterprise bean:
• Writes and compiles the source code
• Specifies the deployment descriptor
• Bundles the.class files and deployment descriptor into an EJB JAR fi
Web Component Creation
A web designer (JSP pages) or software developer (servlets) performs thelowing tasks to deliver a WAR file containing the web component.
• Writes and compiles servlet source code
• Writes JSP and HTML files
• Specifies the deployment descriptor for the web component
• Bundles the.class, .jsp, .html, and deployment descriptor files in theWAR file
J2EE Application Client Creation
A software developer performs the following tasks to deliver a JAR file containg the J2EE application client.
• Writes and compiles the source code
• Specifies the deployment descriptor for the client
• Bundles the.class files and deployment descriptor into the JAR file
Application AssemblerThe application assembler is the company or person who gets application cponent JAR files from component providers and assembles them into a Japplication EAR file. The assembler or deployer can edit the deploymdescriptor directly or use tools that correctly add XML tags according to inter
36 OVERVIEW
an
pre-
ith
tion,lica-s ass to
ca-set-
ovesecific
on-
the
od-
ith
rmtra-tion
tive selections. A software developer performs the following tasks to deliverEAR file containing the J2EE application.
• Assembles EJB JAR and web components (WAR) files created in thevious phases into a J2EE application (EAR) file.
• Specifies the deployment descriptor for the J2EE application.
• Verifies that the contents of the EAR file are well-formed and comply wthe J2EE specification.
Application Deployer and AdministratorThe company or person who configures and deploys the J2EE applicaadministers the computing and networking infrastructure where J2EE apptions run, and oversees the runtime environment. Duties include such thingsetting transaction controls, security attributes, and specifying connectiondatabases.
During configuration, the deployer follows instructions supplied by the applition component provider to resolve external dependencies, specify securitytings, and assign transaction attributes. During installation, the deployer mthe application components to the server, and generates the container-spclasses and interfaces.
A deployer/system administrator performs the following tasks to install and cfigure a J2EE application.
• Adds the J2EE application (EAR) file created in the preceding phase toJ2EE server.
• Configures the J2EE application for the operational environment by mifying the deployment descriptor of the J2EE application.
• Verifies that the contents of the EAR file are well-formed and comply wthe J2EE specification.
• Deploys (installs) the J2EE application EAR file into the J2EE server.
Reference Implementation SoftwareThe J2EE SDK is a non-commercial operational definition of the J2EE platfoand specification made freely available by Sun Microsystems for demonstions, prototyping, and educational uses. It comes with the J2EE applica
REFERENCE IMPLEMENTATION SOFTWARE 37
elop-:
nta-theply
theE
ple, aan-ebcan
J2EEhiche theases
entPIs
od-lock
server, web server, relational database, J2EE APIs, and complete set of devment and deployment tools. You can download the J2EE SDK from the web
http://java.sun.com/j2ee/download.html#sdk
• Product providers use the J2EE SDK to determine what their implemetions must do under a given set of application conditions, and to runJ2EE Compatibility Test Suite to test that their J2EE products fully comwith the specification.
• Application component developers run their J2EE applications onJ2EE SDK to verify the applications are fully portable across all J2Eproducts and tools.
Web ServerThe web server provides services to one or more web containers. For examweb container typically relies on a web server to provide HTTP message hdling. A J2EE implementation is not required to support a particular type of wserver, which means the web server supported by different J2EE productsvary.
Database AccessThe relational database provides persistent storage for application data. Aimplementation is not required to support a particular type of database wmeans the database supported by different J2EE products can vary. SeRelease Notes included with the J2EE SDK download for a list of the databcurrently supported by the reference implementation.
J2EE APIsThe Java 2 Platform, Standard Edition (J2SE™) SDK is required to run the J2EESDK and provides core APIs for writing J2EE components, core developmtools, and the Java virtual machine. The J2EE SDK provides the following Ato be used in J2EE applications.
Enterprise JavaBeans Technology 2.0
An enterprise bean is a body of code with fields and methods to implement mules of business logic. You can think of an enterprise bean as a building b
38 OVERVIEW
gic on
d mes-taseyou.rea-
sion
agethe
e data-re han-s noet orrprise
lica-ttach a
rvletay ofany
d by
text-pes ofsuchon-
that can be used alone or with other enterprise beans to execute business lothe J2EE server.
There are three kinds of enterprise beans: session beans, entity beans, ansage-driven beans as described inBusinessComponents (page 29). You do nohave to write any SQL code or use the JDBC™ API directly to perform databaccess operations with an entity bean. The EJB container handles this forHowever, if you override the default container-managed persistence for anyson, you will need to use the JDBC API. Also, if you choose to have a sesbean access the database, you have to use the JDBC API.
JDBC™ 2.0 API
The JDBC API lets you invoke SQL commands from Java programing langumethods. You use the JDBC API in an enterprise bean when you overridedefault container-managed persistence or have a session bean access thbase. With container-managed persistence, database access operations adled by the container and your enterprise bean implementation containJDBC code or SQL commands. You can also use the JDBC API from a servlJSP page to access the database directly without going through an entebean.
The JDBC API has two parts: an application-level interface used by the apption components to access a database, and a service provider interface to aJDBC driver to the J2EE platform.
Java Servlet Technology 2.3
Java Servlet technology lets you define HTTP-specific servlet classes. A seclass extends the capabilities of servers that host applications accessed by wa request-response programming model. Although servlets can respond totype of request, they are commonly used to extend the applications hosteweb servers.
JavaServer Pages (JSP) Technology 1.2
JSP pages technology lets you put snippets of servlet code directly into abased document. A JSP page is a text-based document that contains two tytext: static template data which can be expressed in any text-based formatas HTML, WML, and XML, and JSP elements that determine how the page cstructs dynamic content.
REFERENCE IMPLEMENTATION SOFTWARE 39
entsication
on
sac-sac-onspera-pera-cateand
ormion: anand
it. Itdata,te the
dataamsand
rentsuitsns-
Java Message Service (JMS) 1.0
The JMS API is a messaging standard that allows J2EE application componto create, send, receive, and read messages. It enables distributed communthat is loosely coupled, reliable, and asynchronous. For more informationJMSsee theonline Java Message Service Tutorial:
http://java.sun.com/products/jms/tutorial/index.html
Java Transaction API (JTA) 1.0
The JTA API provides a standard demarcation interface for demarcating trantions. The J2EE architecture provides a default auto commit to handle trantion commits and roll backs. An auto commit means any other applicativiewing data will see the updated data after each database read or write otion. However, if your application performs two separate database access otions that depend on each other, you will want to use the JTA API to demarwhere the entire transaction including both operations begins, rolls back,commits.
JavaMail™ Technology 1.2
Many Internet applications need to send email notifications so the J2EE platfincludes the JavaMail API with a JavaMail service provider that applicatcomponents can use to send Internet mail. The JavaMail API has two partsapplication-level interface used by the application components to send mail,a service provider interface.
JavaBeans Activation Framework 1.0
The JavaBeans Activation Framework is included because JavaMail usesprovides standard services to determine the type of an arbitrary piece ofencapsulate access to it, discover the operations available on it, and creaappropriate JavaBean component to perform those operations.
Java API for XML (JAXP) 1.1
XML is a language for representing and describing text-based data so thecan be read and handled by any program or tool that uses XML APIs. Progrand tools can generate XML files that other programs and tools can readhandle.
For example, a J2EE application can use XML to produce reports, and diffecompanies that receive the reports can handle the data in a way that besttheir needs. One company might put the XML data through a program to tra
40 OVERVIEW
nyandro-
cre-s that
mpo-the
to itspe of
r asers
enti-hi-
toolica-See
l forer-
late the XML to HTML so it can post the reports to the web, another compamight put the XML data through a tool to create a marketing presentation,yet another company might read the XML data into its J2EE application for pcessing.
J2EE Connector API 1.0
The Connector API is used by J2EE tools vendors and system integrators toate resource adapters that support access to enterprise information systemcan be plugged into any J2EE product. A resource adapter is a software conent that allows J2EE application components to access and interact withunderlying resource manager. Because a resource adapter is specificresource manager, there is typically a different resource adapter for each tydatabase or EIS.
Java Authentication and Authorization Service (JAAS) 1.0
The Java Authentication and Authorization Service (JAAS) provides a way foJ2EE application to authenticate and authorize a specific user or group of uto run it.
JAAS is a Java programing language version of the standard Pluggable Authcation Module (PAM) framework that extends the Java 2 platform security arctecture to support user-based authorization.
ToolsThe J2EE reference implementation provides an application deploymentand an array of scripts for assembling, verifying, and deploying J2EE appltions and managing your development and production environments.J2EE™SDK Tools (page 309) for a discussion of the tools.
Application Deployment Tool
The J2EE reference implementation provides an application deployment tooassembling, verifying, and deploying J2EE applications. It comes in two vsions: command-line and GUI.
REFERENCE IMPLEMENTATION SOFTWARE 41
od-
The GUI tool includes wizards for
• Packaging, configuring, and deploying J2EE applications
• Packaging and configuring enterprise beans
• Packaging and configuring web components
• Packaging and configuring application clients
• Packaging and configuring resource adaptors
In addition, configuration information can be set for each component and mule type in the tabbed inspector panels.
42 OVERVIEW
t let
e
-
Scripts
Table 1 lists the scripts included with the J2EE reference implementation thayou perform operations from the command line.
Table 1 J2EE Scripts
Script Description
j2ee Start and stop the J2EE server.
cloudscape Start and stop the default database.
cloudIJ Run the interactive SQL tool. This is an unsupported tool.
j2eeadmin Add JDBC drivers, JMS destinations, and connection factories for variousresources.
keytool Create public and private keys and generate X509 self-signed certificates.
realmtool Import certificate files. Add J2EE users to and remove J2EE users from thauthentication and authorization list for a J2EE application.
packager Package J2EE application components into EAR, EJB JAR, application client JAR, and WAR files.
verifier Verify that EAR, EJB JAR, application client JAR, and WAR files are well-formed and comply with the J2EE specification.
runclient Run a J2EE application client.
cleanup Remove all deployed applications from the J2EE server.
rvercli-
ge.
Getting Startedby Dale Green
THIS chapter shows you how to develop, deploy, and run a simple client-seapplication that consists of an currency conversion enterprise bean and twoents: a J2EE™ application client and a web client that consists of a JSP pa
Setting Up 44Getting the Example Code 44Building the Example 44Checking the Environment Variables 45Starting the J2EE™ Server 45Starting thedeploytool 45
Creating the J2EE™ Application 46Creating the Enterprise Bean 46
Coding the Enterprise Bean 46Compiling the Source Files 48Packaging the Enterprise Bean 48
Creating the J2EE™ Application Client 49Coding the J2EE Application Client 50Compiling the Application Client 52Packaging the J2EE Application Client 52Specifying the Application Client’s Enterprise Bean Reference 53
Creating the Web Client 53Coding the Web Client 53Compiling the Web Client 55Packaging the Web Client 55Specifying the Web Client’s Enterprise Bean Reference 56
Specifying the JNDI Name 56Deploying the J2EE™ Application 57Running the J2EE™ Application Client 58Running the Web Client 59
43
44 GETTING STARTED
the
le
Modifying the J2EE™ Application 59Modifying a Class File 59Adding a File 60Modifying the Web Client 60Modifying a Deployment Setting 60
Common Problems and Their Solutions 61Cannot Start the J2EE Server 61Compilation Errors 61J2EE Application Client Runtime Errors 62Web Client Runtime Errors 63Deployment Errors 64
Setting UpBefore you start developing the example application, you should followinstructions in this section.
Getting the Example CodeThe source code for components is in theexamples/src/ejb/converter direc-tory. If you are viewing this online, you first need to download the tutorial bundfrom:
http://java.sun.com/j2ee/download.html#tutorial
Building the ExampleTo build the example code you’ll need copies of the J2EE SDK andant, a porta-ble make tool. For more information, seeHow to Build and Run theExamples (page xviii).
SETTING UP 45
bles
:
this
Checking the Environment VariablesThe installation instructions for the J2EE SDK andant explain how to set therequired environment variables. Please verify that the environment variahave been set to the values noted in the following table.
Starting the J2EE™ ServerTo launch the J2EE server, open a terminal window and type this command
j2ee -verbose
Although optional, theverbose option is useful for debugging. To stop theserver, type the following command:
j2ee -stop
Starting the deploytoolThe deploytool has two modes: command-line and GUI. The instructions inchapter refer to the GUI version. To start thedeploytool GUI, open a terminalwindow and type this command:
deploytool
To view the tool’s context-sensitive help, pressf1.
Table 2 Required Environment Variables
Environment Variable Value
JAVA_HOME The location of the J2SE™ SDK installation.
J2EE_HOME The location of the J2EE™ SDK installation.
ANT_HOME The location of theant installation.
PATHShould include thebin directory of the J2EE SDK installationand theant installation.
46 GETTING STARTED
an, apo-
busi-usi-
busi-de for
Creating the J2EE™ ApplicationThe sample application contains three J2EE components: an enterprise beJ2EE application client, and a web component. Before building these comnents, you will create a new J2EE application calledConverterApp and willstore it in a file namedConverterApp.ear.
1. In thedeploytool, select File -> New Application.
2. Click Browse.
3. In the file chooser, navigate toexamples/src/ejb/converter.
4. In the File name field enterConverterApp.ear.
5. Click New Application.
6. Click OK.
Creating the Enterprise BeanThe source code for the enterprise bean is in theexamples/src/ejb/converter
directory. An enterprise bean is a server-side component that contains theness logic of an application. At run time, the application clients execute the bness logic by invoking the enterprise bean’s methods.
Coding the Enterprise BeanThe enterprise bean in this example requires the following code:
• Remote interface
• Home interface
• Enterprise bean class
Coding the Remote Interface
A remote interface defines the business methods that a client may call. Theness methods are implemented in the enterprise bean code. The source cotheConverter remote interface follows.
import javax.ejb.EJBObject;import java.rmi.RemoteException;
public interface Converter extends EJBObject {
CREATING THE ENTERPRISEBEAN 47
, or-
the
he
public double dollarToYen(double dollars) throws RemoteException;public double yenToEuro(double yen) throws RemoteException;}
Coding the Home Interface
A home interface defines the methods that allow a client to create, findremove an enterprise bean. TheConverterHome interface contains a single create method, which returns an object of the remote interface type. Here issource code for theConverterHome interface:
import java.io.Serializable;
import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.EJBHome;
public interface ConverterHome extends EJBHome {
Converter create() throws RemoteException, CreateException;}
Coding the Enterprise Bean Class
The enterprise bean in our example is a stateless session bean calledConvert-
erEJB. This bean implements the two business methods,dollarToYen andyen-ToEuro, that theConverter remote interface defines. The source code for tConverterEJB class follows.
import java.rmi.RemoteException;import javax.ejb.SessionBean;import javax.ejb.SessionContext;
public class ConverterEJB implements SessionBean {
public double dollarToYen(double dollars) {
return dollars * 121.6000;}
public double yenToEuro(double yen) {
return yen * 0.0077;}
public ConverterEJB() {}
48 GETTING STARTED
2EE
-
JAR
public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {}}
Compiling the Source FilesNow you are ready to compile the remote interface (Converter.java), homeinterface (ConverterHome.java), and the enterprise bean class (Convert-
erEJB.java):
1. Go to theexamples/src directory.
2. Open the filebuild.xml in a text editor. Edit the following line, setting thevalue of thej2ee-home property to the J2EE SDK installation directory:
<property name="j2ee-home" value="C:\j2sdkee1.3" />
3. In a terminal window type the following command:
ant converter
This command compiles the source files for the enterprise bean and the Japplication client. It places the resulting class files in theexam-ples/build/ejb/converter directory. For more information aboutant, seeHow to Build and Run the Examples (page xviii).
Note:When compiling the code, the precedingant task includes thej2ee.jar filein the classpath. This file resides in thelib directory of your J2EE SDK installa-tion. If you plan on using other tools to compile the source code for J2EE components, make sure that the classpath includes thej2ee.jar file.
Packaging the Enterprise BeanIn this section you will run the New Enterprise Bean Wizard of thedeploytool
to perform these tasks:
• Create the bean’s deployment descriptor.
• Package the deployment descriptor and the bean’s classes in an EJBfile.
• Insert the EJB JAR file into the application’sConverterApp.ear file.
CREATING THE J2EE™ APPLICATION CLIENT 49
an.
rt-
.)
on-you
an-ine
To start the New Enterprise Bean Wizard, select File->New Enterprise BeThe wizard displays the following dialog boxes.
1. Introduction Dialog Box
a. Read this explanatory text for an overview of the wizard’s features.
b. Click Next.
2. EJB JAR Dialog Box
a. In the combo box labelled Enterprise Bean Will Go In, select ConveerApp.
b. In the JAR Display Name field enterConverterJAR.
c. Click the Add button next to the Contents text area.
d. In the tree under Available Files, locate theexamples/build/ejb/con-
verter directory. (Or, you may type the directory name in the top field
e. Select the following classes from the text area and click Add: Cverter.class, ConverterEJB.class, and ConverterHome.class. (Or,may drag them to the bottom field.)
f. Click OK.
g. Click Next.
3. General Dialog Box
a. Under Bean Type, select the Session radio button.
b. Select the Stateless radio button.
c. In the Enterprise Bean Class combo box, select ConverterEJB.
d. In the Home Interface combo box, select ConverterHome.
e. In the Remote Interface combo box, select Converter.
f. In the Enterprise Bean Name field, enterConverterBean.
g. Click Next.
4. Environment Entries Dialog Box
Because you may skip the remaining dialog boxes, click Finish.
Creating the J2EE™ Application ClientA J2EE application client is a program written in the Java™ programming lguage. At run time, the client program executes in a different virtual mach(VM) than the J2EE server.
50 GETTING STARTED
hethepli-
grambeansered
e
e
ed
The J2EE application client in this example requires two different JAR files. Tfirst JAR file is for the J2EE component of the client. This JAR file containsclient’s deployment descriptor and its class files. When you run the New Apcation Client wizard, thedeploytool automatically creates the JAR file andstores it in the application’s EAR file. Defined by theJ2EE Specifications, theJAR file is portable across all compliant J2EE servers.
The second JAR file contains stub classes that are required by the client proat run time. These stub classes enable the client to access the enterprisethat are running in the J2EE server. Because this second JAR file is not covby theJ2EE Specifications, it is implementation-specific, intended only for thJ2EE SDK.
The J2EE application client source code is inexamples/src/ejb/con-verter/ConverterClient.java. You already compiled this code along with thenterprise bean code in the section,Compiling the Source Files (page 48).
Coding the J2EE Application ClientThe ConverterClient.java source code illustrates the basic tasks performby the client of an enterprise bean:
• Locating the home interface
• Creating an enterprise bean instance
• Invoking a business method
Locating the Home Interface
TheConverterHome interface defines life-cycle methods such ascreate. Beforethe ConverterClient can invoke thecreate method, it must instantiate anobject whose type isConverterHome. This is a three-step process:
1. Create a JNDI naming context.
Context initial = new InitialContext();
2. Retrieve the object bound to the nameejb/SimpleConverter.
Object objref = initial.lookup ("java:comp/env/ejb/SimpleConverter");
3. Narrow the reference to aConverterHome object.
CREATING THE J2EE™ APPLICATION CLIENT 51
the
ConverterHome home = (ConverterHome) PortableRemoteObject.narrow(objref, ConverterHome.class);
Creating an Enterprise Bean Instance
To create theConverterEJB class, the client invokes thecreate method on theConverterHome object. Thecreate method returns an object whose type isCon-
verter. The remoteConverter interface defines the business methods inCon-
verterEJB that the client may call. When the client invokes thecreate method,the EJB container instantiatesConverterEJB, and then invokes theConvert-erEJB.ejbCreate method. The client invokes thecreate method as follows:
Converter currencyConverter = home.create();
Invoking a Business Method
Calling a business method is easy—you simply invoke the method on theCon-
verter object. The EJB container will invoke the corresponding method onConverterEJB instance that is running on the server. The client invokes thedol-
larToYen business method in the following line of code.
double amount = currencyConverter.dollarToYen(100.00);
ConverterClient Source Code
The full source code for theConverterClient program follows.
import javax.naming.Context;import javax.naming.InitialContext;import javax.rmi.PortableRemoteObject;import Converter;import ConverterHome;
public class ConverterClient {
public static void main(String[] args) {
try { Context initial = new InitialContext(); Object objref = initial.lookup ("java:comp/env/ejb/SimpleConverter"); ConverterHome home = (ConverterHome)PortableRemoteObject.narrow( objref, ConverterHome.class); Converter currencyConverter = home.create();
52 GETTING STARTED
bean
ients
li-
double amount = currencyConverter.dollarToYen(100.00); System.out.println(String.valueOf(amount)); amount = currencyConverter.yenToEuro(100.00); System.out.println(String.valueOf(amount));
currencyConverter.remove();
} catch (Exception ex) {System.err.println(“Caught an unexpected exception!”);
ex.printStackTrace(); } }}
Compiling the Application ClientThe application client files are compiled at the same time as the enterprisefiles as described inCompiling the Source Files (page 48).
Packaging the J2EE Application ClientTo package an application client component, you run the New Application ClWizard of thedeploytool. During this process, the wizard puts the client fileinto a JAR file and then adds the JAR file to the application’sConverterApp.ear
file.
To start the New Application Client Wizard, select File->New Application Cent. The wizard displays the following dialog boxes.
1. Introduction Dialog Box:
a. Read this explanatory text for an overview of the wizard’s features.
b. Click Next.
2. JAR File Contents Dialog Box
a. Click the Add button next to the Contents text area.
b. In the tree under Available Files, locate theexamples/build/ejb/con-
verter directory.
c. Select ConverterClient.class and click Add.
d. Click OK.
e. Click Next.
CREATING THE WEB CLIENT 53
ged
se
aticTML,
g ancal to
3. General Dialog Box:
a. In the Main Class combo box, select ConverterClient.
b. Verify that the entry in the Display Name field is ConverterClient.
c. In the Callback Handler Class combo box, select container-manaauthentication.
d. Click Finish.
Specifying the Application Client’s Enterprise BeanReferenceWhen it invokes thelookup method, the ConverterClient refers to an enterpribean:
Object objref = initial.lookup ("java:comp/env/ejb/SimpleConverter");
You specify this reference as follows:
1. In the tree, select ConverterClient.
2. Select the EJB Ref’s tab.
3. Click Add.
4. In the Coded Name column enterejb/SimpleConverter.
5. In the Type column, select Session.
6. In the Home column enterConverterHome.
7. In the Remote column enterConverter.
Creating the Web ClientThe web client is contained in the JSP pageexamples/src/ejb/con-verter/index.jsp. A JSP page is a text-based document that contains sttemplate data, which can be expressed in any text-based format such as HWML, and XML and JSP elements, which construct dynamic content.
Coding the Web ClientThe statements (highlighted below) for locating the home interface, creatinenterprise bean instance, and invoking a business method are nearly identithose of the J2EE application client. (The parameter of thelookup method is the
54 GETTING STARTED
hey
l-Ae
result
only difference.) Because the first two functions are performed only once, tappear in a JSP declaration (enclosed within the<%! %> characters), that con-tains the initialization method,jspInit, of the JSP page. The declaration is folowed by standard HTML markup for creating a form with an input field.scriptlet (enclosed within the<% %> characters) retrieves a parameter from threquest and converts it to a double. Finally, JSP expressions (enclosed within<%=
%> characters) invoke the enterprise bean’s business methods and insert theinto the stream of data returned to the client.
<%@ page import="javax.ejb.*, javax.naming.*,javax.rmi.PortableRemoteObject, java.rmi.RemoteException" %><%! private Converter converter = null; public void jspInit() { try {
InitialContext ic = new InitialContext(); Object objRef = ic.lookup(" java:comp/env/ejb/TheConverter"); ConverterHome home = (ConverterHome)PortableRemoteObject.narrow( objRef, ConverterHome.class);
converter = home.create(); } catch (RemoteException ex) { ... } } ...%><html><head> <title>Converter</title></head>
<body bgcolor="white"><h1><center>Converter</center></h1><hr><p>Enter an amount to convert:</p><form method="get"><input type="text" name="amount" size="25"><br><p><input type="submit" value="Submit"><input type="reset" value="Reset"></form><% String amount = request.getParameter("amount");
CREATING THE WEB CLIENT 55
f thele
ent.
ct
if ( amount != null && amount.length() > 0 ) { Double d = new Double (amount);%> <p><%= amount %> dollars are
<%= converter.dollarToYen(d.doubleValue()) %> Yen. <p><%= amount %> Yen are
<%= converter.yenToEuro(d.doubleValue()) %> Euro.<% }%></body></html>
Compiling the Web ClientThe J2EE server automatically compiles the web client.
Packaging the Web ClientTo package a web component, you run the New Web Component Wizard odeploytool. During this process, the wizard puts the client files into a WAR fiand then adds the WAR file to the application’sConverterApp.ear file.
To start the New Web Component Wizard, select File->New Web ComponThe wizard displays the following dialog boxes.
1. Introduction Dialog Box:
a. Read this explanatory text for an overview of the wizard’s features.
b. Click Next.
2. WAR File General Properties Dialog Box
a. In the combo box labelled Create New WAR File in Application, seleConverterApp.
b. In the WAR Display Name field, enterConverterWAR.
c. Click Add.
d. Navigate toexamples/build/ejb/converter.
e. Select index.jsp.
f. Click Add.
g. Click OK
h. Click Next
56 GETTING STARTED
n:
nter-lica-
s inndi-mble
3. Choose Component Type Dialog Box
a. Select the JSP radio button.
b. Click Next.
4. Component General Properties Dialog Box
a. In the JSP Filename combo box, select index.jsp.
b. In the Web Component Name field, enterconverter.
c. Click Next.
d. Click Finish.
Specifying the Web Client’s Enterprise BeanReferenceWhen it invokes thelookup method, the web client refers to an enterprise bea
Object objref = initial.lookup ("java:comp/env/ejb/TheConverter");
You specify this reference as follows:
1. In the tree, select ConverterWAR.
2. Select the EJB Ref’s tab.
3. Click Add.
4. In the Coded Name column enterejb/TheConverter.
5. In the Type column, select Session.
6. In the Home column enterConverterHome.
7. In the Remote column enterConverter.
Specifying the JNDI NameAlthough the J2EE application client and the web client access the same eprise bean, their code refers to the bean by different names. The J2EE apption client refers to the bean asSimpleConverter, but the web client refers to itasTheConverter. These references are in the parameters of thelookup calls. Inorder for thelookup method to retrieve the bean, you must map the referencethe code to the bean’s JNDI name. Although this mapping adds a level of irection, it decouples the clients and the beans, making it easier to asseapplications from J2EE components.
DEPLOYING THE J2EE™ APPLICATION 57
llow
the
loy-
to
To map the bean references in the clients to the JNDI name of the bean, fothese steps:
1. In the tree, select ConverterApp.
2. Select the JNDI Names tab.
3. To specify a JNDI name for the bean, in the Application table locateConverterBean component and enterMyConverter in the JNDI Name col-umn.
4. To map the references, in the References table enterMyConverter in theJNDI Name for each row.
Deploying the J2EE™ ApplicationNow that the J2EE application contains the components, it is ready for depment.
1. Select Tools->Deploy.
2. In the Introduction dialog box, select ConverterApp for the ObjectDeploy and localhost for the Target Server.
3. Select the checkbox labelled Return Client Jar.
4. In the text field that appears, enter the full path name for the fileConvert-
erAppClient.jar so that it will reside in theexamples/src/ejb/con-verter subdirectory. TheConverterAppClient.jar file contains the stubclasses that enable remote access to theConverterBean.
5. Click Next.
58 GETTING STARTED
evi-
ent
ustce
eld
6. In the JNDI Names dialog box, check the names you entered in the prous section.
7. Click Next.
8. In the WAR Context Root dialog box, enterconverter in the Context Rootfield. When you run the web client, theconverter context root will be partof the URL.
9. In the Review dialog box, click Finish.
10. In the Deployment Progress dialog box, click OK when the deploymcompletes.
Running the J2EE™ Application Client1. In a terminal window, go to theexamples/src/ejb/converter directory.
2. Verify that this directory contains theConverterApp.ear andConverter-AppClient.jar files.
3. Set the APPCPATH environment variable to ConverterAppClient.jar.
4. If the client resides on a different machine than the J2EE server, you mset the VMARGS environment variable to the following value. Repla<host> with the name of the host running the J2EE server.
-Dorg.omg.CORBA.ORBInitialHost=<host>
5. Type the following command:
runclient -client ConverterApp.ear -name ConverterClient
6. The client container pops open a login window. In the User Name fienterguest and in the Password field enterguest123.
7. In the terminal window, the client displays these lines:
Binding name:‘java:comp/env/ejb/SimpleConverter‘12160.00.77Unbinding name:‘java:comp/env/ejb/SimpleConverter‘
RUNNING THE WEB CLIENT 59
on
ra-must
com-t to
Running the Web ClientTo run the web client point your browser at the following URL. Replace<host>
with the name of the host running the J2EE server. If your browser is runningthe same host as the J2EE server, you may replace<host> with localhost.
http://<host>:8000/converter
You should see the following after entering100 in the input field and clickingSubmit:
Modifying the J2EE™ ApplicationSince the J2EE SDK is intended for experimentation, it directly supports itetive development. Whenever you make a change to a J2EE application, youredeploy the application.
Modifying a Class FileTo modify a class file in an enterprise bean, you change the source code, repile it, and redeploy the application. For example, suppose that you wanchange the exchange rate in thedollarToYen business method of theConvert-erEJB class:
1. Edit theConverterEJB.java source file.
2. RecompileConverterEJB.java by typingant converter.
60 GETTING STARTED
e
m
n.
JNDI
3. In thedeploytool, select Tools->Update and Redeploy Application. Thdeploytool replaces the old class file inConverterApp.ear with the newone and then redeploys the application.
Adding a FileTo add a file to the EJB JAR or WAR of the application, you would perforthese steps:
1. Select the JAR or WAR in the tree.
2. Select the General tab.
3. Click the Add button to the right of the Contents field.
4. In the Edit Contents dialog box, locate the file and click Add.
5. From the main toolbar, select Tools->Update and Redeploy Applicatio
Modifying the Web ClientTo modify the web client, you simply edit the JSP page and redeployConvert-
erApp.
Modifying a Deployment SettingTo modify a deployment setting ofConverterApp, you edit the appropriate fieldin a tabbed pane and redeploy the application. For example, to change thename of theConverterBean from ATypo to MyConverter, you would followthese steps:
1. In thedeploytool, select ConverterApp in the tree.
2. Select the JNDI Names tab.
3. In the JNDI Name field, enterMyConverter.
4. Select Tools->Update and Redeploy Application.
COMMON PROBLEMS AND THEIR SOLUTIONS 61
run-
port
Common Problems and Their Solutions
Cannot Start the J2EE Server
Naming and Directory Service Port Conflict
Symptom: When you start the J2EE server with the-verbose option, it displaysthese lines:
J2EE server listen port: 1050RuntimeException: Could not initialize server. . .
Solution: Another process is using port 1050. If the J2EE server is alreadyning, you can stop it by typingj2ee -stop. If some other program is using theport, then you can change the default port number (1050) by editing thecon-
fig/orb.properties file of your J2EE SDK installation.
For more information about default port numbers, see theConfiguration Guidein the documentation download bundle of the J2EE SDK.
Web Service Port Conflict
Symptom: When you start the J2EE server with the-verbose option, it displaysthese lines:
LifecycleException: HttpConnector[8000].open:java.net.BindException: Address in use. . .
Solution: Another process is using port 8000. You can change the defaultnumber (8000) by editing theconfig/web.properties file of your J2EE SDKinstallation.
Compilation Errors
Ant Cannot Locate the Build File
Symptom: When you typeant converter, these messages appear:
Searching for build.xmlCould not locate a build file!
Solution: Before runningant, go theexamples/src directory:
62 GETTING STARTED
,
hat
The Compiler Cannot Resolve Symbols
Symptom: When you typeant converter, the compiler reports many errorsincluding these:
cannot resolve symbol. . .BUILD FAILED. . .Compile failed, messages should have been provided
Solution: Make sure you’ve edited thebuild.xml so that the value of thej2ee-home property is set to the J2EE SDK installation directory. SeeCompiling theSource Files (page 48).
J2EE Application Client Runtime Errors
The Client Cannot Find ConverterApp.ear
Symptom: The client reports this exception:
IOException: ConverterApp.ear does not exist
Solution: Ensure that theConverterApp.ear file exists and that you’ve specifiedit with the-client option:
runclient -client ConverterApp.ear -name ConverterClient
You created theConverterApp.ear file in the section,Creatingthe J2EE™Application (page 46). See also,Running the J2EE™ ApplicationClient (page 58).
The Client Cannot Find the ConverterClient Component
Symptom: The client displays this line:
No application client descriptors defined for: . . .
Solution: Verify that you’ve created the ConverterClient component and tyou’ve specified it for the-name option of therunclient command. You createdthe ConverterClient component in the section,Packagingthe J2EEApplicationClient (page 52).
COMMON PROBLEMS AND THEIR SOLUTIONS 63
is
tion,n-
The Login Failed
Symptom: After you click OK in the login dialog box, the client reports thexception:
FailedLoginException: Password Incorrect
Solution: In the login dialog box, enterguest as the user name andguest123 asthe password.
The J2EE Application Has Not Been Deployed
Symptom: The client reports the following exception:
NameNotFoundException. Root exception is org.omg.CosNaming. . .
Solution: Deploy the application. For instructions, seeDeploying the J2EE™Application (page 57).
The JNDI Name is Incorrect
Symptom: The client reports the following exception:
NameNotFoundException. Root exception is org.omg.CosNaming. . .
Solution: In the JNDI Names tabbed pane of theConverterApp, make sure thatthe JNDI names for theConverterBean and theejb/SimpleConverter match.Edit the appropriate JNDI Name field and then redeploy the application.
Web Client Runtime Errors
The Web Context in the URL is Incorrect
Symptom: The browser reports that the page cannot be found (HTTP 404).
Solution: Verify that the web context (converter) in the URL matches the oneyou specified in the Component General Properties dialog box in the secPackagingtheWebClient (page 55). The case (upper or lower) of the web cotext is significant.
The J2EE Application Has Not Been Deployed
Symptom: The browser reports that the page cannot be found (HTTP 404).
Solution: Deploy the application.
64 GETTING STARTED
at
MLthe
h as
The JNDI Name is Incorrect
Symptom: When you click Submit on the web page, the browser reports thA
Servlet Exception Has Occurred.
Solution: In the JNDI Names tabbed pane of theConverterApp, make sure thatthe JNDI names for theConverterBean and theConverterWAR match. Edit theappropriate JNDI Name field and then redeploy the application.
Deployment ErrorsIf you experience deployment errors, it could be because you have an Xparser in your classpath that gets invoked before the parser included withJ2EE SDK. For example, make sure you remove any parser libraries sucjaxp.jar from yourjdk1.3/lib/ext directory.
clientessione-
ses-t anssionto ter-
s intoow
Session Beansby Dale Green
A session bean represents a single client inside the J2EE™ server. Theaccesses remote services by invoking the session bean’s methods. The sbean performs work for its client, shielding the client from complexity by excuting business tasks inside the server.
As its name suggests, a session bean is similar to an interactive session. Asion bean is not shared—it may have just one client, in the same way thainteractive session may have just one user. Like an interactive session, a sebean is not persistent. When the client terminates, its session bean appearsminate and is no longer associated with the client.
Session beans are powerful because they extend the reach of your clientremote servers—yet they’re easy to build. The following section shows you hto construct a simple session bean.
A Session Bean Example 66Session Bean Class 66Helper Classes 72
State Management Modes 72Stateful Session Beans 72Stateless Session Beans 73Choosing Between Stateful and Stateless Session Beans 73
The Life Cycle of a Session Bean 74The Stateful Session Bean Life Cycle 74The Stateless Session Bean Life Cycle 75
Other Enterprise Bean Features 76Accessing Environment Entries 76Comparing Enterprise Beans 77Passing an Enterprise Bean’s Object Reference 78
65
66 SESSIONBEANS
bookrieveode:
s of as. The
A Session Bean ExampleThe session bean in this section represents the shopping cart in an onlinestore. The bean’s client may add a book to the cart, remove a book, or retthe cart’s contents. To construct this session bean, you need the following c
• Session Bean Class (CartEJB)
• Home Interface (CartHome)
• Remote Interface (Cart)
The preceding files are required for any enterprise bean. To meet the needspecific application, an enterprise bean may also need some helper classeCartEJB session bean uses two helper classes,BookException andIdVerifier,which are discussed in the section,Helper Classes (page 72).
The source code for this example is in theexamples/src/ejb/cart directory.To compile the code, go to theexamples/src directory and typeant cart.
Session Bean ClassThe session bean class for this example is calledCartEJB. Like any sessionbean, theCartEJB class must meet these requirements:
It implements theSessionBean interface.
• The class is defined as public.
• The class cannot be defined asabstract or final.
• It implements one or moreejbCreate methods.
• It implements the business methods.
• It contains apublic constructor with no parameters.
• It must not define thefinalize method.
The source code forCartEJB follows:
import java.util.*;import javax.ejb.*;
public class CartEJB implements SessionBean {
String customerName; String customerId; Vector contents;
A SESSIONBEAN EXAMPLE 67
public void ejbCreate(String person) throws CreateException {
if (person == null) { throw new CreateException(“Null person not allowed.”); } else { customerName = person; }
customerId = “0”; contents = new Vector(); }
public void ejbCreate(String person, String id) throws CreateException {
if (person == null) { throw new CreateException(“Null person not allowed.”); } else { customerName = person; }
IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new CreateException(“Invalid id: “ + id); }
contents = new Vector(); }
public void addBook(String title) {
contents.addElement(title); }
public void removeBook(String title) throws BookException {
boolean result = contents.removeElement(title); if (result == false) { throw new BookException(title + “ not in cart.”); } }
public Vector getContents() {
68 SESSIONBEANS
em
t
rectlybean.
return contents; }
public CartEJB() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {}
}
The SessionBean Interface
The SessionBean interface extends theEnterpriseBean interface, which inturn extends theSerializable interface. TheSessionBean interface declaresthe ejbRemove, ejbActivate, ejbPassivate, andsetSessionContext meth-ods. TheCartEJB class doesn’t use these methods, but it must implement thbecause they’re declared in theSessionBean interface. Consequently, thesemethods are empty in theCartEJB class. Later sections explain when you mighuse these methods.
The ejbCreate Methods
Because an enterprise bean runs inside an EJB container, a client cannot diinstantiate the bean. Only the EJB container can instantiate an enterpriseDuring instantiation, the example program performs these steps:
1. The client invokes acreate method on the home object:
Cart shoppingCart = home.create(“Duke DeEarl”,”123”);
2. The EJB container instantiates the enterprise bean.
3. The EJB container invokes the appropriateejbCreate method inCartEJB:
public void ejbCreate(String person, String id) throws CreateException {
if (person == null) { throw new CreateException(“Null person not allowed.”); } else { customerName = person; }
IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) {
A SESSIONBEAN EXAMPLE 69
he
res of
. Therned
odsfol-
customerId = id; } else { throw new CreateException(“Invalid id: “ + id); }
contents = new Vector();}
Typically, anejbCreate method initializes the state of the enterprise bean. TprecedingejbCreate method, for example, initializes thecustomerName andcustomerId variables with the arguments passed by thecreate method.
An enterprise bean may have one or more ejbCreate methods. The signatuthe methods meet the following requirements:
• The access control modifier must bepublic.
• The return type must bevoid.
• The arguments must be legal types for Java RMI.
• The modifier cannot bestatic or final.
The throws clause may include thejavax.ejb.CreateException and otherexceptions that are specific to your application. TheejbCreate method usuallythrows aCreateException if an input parameter is invalid.
Business Methods
The primary purpose of a session bean is to run business tasks for the clientclient invokes business methods on the remote object reference that is retuby the create method. From the client’s perspective, the business methappear to run locally, but they actually run remotely in the session bean. Thelowing code snippet shows how theCartClient program invokes the businessmethods:
Cart shoppingCart = home.create(“Duke DeEarl”, “123”);. . .shoppingCart.addBook(“The Martian Chronicles”);shoppingCart.removeBook(“Alice In Wonderland”);bookList = shoppingCart.getContents();
TheCartEJB class implements the business methods in the following code:
70 SESSIONBEANS
tec-
on.
ata-
a-
r-
public void addBook(String title) {
contents.addElement(new String(title));}
public void removeBook(String title) throws BookException {
boolean result = contents.removeElement(title); if (result == false) { throw new BookException(title + “ not in cart.”); }}
public Vector getContents() { return contents;}
The signature of a business method must conform to these rules:
• The method name must not conflict with one defined by the EJB architure. For example, you cannot call a business methodejbCreate orejbActivate.
• The access control modifier must bepublic.
• The arguments and return types must be legal types for Java RMI.
• The modifier must not bestatic or final.
Thethrows clause may include exceptions that you define for your applicatiTheremoveBook method, for example, throws theBookException if the book isnot in the cart.
To indicate a system-level problem, such as the inability to connect to a dbase, a business method should throw thejavax.ejb.EJBException. When abusiness method throws anEJBException, the container wraps it in aRemote-Exception, which is caught by the client. The container will not wrap appliction exceptions such asBookException. BecauseEJBException is a subclass ofRuntimeException, you do not need to include it in thethrows clause of thebusiness method.
Home Interface
A home interface extends theEJBHome interface. The purpose of the home inteface is to define the create methods that a client may invoke. TheCartClient
program, for example, invokes this create method:
Cart shoppingCart = home.create(“Duke DeEarl”, “123”);
A SESSIONBEAN EXAMPLE 71
an.
Every create method in the home interface corresponds to anejbCreate
method in the bean class. The signatures of theejbCreate methods in theCartEJB class follow:
public void ejbCreate(String person) throws CreateException. . .public void ejbCreate(String person, String id) throws CreateException
Compare theejbCreate signatures with those of thecreate methods in theCartHome interface:
import java.io.Serializable;import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.EJBHome;
public interface CartHome extends EJBHome { Cart create(String person) throws RemoteException, CreateException; Cart create(String person, String id) throwsRemoteException, CreateException;}
The signatures of theejbCreate andcreate methods are similar, but differ inimportant ways. The rules for defining the signatures of thecreate methods of ahome interface follow:
• The number and types of arguments in acreate method must match thoseof its correspondingejbCreate method.
• The arguments and return type of thecreate method must be valid RMItypes.
• A create method returns the remote interface type of the enterprise be(But anejbCreate method returns void.)
• The throws clause of the create method must include thejava.rmi.RemoteException and thejavax.ejb.CreateException.
Remote Interface
The remote interface, which extendsjavax.ejb.EJBObject, defines the busi-ness methods that a client may invoke. Here is the source code for theCart
remote interface:
72 SESSIONBEANS
d in
al tolass.
d
oose
e the
lientt nature
import java.util.*;import javax.ejb.EJBObject;import java.rmi.RemoteException;
public interface Cart extends EJBObject {
public void addBook(String title) throws RemoteException; public void removeBook(String title) throws BookException,
RemoteException; public Vector getContents() throws RemoteException;}
The method definitions in a remote interface must follow these rules:
• Each method in the remote interface must match a method implementethe enterprise bean class.
• The signatures of the methods in the remote interface must be identicthe signatures of the corresponding methods in the enterprise bean c
• The arguments and return values must be valid RMI types.
• Thethrows clause must include thejava.rmi.RemoteException.
Helper ClassesTheCartEJB bean has two helper classes:BookException andIVerifier. TheBookException is thrown by theremoveBook method and theIdVerifier vali-dates thecustomerId in one of theejbCreate methods. Helper classes shoulreside in the EJB JAR file that contains the enterprise bean class
State Management ModesWhen you specify the deployment descriptor of a session bean, you must chbetween two state management modes: stateful or stateless.
Stateful Session BeansThe CartEJB example, discussed inSessionBean Class (page 66), has threeinstance variables:customerName, customerId, andcontents. These variablesrepresent the conversational state of the shopping cart application. BecausCartEJB contains a conversational state, it is called a stateful session bean.
The state is retained for the duration of the client-bean session. When the cremoves the bean, the session ends and the state disappears. This transien
STATE MANAGEMENT MODES 73
ween
ticulartancehenthodcon-
betteranans to
daryy stor-beans.
ssion
ndi-
oca-
of the state is not a problem, however, because when the conversation betthe client and the bean ends there is no need to retain the state.
Stateless Session BeansA stateless session bean does not maintain a conversational state for a parclient. When a client invokes the method of a stateless bean, the beans’s insvariables may contain a state, but only for the duration of the invocation. Wthe method is finished, the state is no longer retained. Except during meinvocation, all instances of a stateless bean are equivalent, allowing the EJBtainer to assign an instance to any client.
Because stateless session beans can support multiple clients, they can offerscalability for applications that require large numbers of clients. Typically,application requires fewer stateless session beans than stateful session besupport the same number of clients.
At times, the EJB container may write a stateful session bean out to seconstorage. However, stateless session beans are never written out to secondarage. Therefore, stateless beans may offer better performance than stateful
The home interface of a stateless session bean must have a singlecreate methodwith no arguments. The session bean class must contain oneejbCreate method,also without arguments. (The arguments are only needed by stateful sebeans, which use them to initialize their states.)
Choosing Between Stateful and Stateless SessionBeansYou should consider using a stateful session bean if any of the following cotions are true:
• The bean’s state must be initialized when it is created.
• The bean needs to hold information about the client across method invtions.
• The client is an interactive application.
74 SESSIONBEANS
2EEmay
r cli-om a
thod
Thegh
hercess.
s life-
usi-
assi-the
ssiva-
it iso the
JBr
bys,ted.
Since the primary goal of a session bean is to represent a client in the Jserver, most of your session beans will be stateful. However, sometimes youwant to use stateless session beans:
• The bean performs a task that is not tailored to the needs of a particulaent. For example, you might use a stateless session bean to fetch frdatabase a commonly used set of data.
• The bean doesn’t need to hold information about the client across meinvocations.
The Life Cycle of a Session BeanA session bean goes through various stages during its lifetime, or life cycle.life cycle is managed by the EJB container, not by your applications. Althouyour applications cannot explicitly manage a bean’s life cycle, you’ll find tinformation in the following sections useful when you need to manage resousuch as database connections. SeeResource Connections (page 269) for detail
The Stateful Session Bean Life CycleFigure 6 illustrates the stages that a session bean passes through during ittime. The client initiates the life cycle by invoking thecreate method.The EJBcontainer instantiates the bean and then invokes thesetSessionContext andejbCreate methods in the session bean. The bean is now ready to have its bness methods invoked.
While in the ready stage, the EJB container may decide to deactivate, or pvate, the bean by moving it from memory to secondary storage. (Typically,EJB container uses a least-recently-used algorithm to select a bean for pation.) The EJB container invokes the bean’sejbPassivate method immediatelybefore passivating it. If a client invokes a business method on the bean whilein the passive stage, the EJB container activates the bean, moving it back tready stage, and then calls the bean’sejbActivate method.
At the end of the life cycle, the client invokes the remove method and the Econtainer calls the bean’sejbRemove method. The bean’s instance is ready fogarbage collection.
Your code controls the invocation of only two life cycle methods—thecreate
andremove methods in the client. All other methods in Figure 6 are invokedthe EJB container. TheejbCreate method, for example, is inside the bean clasallowing you to perform certain operations right after the bean is instantia
THE LIFE CYCLE OF A SESSIONBEAN 75
st twoure 7
For instance, you may wish to connect to a database in theejbCreate method.SeeResource Connections (page 269) for more information.
Figure 6 Life Cycle of a Stateful Session Bean
The Stateless Session Bean Life CycleBecause a stateless session bean is never passivated, its life cycle has justages: non-existent and ready for the invocation of business methods. Figillustrates the stages of a stateless session bean.
1. create 2. setSessionContext 3. ejbCreate
1. remove 2. ejbRemove
ejbPassivate
ejbActivate
Does Not Exist
Ready Passive
76 SESSIONBEANS
is ahoutxam-loy-on
tethod
Figure 7 Life Cycle of a Stateless Session Bean
Other Enterprise Bean FeaturesThe topics that follow apply to both session and entity beans.
Accessing Environment EntriesStored in an enterprise bean’s deployment descriptor, an environment entryname-value pair that allows you to customize the bean’s business logic witchanging its source code. An enterprise bean that calculates discounts, for eple, might have an environment entry named “Discount Percent.” Before deping the bean’s application, you could assign “Discount Percent” a value of .05the Environment tabbed pane of thedeploytool. When you run the application,the enterprise bean fetches the .05 value from its environment.
In the following code example, theapplyDiscount method uses environmenentries to calculate a discount based on the purchase amount. First, the m
1. setSessionContext 2. ejbCreate
ejbRemove
Does Not Exist
Ready
OTHER ENTERPRISEBEAN FEATURES 77
, if
the
locates the environment naming context by invokinglookup with thejava:comp/env parameter. Then it callslookup on the environment to get thevalues for the “Discount Level” and “Discount Percent” names. For exampleyou assign a value of .05 to the “Discount Percent” name in thedeploytool, thecode will assign .05 to thediscountPercent variable. TheapplyDiscountmethod, which follows, is in theCheckerEJB class. The source code for thisexample is inexamples/src/ejb/checker.
public double applyDiscount(double amount) {
try {
double discount;
Context initial = new InitialContext(); Context environment = (Context)initial.lookup(“java:comp/env”);
Double discountLevel = (Double)environment.lookup(“Discount Level”); Double discountPercent = (Double)environment.lookup(“Discount Percent”);
if (amount >= discountLevel.doubleValue()) { discount = discountPercent.doubleValue(); } else { discount = 0.00; }
return amount * (1.00 - discount);
} catch (NamingException ex) { throw new EJBException(“NamingException: “ + ex.getMessage()); } }
Comparing Enterprise BeansA client can determine if two stateful session beans are identical by invokingisIdentical method:
78 SESSIONBEANS
notherbean
thes thean’snce)
th, the
bookCart = home.create(“Bill Shakespeare”);videoCart = home.create(“Lefty Lee”);. . .if (bookCart.isIdentical(bookCart)) { // true . . . }if (bookCart.isIdentical(videoCart)) { // false . . . }
Because stateless session beans have the same object identity, theisIdentical
method always returnstrue when used to compare them.
To determine if two entity beans are identical, the client can invoke theisIden-
tical method, or it can fetch and compare the beans’s primary keys:
String key1 = (String)accta.getPrimaryKey();String key2 = (String)acctb.getPrimaryKey();
if (key1.compareTo(key2) == 0) System.out.println(“equal”);
Passing an Enterprise Bean’s Object ReferenceSuppose that your enterprise bean needs to pass a reference to itself to abean. You might want to pass the reference, for example, so that the secondcan call the first bean’s methods. You can’t pass thethis reference because itpoints to the bean’s instance, which is running in the EJB container. Onlycontainer may directly invoke methods on the bean’s instance. Clients accesinstance indirectly by invoking methods on the object whose type is the beremote interface. It is the reference to this object (the bean’s remote referethat the first bean would pass to the second bean.
A session bean obtains its remote reference by calling thegetEJBObject methodof theSessionContext interface. An entity bean would call thegetEJBObjectmethod of theEntityContext interface. These interfaces provide beans wiaccess to the instance contexts maintained by the EJB container. Typicallybean saves the context in thesetSessionContext method. The following codefragment shows how a session bean might use these methods.
public class WagonEJB implements SessionBean {
SessionContext context; . . . public void setSessionContext(SessionContext sc) { this.context = sc; }
OTHER ENTERPRISEBEAN FEATURES 79
. . . public void passItOn(Basket basket) { . . . basket.copyItems(context.getEJBObject()); } . . .
80 SESSIONBEANS
ism,se toducts.ntity
Entity Beansby Dale Green
AN entity bean represents an entity kept in a persistent storage mechanusually a database. A business application, for example, might use a databastore business entity objects such as accounts, customers, orders, and proInside the J2EE™ server, this application would represent the business eobjects with entity beans.
Characteristics of Entity Beans 82Persistence 82Shared Access 83Primary Key 83
A Bean-Managed Persistence Example 83Entity Bean Class 84The EntityBean Interface 84Home Interface 92Remote Interface 94Tips for Running theAccountEJB Example 94
Mapping Table Relationships For Bean-Managed Persistence 96One-to-One Relationships 97One-to-Many Relationships 100Many-to-Many Relationships 108
About Container-Managed Persistence 111A Container-Managed Persistence Example 111Primary Key Class 111
Creating a Primary Key Class 112Class Requirements 113Bean-Managed Persistence and the Primary Key Class 113Container-Managed Persistence and the Primary Key Class 114Getting the Primary Key 114
Handling Exceptions 115
81
82 ENTITY BEANS
rsis-
ersis-f theu’re
it stillt ser-
d. Youn in
s the
ratesentity
en-f this
The Life Cycle of an Entity Bean 116
Characteristics of Entity BeansEntity beans differ from session beans in several ways. Entity beans are petent, allow shared access, and have primary keys.
PersistenceBecause the state of an entity bean is saved in a storage mechanism, it is ptent. Persistence means that the entity bean exists beyond the lifetime oapplication or the J2EE server process. If you’ve worked with databases, yofamiliar with persistent data. The data in a database is persistent becauseexists even after you shut down the database server or the applications ivices.
There are two types of persistence: bean-managed and container-managedeclare the persistence type with the deploytool, which stores the informatiothe entity bean’s deployment descriptor.
Bean-Managed Persistence
With bean-managed persistence, the entity bean code that you write containcalls that access the database. TheejbCreate method, for example, will issuethe SQLinsert statement. You are responsible for coding theinsert statementand any other necessary SQL calls. SeeA Bean-ManagedPersistenceExample (page 83).
Container-Managed Persistence
If the container manages an entity bean’s persistence, it automatically genethe necessary database access calls. For example, when a client creates anbean, the container generates a SQLinsert statement. The code that you writefor the entity bean includes no SQL calls. As a result, the entity bean is indepdent of any particular datastore, such as a relational database. Because oindependence, the beans are portable across all compliant J2EE servers.
A BEAN-MANAGED PERSISTENCEEXAMPLE 83
s over
epen-cause2EE
iner,
antsac-pec-nots the
forpri-ma-
. The.
Entity beans with container-managed persistence has several advantagethose with bean-managed persistence:
• They require less code.
• Because they don’t contain the database access calls, their code is inddent of any particular data store, such as a relational database. And beof this independence, the beans are portable across all compliant Jservers.
• Their relationships with other objects are managed by the EJB contanot by routines in bean’s code.
Shared AccessEntity beans may be shared by multiple clients. Because the clients might wto change the same data, it’s important that entity beans work within trantions. Typically, the EJB container provides transaction management. You sify the transaction attributes in the bean’s deployment descriptor. You dohave to code the transaction boundaries in the bean—the container markboundaries for you. SeeTransactions (page 235) for more information.
Primary KeyEach entity bean has a unique object identifier. A customer entity bean,example, might be identified by a customer number. The unique identifier, ormary key, enables the client to locate a particular entity bean. For more infortion, see the section,Primary Key Class (page 111).
A Bean-Managed Persistence ExampleThe entity bean illustrated in this section represents a simple bank accountstate of the entity bean is stored in themyaccount table of a relational databaseThemyaccount table was created by the following SQL statement:
CREATE TABLE myaccount (id VARCHAR(3) CONSTRAINT pk_account PRIMARY KEY, firstname VARCHAR(24), lastname VARCHAR(24), balance DECIMAL(10,2));
84 ENTITY BEANS
).
f
To write an entity bean, you must provide the following code:
• Entity Bean Class (AccountEJB)
• Home Interface (AccountHome)
• Remote Interface (Account)
This example also makes use of the following classes:
• A helper class namedInsufficientBalanceException.
• A client class calledAccountClient.
The source code for this example is in theexamples/src/ejb/account direc-tory. To compile the code, go to theexamples/src directory and typeantaccount.
Entity Bean ClassThe sample entity bean class is calledAccountEJB. As you look through itscode, note that it meets the requirements of every entity bean:
• It implements theEntityBean interface.
• The class is defined aspublic.
• The class cannot be defined asabstract or final.
• It implements zero or moreejbCreate andejbPostCreate methods.
• It implements the finder methods (only for bean-managed persistence
• It implements the business methods.
• It contains an empty constructor.
• It does not implement thefinalize method.
The EntityBean InterfaceTheEntityBean interface extends theEnterpriseBean interface, which extendsthe Serializable interface. TheEntityBean interface declares a number omethods, such asejbActivate andejbLoad, which you must implement in yourentity bean class. These methods are discussed later sections.
A BEAN-MANAGED PERSISTENCEEXAMPLE 85
orre-
e
e
The ejbCreate Method
When the client invokes a create method, the EJB container invokes the cspondingejbCreate method. Typically, anejbCreate method in an entity beanperforms the following tasks:
• Inserts the entity state into the database.
• Initializes the instance variables.
• Returns the primary key.
TheejbCreate method ofAccountEJB inserts the entity state into the databasby invoking the privateinsertRow method, which issues the SQLinsert state-ment. Here is the source code for theejbCreate method in theAccountEJBclass:
public String ejbCreate(String id, String firstName, String lastName, double balance) throws CreateException {
if (balance < 0.00) { throw new CreateException (“A negative initial balance is not allowed.”); }
try { insertRow(id, firstName, lastName, balance); } catch (Exception ex) { throw new EJBException(“ejbCreate: “ + ex.getMessage()); }
this.id = id; this.firstName = firstName; this.lastName = lastName; this.balance = balance;
return id; }
Although theAccountEJB class has just oneejbCreate method, an enterprisebean may contain multipleejbCreate methods. For an example, see thCartEJB.java source code.
86 ENTITY BEANS
e
sis-
eady
ppli-ightso-
When writing anejbCreate method for an entity bean, be sure to follow thesrules:
• The access control modifier must bepublic.
• The return type must be the primary key (only for bean-managed pertence).
• The arguments must be legal types for Java RMI.
• The method modifier cannot befinal or static
The throws clause may include thejavax.ejb.CreateException and excep-tions that are specific to your application. AnejbCreate method usually throwsa CreateException if an input parameter is invalid. If anejbCreate methodcannot create an entity because another entity with the same primary key alrexists, it should throw ajavax.ejb.DuplicateKeyException (a subclass ofCreateException). If a client receives aCreateException or a Dupli-
cateKeyException, it should assume that the entity was not created.
The state of an entity bean may be directly inserted into the database by an acation that is unknown to the J2EE server. For example, a SQL script minsert a row into themyaccount table. Although the entity bean for this row wanot created by anejbCreate method, the bean can be located by a client prgram.
The ejbPostCreate Method
For eachejbCreate method, you must write anejbPostCreate method in theentity bean class. The EJB container invokesejbPostCreate immediately afterit calls ejbCreate. Unlike theejbCreate method, theejbPostCreate methodcan invoke thegetPrimaryKey andgetEJBObject methods of theEntityCon-text interface. For more information on thegetEJBObject method, seePassingan EnterpriseBean’s Object Reference (page 78). Often, yourejbPostCreatemethods will be empty.
The signature of anejbPostCreate must meet the following requirements:
• The number and types of arguments must match a correspondingejbCre-
ate method.
• The access control modifier must bepublic.
• The method modifier cannot befinal or static.
• The return type must bevoid.
The throws clause may include thejavax.ejb.CreateException and excep-tions that are specific to your application.
A BEAN-MANAGED PERSISTENCEEXAMPLE 87
the
n
am-that
bean
mhe
nesssri-you.ari-
utes
The ejbRemove Method
A client removes an entity bean by invoking theremove method. This invocationcauses the EJB client to call theejbRemove method, which deletes the entitystate from the database. The code for theejbRemove method in theAccountEJBclass follows:
public void ejbRemove() {
try {deleteRow(id);
} catch (Exception ex) {throw new EJBException(“ejbRemove: “ +ex.getMessage());
}}
If the ejbRemove method encounters a system problem, it should throwjavax.ejb.EJBException. If it encounters an application error, it should throwa javax.ejb.RemoveException. For a comparison of system and applicatioexceptions, see the section,Handling Exceptions (page 115).
An entity bean may also be removed directly by a database deletion. For exple, if a SQL script deletes a row that contains an entity bean state, thenentity bean is removed.
The ejbLoad and ejbStore Methods
If the EJB container needs to synchronize the instance variables of an entitywith the corresponding values stored in a database, it invokes theejbLoad andejbStore methods. TheejbLoad method refreshes the instance variables frothe database, and theejbStore method writes the variables to the database. Tclient may not callejbLoad andejbStore.
If a business method is associated with a transaction, the container invokesejb-
Load before the business method executes. Immediately after the busimethod executes, the container callsejbStore. Because the container invokeejbLoad andejbStore, you do not have to refresh and store the instance vaables in your business methods—the container performs these functions forThe AccountEJB class relies on the container to synchronize the instance vables with the database. Therefore, the business methods ofAccountEJB shouldbe associated with transactions. For instructions on setting transaction attribfor methods, see the section,Running the New Enterprise BeanWizard (page 95).
88 ENTITY BEANS
g
bles.ee
ple-
If the ejbLoad andejbStore methods cannot locate an entity in the underlyindatabase, they should throw thejavax.ejb.NoSuchEntityException. Thisexception is a subclass ofEJBException. BecauseEJBException is a subclassof RuntimeException, you do not have to include it in thethrows clause. WhenNoSuchEntityException is thrown, the EJB container wraps it in aRemoteEx-ception before returning it to the client.
In theAccountEJB class,ejbLoad invokes theloadRow method, which issues aSQL select statement and assigns the retrieved data to the instance variaThe ejbStore method calls thestoreRow method, which stores the instancvariables in the database with a SQLupdate statement. Here is the code for thejbLoad andejbStore methods:
public void ejbLoad() {
try { loadRow(); } catch (Exception ex) { throw new EJBException(“ejbLoad: “ + ex.getMessage()); } }
public void ejbStore() {
try { storeRow(); } catch (Exception ex) { throw new EJBException(“ejbLoad: “ + ex.getMessage()); } }
The Finder Methods
The finder methods allow clients to locate entity beans. TheAccountClient pro-gram locates entity beans with three finder methods:
Account jones = home.findByPrimaryKey(“836”);. . .Collection c = home.findByLastName(“Smith”);. . .Collection c = home.findInRange(20.00, 99.00);
For every finder method available to a client, the entity bean class must imment a corresponding method that begins with the prefixejbFind. The
A BEAN-MANAGED PERSISTENCEEXAMPLE 89
the
AccountEJB entity bean class, for example, implements theejbFindByLastName
method as follows:
public Collection ejbFindByLastName(String lastName) throws FinderException {
Collection result;
try { result = selectByLastName(lastName); } catch (Exception ex) { throw new EJBException(“ejbFindByLastName “ + ex.getMessage()); } return result;}
The finder methods specific to your application, such asejbFindByLastName
and ejbFindInRange, are optional, but theejbFindByPrimaryKey method isrequired. As its name infers, theejbFindByPrimaryKey method accepts as anargument the primary key, which it uses to locate an entity bean. InAccountEJB class, the primary key is theid variable. Here is the code for theejbFindByPrimaryKey method:
public String ejbFindByPrimaryKey(String primaryKey) throws FinderException {
boolean result;
try { result = selectByPrimaryKey(primaryKey); } catch (Exception ex) { throw new EJBException(“ejbFindByPrimaryKey: “ + ex.getMessage()); }
if (result) { return primaryKey; } else { throw new ObjectNotFoundException (“Row for id “ + primaryKey + “ not found.”); }}
90 ENTITY BEANS
s am-
le-
s.
sin-
d
ulatebase,. The
TheejbFindByPrimaryKey method may look strange to you, because it useprimaryKey for both the method argument and return value. However, remeber that the client does not callejbFindByPrimaryKey directly. It is the EJBcontainer that calls theejbFindByPrimaryKey method. The client invokes thefindByPrimaryKey method, which is defined in the home interface.
The following list summarizes the rules for the finder methods that you impment in an entity bean class with bean-managed persistence:
• TheejbFindByPrimaryKey method must be implemented.
• A finder method name must start with the prefixejbFind.
• The access control modifier must bepublic.
• The method modifier cannot befinal or static.
• The arguments and return type must be legal types for Java RMI.
• The return type must be the primary key or a collection of primary key
The throws clause may include thejavax.ejb.FinderException, and otherexceptions that are specific to your application. If a finder method returns agle primary key, it should throw thejavax.ejb.ObjectNotFoundException ifthe requested entity does not exist. TheObjectNotFoundException is a subclassof FinderException. If a finder method returns a collection of primary keys anit does not find any objects, it should return an empty collection.
The Business Methods
The business methods contain the business logic that you want to encapswithin the entity bean. Usually, the business methods do not access the dataallowing you to separate business logic from the database access codeAccountEJB entity bean contains these business methods:
public void debit(double amount) throws InsufficientBalanceException {
if (balance - amount < 0) { throw new InsufficientBalanceException(); } balance -= amount; }
public void credit(double amount) {
balance += amount; }
A BEAN-MANAGED PERSISTENCEEXAMPLE 91
both
the
ca-
the
public String getFirstName() {
return firstName; }
public String getLastName() {
return lastName; }
public double getBalance() {
return balance; }
TheAccountClient program invokes the business methods as follows:
Account duke = home.create(“123”, “Duke”, “Earl”, 0.00);duke.credit(88.50);duke.debit(20.25);double balance = duke.getBalance();
The requirements for the signature of a business method are the same forsession and entity beans:
• The method name must not conflict with a method name defined byEJB architecture. For example, you cannot call a business methodejbCre-
ate or ejbActivate.
• The access control modifier must bepublic.
• The method modifier cannot befinal or static.
• The arguments and return types must be legal types for Java RMI.
Thethrows clause may include the exceptions that you define for your applition. Thedebit method, for example, throws theInsufficientBalanceExcep-tion. To indicate a system-level problem, a business method should throwjavax.ejb.EJBException.
92 ENTITY BEANS
gethodsEJB
the
, see
d an
Database Calls
The following table summarizes the database access calls in theAccountEJB
class:
The business methods of theAccountEJB class are absent from the precedintable because they do not access the database. Instead, these business mupdate the instance variables, which are written to the database when thecontainer callsejbStore. Another developer may have chosen to accessdatabase in the business methods of theAccountEJB class. It’s a design decisionthat depends on the specific needs of your application.
Before accessing a database you must connect to it. For more informationthe section,Resource Connections (page 269).
Home InterfaceThe home interface defines the methods that allow a client to create and finentity bean. TheAccountHome interface follows:
import java.util.Collection;import java.rmi.RemoteException;import javax.ejb.*;
public interface AccountHome extends EJBHome {
Table 3 SQL Statements inAccountEJB
Method SQL Statement
ejbCreate insert
ejbFindByPrima-ryKey
select
ejbFindByLastName select
ejbFindInRange select
ejbLoad select
ejbRemove delete
ejbStore update
A BEAN-MANAGED PERSISTENCEEXAMPLE 93
nts:
thewith
ond-
n of
g
public Account create(String id, String firstName, String lastName, double balance) throws RemoteException, CreateException;
public Account findByPrimaryKey(String id) throws FinderException, RemoteException;
public Collection findByLastName(String lastName) throws FinderException, RemoteException;
public Collection findInRange(double low, double high) throws FinderException, RemoteException;}
Eachcreate method in the home interface must conform to these requireme
• It has the same number and types of arguments as its matchingejbCreate
method in the enterprise bean class.
• It returns the remote interface type of the enterprise bean.
• Thethrows clause includes the exceptions specified by thethrows clauseof the correspondingejbCreate andejbPostCreate methods.
• The throws clause contains thejava.rmi.RemoteException and thejavax.ejb.CreateException.
Every finder method in the home interface corresponds to a finder method inentity bean class. The name of a finder method in the home interface beginsfind, whereas the name of one in the entity bean class begins withejbFind. Forexample, theAccountHome class defines thefindByLastName method, and theAccountEJB class implements theejbFindByLastName method. The rules fordefining the signatures of the finder methods of a home interface follow:
• The number and types of arguments must match those of the corresping method in the entity bean class.
• The return type is the entity bean’s remote interface type, or a collectiothose types.
• The exceptions in thethrows clause include those of the correspondinmethod in the entity bean class.
• The throws clause contains thejavax.ejb.FinderException and thejavax.ejb.RemoteException.
94 ENTITY BEANS
ame
ter-
al tolass.
SDKby
Remote InterfaceThe remote interface extendsjavax.ejb.EJBObject and defines the businessmethods that a client may invoke. Here is theAccount remote interface:
import javax.ejb.EJBObject;import java.rmi.RemoteException;
public interface Account extends EJBObject {
public void debit(double amount) throws InsufficientBalanceException, RemoteException;
public void credit(double amount) throws RemoteException;
public String getFirstName() throws RemoteException;
public String getLastName() throws RemoteException;
public double getBalance() throws RemoteException;}
The requirements for the method definitions in a remote interface are the sfor both session and entity beans:
• Each method in the remote interface must match a method in the enprise bean class.
• The signatures of the methods in the remote interface must be identicthe signatures of the corresponding methods in the enterprise bean c
• The arguments and return values must be valid RMI types.
• The throws clause must includejava.rmi.RemoteException.
Tips for Running the AccountEJB Example
Setting Up the Database
The instructions that follow explain how to use theAccountEJB example with aCloudscape database. The Cloudscape software is included with the J2EEdownload bundle. You may also run this example with databases provided
A BEAN-MANAGED PERSISTENCEEXAMPLE 95
r byr,
an.fol-
lect
other vendors. (See theRelease Notesof the J2EE SDK for a list of supporteddatabases.)
1. From the command-line prompt, run the Cloudscape database servetypingcloudscape -start. (When you are ready to shut down the servetypecloudscape -stop.)
2. Create themyaccount database table:
a. Go to theexamples/src directory
b. Typeant create-myaccount-table.
Note: If you are not using a Cloudscape database, you may use theexam-
ples/src/ejb/sql/myaccount.sql script to create themyaccount table.
Running the New Enterprise Bean Wizard
To start the New Enterprise Bean Wizard, select File->New Enterprise BeAlthough the wizard displays many dialog boxes, for this example only thelowing dialog boxes require input.
1. General Dialog Box
a. Select the Entity radio button.
b. In the Enterprise Bean Name field, enterAccountBean.
2. Entity Settings Dialog Box
a. Select the radio button labelled Bean-Managed Persistence.
3. Resource References Dialog Box:
a. Click Add.
b. In the Coded Name field, enterjdbc/AccountDB.
c. In the Type column, select javax.sql.DataSource.
d. In the Authentication column, select Container.
4. Transaction Management Dialog Box
a. For the business methods, in the Transaction Type column seRequired. The business methods aredebit, credit, getFirstName,getLastName, andgetBalance.
Deploying the J2EE Application
1. In thedeploytool, select Tools->Deploy.
2. Click the radio button labelled Return Client Jar. SpecifyAccountAppCli-
ent.jar as the file name.
96 ENTITY BEANS
in
tion-ans.
3. In the JNDI Names dialog, in the Application table enterMyAccount as theJNDI name for theAccountBean.
4. In the References table, enterjdbc/Cloudscape as the JNDI name for thejdbc/AccountDB reference name.
5. In the References table, enterMyAccount as the JNDI name for theejb/SimpleAccount reference, which is an enterprise bean referencetheAccountClient code.
Running the J2EE Application
1. In a terminal window, set theAPPCPATH environment variable to the nameof the stub client JAR file (AccountAppClient.jar).
2. Go to the directory containing the application EAR file.
3. Run the application with therunclient script. In the following example,the application EAR file isAccountApp.ear and the name of the J2EEapplication client isAccountClient:
runclient -client AccountApp.ear -name AccountClient
4. In the login dialog, enterguest as the user name andguest123 as the pass-word.
5. The client should display the following lines in the terminal window:
balance = 68.25balance = 32.53456: 44.77730: 19.53268: 100.06836: 32.53456: 44.77
Mapping Table Relationships For Bean-Managed Persistence
In a relational database, tables can be related by common columns. The relaships between the tables affect the design of their corresponding entity be
MAPPING TABLE RELATIONSHIPS FORBEAN-MANAGED PERSIS-
fol-
in
pe of
re-
ith
y of
The entity beans discussed in this section are backed up by tables with thelowing types of relationships:
• One-to-One Relationships
• One-to-Many Relationships
• Many-to-Many Relationships
One-to-One RelationshipsIn a one-to-one relationship, each row in a table is related to a single rowanother table. For example, in a warehouse application astoragebin tablemight have a one-to-one relationship with awidget table. This applicationwould model a physical warehouse where each storage bin contains one tywidget and each widget resides in one storage bin.
Figure 8 illustrates thestoragebin andwidget tables. Because thestorage-binid uniquely identifies a row in thestoragebin table, it is that table’s primarykey. Thewidgetid is the primary key of thewidget table. The two tables arerelated because thewidgetid is also a column in thestoragebin table. Byreferring to the primary key of thewidget table, thewidgetid in thestorage-bin table identifies which widget resides in a particular storage bin in the wahouse. Because thewidgetid of thestoragebin table refers to the primary keyof another table, it is called a foreign key. (The figure denotes a primary key wPK and a foreign key with FK.)
Figure 8 One-to-One Table Relationship
A dependent (child) table includes a foreign key that matches the primary kethe referenced (parent) table. The values of the foreign keys in thestoragebin
(child) table depend on the primary keys in thewidget (parent) table. For exam-ple, if thestoragebin table has a row with awidgetid of 344, then the widgettable should also have a row whosewidgetid is 344.
StorageBin Table
storagebinid (PK) widgetid (FK) quantity
widgetid (PK) description price
Widget Table
1 : 1
98 ENTITY BEANS
epen-uch a
ingt
-
When designing a database application, you may choose to enforce the ddency between the parent and child tables. There are two ways to enforce sdependency: by defining a referential constraint in the database or by performchecks in the application code. Thestoragebin table has a referential constrainnamedfk_widgetid:
CREATE TABLE storagebin (storagebinid VARCHAR(3) CONSTRAINT pk_storagebin PRIMARY KEY, widgetid VARCHAR(3), quantity INTEGER, CONSTRAINT fk_widgetid FOREIGN KEY (widgetid) REFERENCES widget(widgetid));
The source code for the following example is in theexamples/src/ejb/stor-
agebin directory. To compile the code, go to theexamples/src directory andtypeant storagebin.
The StorageBinEJB and WidgetEJB classes illustrate the one-to-one relationship of thestoragebin andwidget tables. TheStorageEJB class contains vari-ables for each column in thestoragebin table, including the foreign key,widgetId:
private String storageBinId;private String widgetId;private int quantity;The ejbFindByWidgetId method of the StorageEJB class returns thestorageBinId that matches a given widgetId:public String ejbFindByWidgetId(String widgetId) throws FinderException {
String storageBinId;
try { storageBinId = selectByWidgetId(widgetId); } catch (Exception ex) { throw new EJBException(“ejbFindByWidgetId: “ + ex.getMessage()); }
if (storageBinId == null) { throw new ObjectNotFoundException (“Row for widgetId “ + widgetId + “ not found.”); }
MAPPING TABLE RELATIONSHIPS FORBEAN-MANAGED PERSIS-
se
else { return storageBinId; }}
TheejbFindByWidgetId method locates the widgetId by querying the databain theselectByWidgetId method:
private String selectByWidgetId(String widgetId) throws SQLException {
String storageBinId;
String selectStatement = “select storagebinid “ + “from storagebin where widgetid = ? “; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, widgetId);
ResultSet rs = prepStmt.executeQuery();
if (rs.next()) { storageBinId = rs.getString(1); } else { storageBinId = null; }
prepStmt.close(); return storageBinId;}
To find out which storage bin a widget resides in, theStorageBinClient pro-gram calls thefindByWidgetId method:
String widgetId = “777”;StorageBin storageBin = storageBinHome.findByWidgetId(widgetId);String storageBinId = (String)storageBin.getPrimaryKey();int quantity = storageBin.getQuantity();
Tips for Running the StorageBinEJB Example
1. Create the database tables by typingant create-storagebin-table.
2. Specify bean-managed persistence for both entity beans.
100 ENTITY BEANS
.
ildata-ess ayer
la-cide
3. For the business methods, specify the Required transaction attribute
4. For theStorageBinBean, specifyjdbc/StorageBinDB as the coded namefor the resource reference.
5. For theWidgetBean, specifyjdbc/WidgetDB as the coded name for theresource reference.
6. For theStorageBinClient, add two enterprise bean references:ejb/Sim-
pleStorageBin andejb/SimpleWidget.
7. Use the JNDI names listed in the following table.
One-to-Many RelationshipsIf the primary key in a parent table matches multiple foreign keys in a chtable, then the relationship is one-to-many. This relationship is common in dbase applications. For example, an application for a sports league might accteam table and aplayer table. Each team has multiple players and each plabelongs to a single team. Every row in the child table (player), has a foreign keyidentifying the player’s team. This foreign key matches theteam table’s primarykey.
The sections that follow describe how you might implement one-to-many retionships in entity beans. When designing such entity beans, you must dewhether both tables are represented by entity beans, or just one.
Table 4 JNDI Names for theStorageBinEJB Example
Component orReference Name JNDI Name
StorageBinBean MyStorageBin
WidgetBean MyWidget
jdbc/StorageBinDB jdbc/Cloudscape
jdbc/WidgetDB jdbc/Cloudscape
ejb/SimpleStorageBin MyStorageBin
ejb/SimpleWidget MyWidget
MAPPING TABLE RELATIONSHIPS FORBEAN-MANAGED PERSIS-
abaseon-lass.cus-the
der.notg sources
y
e
y.
A Helper Class for the Child Table
Not every database table needs to be mapped to an entity bean. If a dattable doesn’t represent a business entity, or if it stores information that is ctained in another entity, then the table should be represented with a helper cFor example, in an online shopping application each order submitted by atomer can have multiple line items. The application stores the information indatabase tables shown by the following figure.
Figure 9 One-to-Many Relationship: Order and Line Items
Not only does a line item belong to an order, it does not exist without the orTherefore, thelineitems table should be represented with a helper class andwith an entity bean. Using a helper class in this case is not required, but doinmight improve performance because a helper class uses fewer system resothan an entity bean.
The source code for the following example is in theexamples/src/ejb/order
directory. To compile the code, go to theexamples/src directory and typeantorder.
The LineItem and OrderEJB classes show how to implement a one-to-manrelationship with a helper class (LineItem) and an entity bean (OrderEJB). Theinstance variables in theLineItem class correspond to the columns in thlineitems table. The itemNo variable matches the primary key for thelineitems table and theorderId variable represents the table’s foreign keHere is the source code for theLineItem class:
public class LineItem implements java.io.Serializable {
String productId; int quantity; double unitPrice;
1 : Many
Orders Table
orderid (PK) customerid totalprice status
LineItems Table
itemno (PK) orderid (FK) productid unitprice quantity
102 ENTITY BEANS
int itemNo; String orderId;
public LineItem(String productId, int quantity, double unitPrice, int itemNo, String orderId) {
this.productId = productId; this.quantity = quantity; this.unitPrice = unitPrice; this.itemNo = itemNo; this.orderId = orderId; }
public String getProductId() { return productId; }
public int getQuantity() { return quantity; }
public double getUnitPrice() { return unitPrice; }
public int getItemNo() { return itemNo; }
public String getOrderId() { return orderId; }
}
The OrderEJB class contains anArrayList variable namedlineItems. Eachelement in thelineItems variable is aLineItem object. ThelineItems vari-able is passed to theOrderEJB class in theejbCreate method. For everyLineItem object in thelineItems variable, theejbCreate method inserts a rowinto thelineitems table. It also inserts a single row into theorders table. Thecode for theejbCreate method follows:
public String ejbCreate(String orderId, String customerId, String status, double totalPrice, ArrayList lineItems) throws CreateException {
MAPPING TABLE RELATIONSHIPS FORBEAN-MANAGED PERSIS-
he
e a
try { insertOrder(orderId, customerId, status, totalPrice); for (int i = 0; i < lineItems.size(); i++) { LineItem item = (LineItem)lineItems.get(i); insertItem(item); } } catch (Exception ex) { throw new EJBException(“ejbCreate: “ + ex.getMessage()); }
this.orderId = orderId; this.customerId = customerId; this.status = status; this.totalPrice = totalPrice; this.lineItems = lineItems ;
return orderId;}
TheOrderClient program creates and loads anArrayList of LineItem objects.The program passes thisArrayList to the entity bean when it invokes thecre-ate method:
ArrayList lineItems = new ArrayList();lineItems.add(new LineItem(“p23”, 13, 12.00, 1, “123”));lineItems.add(new LineItem(“p67”, 47, 89.00, 2, “123”));lineItems.add(new LineItem(“p11”, 28, 41.00, 3, “123”));. . .Order duke = home.create(“123”, “c44”, “open”, totalItems(lineItems), lineItems);
Other methods in theOrderEJB class also access both database tables. TejbRemove method, for example, deletes not only a row from theorders table,but also deletes all corresponding rows in thelineitems table. TheejbLoad andejbStore methods synchronize the state of anOrderEJB instance, including thelineItems ArrayList, with theorders andlineitems tables.
TheejbFindByProductId method enables clients to locate all orders that havparticular line item. This method queries thelineitems table for all rows with aparticularproductId. The method returns aCollection of productId Stringobjects. TheOrderClient program iterates through theCollection and printsthe primary key of each order:
104 ENTITY BEANS
ired.
ro-
ing
ble.
ent
Collection c = home.findByProductId(“p67”);Iterator i=c.iterator();while (i.hasNext()) { Order order = (Order)i.next(); String id = (String)order.getPrimaryKey(); System.out.println(id); }
Tips for Running the OrderEJB Example:
1. Create the database tables by typing ant create-order-table.
2. Add the LineItem.class file to the EJB JAR file that contains theOrderEJB.class file.
3. Specifyjdbc/OrderDB as the coded name for the resource reference.
4. For the transaction attributes of the business methods, specify RequThis attribute value causes the container to callejbLoad before (andejb-Store after) each business method invocation. These calls will synchnize the bean’s state with the database tables.
5. For theOrderClient, add theejb/SimpleOrder enterprise bean refer-ence.
6. Use the JNDI names listed in the following table.
An Entity Bean for the Child Table
You should consider building an entity bean for a child table under the followconditions:
• The information in the child table is not a subset of that in the parent ta
• The business entity of the child table could exist without that of the partable.
Table 5 JNDI Names for theOrderEJB Example
Component orReference Name JNDI Name
OrderBean MyOrder
jdbc/OrderDB jdbc/Cloudscape
ejb/SimpleOrder MyOrder
MAPPING TABLE RELATIONSHIPS FORBEAN-MANAGED PERSIS-
not
epre-only
abase
-
o-r
fferent
• The child table might be accessed by another application that doesaccess the parent table.
These conditions exist in the following scenario. Suppose that each sales rsentative in a company has multiple customers and that each customer hasone sales representative. The company tracks its sales force with a datapplication. In the database, each row in thesalesrep table (parent) matchesmultiple rows in thecustomer table (child). Figure 10 illustrates this relationship.
Figure 10 One-to-Many Relationship: Sales Representative and Customers
The SalesRepEJB andCustomerEJB entity bean classes implement the one-tmany relationship of the ofsales andcustomer tables. (The source code fothese classes is in theexamples/src/ejb/salesrep directory.)
The SalesRepEJB class contains a variable namedcustomerIds, which is anArrayList of String elements. TheseString elements identify which custom-ers belong to the sales representative. Because thecustomerIds variable reflectsthis relationship, theSalesRepEJB class must keep the variable up to date.
The SalesRepEJB class instantiates thecustomerIds variable in thesetEnti-tyContext method, not inejbCreate. The container invokessetEntityCon-text just once—when it creates the bean instance—ensuring thatcustomerIds
is instantiated just once. Because the same bean instance can assume diidentities during its life cycle, instantiatingcustomerIds in ejbCreate mightcause multiple and unnecessary instantiations. Therefore, theSalesRepEJB classinstantiates thecustomerIds variable insetEntityContext:
public void setEntityContext(EntityContext context) {
this.context = context; customerIds = new ArrayList();
try { makeConnection();
1 : Many
SalesRep Table
salesrepid (PK) name
Customer Table
customerid (PK) salesrepid (FK) name
106 ENTITY BEANS
a
theyou
d.The
Context initial = new InitialContext(); Object objref =initial.lookup(“java:comp/env/ejb/Customer”);
customerHome = (CustomerHome)PortableRemoteObject.narrow(objref, CustomerHome.class); } catch (Exception ex) { throw new EJBException(“setEntityContext: “ + ex.getMessage()); }}
Invoked by theejbLoad method,loadEnrollerIds is a private method thatrefreshes thecustomerIds variable. There are two approaches when codingmethod such asloadCustomerIds: fetch the identifiers from thecustomer data-base table or get them from theCustomer entity bean. Fetching the identifiersfrom the database might be faster, but exposes theSalesRepEJB code to theCus-tomer bean’s underlying database table. In the future, if you were to changeCustomer bean’s table (or move the bean to a different J2EE server), thenmight need to change theSalesRepEJB code. But if theSalesRepEJB gets theidentifiers from theCustomer entity bean, no coding changes would be requireThe two approaches present a trade-off: performance versus flexibility.SalesRepEJB example opts for flexibility, loading thecustomerIds variable bycalling thefindSalesRep andgetPrimaryKey methods of theCustomer bean.Here is the code for theloadCustomerIds method:
private void loadCustomerIds() {
customerIds.clear();
try { Collection c = customerHome.findBySalesRep(salesRepId); Iterator i=c.iterator();
while (i.hasNext()) { Customer customer = (Customer)i.next(); String id = (String)customer.getPrimaryKey(); customerIds.add(id); }
} catch (Exception ex) {throw new EJBException(“Exception in loadCustomerIds: “ +
ex.getMessage()); }}
MAPPING TABLE RELATIONSHIPS FORBEAN-MANAGED PERSIS-
data-
tion
. To
ach
e
ds to
If a customer’s sales representative changes, the client program updates thebase by calling thesetSalesRepId method of theCustomerEJB class. The nexttime a business method of theSalesRepEJB is called, theejbLoad methodinvokes loadCustomerIds, which refreshes thecustomerIds variable. (Toensure thatejbLoad is invoked before each business method, set the transacattributes of the business methods to Required.) For example, theSalesRepCli-
ent program changes thesalesRepId for a customer named Mary Jackson:
Customer mary = customerHome.findByPrimaryKey(“987”);mary.setSalesRepId(“543”);
The salesRepId 543 identifies a sales representative named Janice Martinlist all of Janice’s customers, theSalesRepClient program invokes thegetCus-tomerIds method, iterates through the ArrayList of identifiers, and locates eCustomer bean by calling theCustomer bean’sfindByPrimaryKey method:
SalesRep janice = salesHome.findByPrimaryKey(“543”);ArrayList a = janice.getCustomerIds();i = a.iterator();
while (i.hasNext()) { String customerId = (String)i.next(); Customer customer =customerHome.findByPrimaryKey(customerId); String name = customer.getName(); System.out.println(customerId + “: “ + name);}
Tips for Running the SalesRepEJB Example:
1. Create the database tables by typingant create-salesrep-table.
2. For both beans specifyjdbc/SalesDB as the coded name for the resourcreference.
3. For both beans, set the transaction attributes of the business methoRequired.
4. For theSalesRepEJB bean, add theejb/Customer enterprise bean refer-ence.
5. For theSalesRepClient, add these enterprise bean references:ejb/Sim-
pleSalesRep andejb/SimpleCustomer.
108 ENTITY BEANS
ur-s andrepre-, the
d FK
6. Specify the JNDI names listed in the following table.
Many-to-Many RelationshipsIn a many-to-many relationship, each entity may be related to multiple occrences of the other entity. For example, a college course has many studenteach student may take several courses. In a database, this relationship issented by a cross reference table containing the foreign keys. In Figure 11cross reference table is the enrollment table. (PK indicates a primary key ana foreign key.)
Table 6 JNDI Names for theSalesRepEJB Example
Component orReference Name JNDI Name
SalesRepBean MySalesRep
CustomerBean MyCustomer
jdbc/SalesDB jdbc/Cloudscape
ejb/Customer MyCustomer
ejb/SimpleSalesRep MySalesRep
ejb/SimpleCustomer MyCustomer
MAPPING TABLE RELATIONSHIPS FORBEAN-MANAGED PERSIS-
ins
is
e
Figure 11 Many-to-Many Relationship: Students and Courses
These tables are accessed by theStudentEJB, CourseEJB, and EnrollerEJB
classes. The source code for these classes is in theexamples/src/ejb/enrol-
ler directory. To compile the code, go to theexamples/src directory and typeant enroller.
TheStudentEJB andCourseEJB classes are complementary. Each class contaanArrayList of foreign keys. TheStudentEJB class, for example, contains anArrayList named courseIds, which identifies the courses the studentenrolled in. TheejbLoad method adds elements to thecourseIds ArrayList bycalling loadCourseIds, a private method. TheloadCourseIds method gets thecourse identifiers from theEnroller session bean. The source code for thloadCourseIds method follows:
private void loadCourseIds() {
courseIds.clear();
try { Enroller enroller = enrollerHome.create(); ArrayList a = enroller.getCourseIds(studentId);
1 : Many
Student Table
studentid (PK) name
Many : 1
Enrollment Table
studentid (FK) courseid (FK)
Course Table
courseid (PK) name
110 ENTITY BEANS
n thells
ble.
ong to
courseIds.addAll(a);
} catch (Exception ex) { throw new EJBException(“Exception in loadCourseIds: “ + ex.getMessage()); }}
Invoked by theloadCourseIds method, thegetCourses method of theEnrol-lerEJB class queries theenrollment table:
select courseid from enrollmentwhere studentid = ?
Only the EnrollerEJB class accesses theenrollment table. Therefore, theEnrollerEJB class manages the student-course relationship represented ienrollment table. If a student enrolls in a course, for example, the client catheenroll business method, which inserts a row:
insert into enrollmentvalues (studentid, courseid)
If a student drops a course, theunEnroll method deletes a row:
delete from enrollmentwhere studentid = ? and courseid = ?
And if a student leaves the school, thedeleteStudent method deletes all rowsin the table for that student:
delete from enrollmentwhere student = ?
TheEnrollerEJB class does not delete the matching row from the student taThat action is performed by theejbRemove method of theStudentEJB class. Toensure that both deletes are executed as a single operation, they should belthe same transaction. SeeTransactions (page 235) for more information.
Tips for running the EnrollerEJB example:
1. Create the database tables by typingant create-enroller-table.
2. For all three beans, specifyjdbc/CollegeDB as the coded name for theresource reference.
3. For all three beans, specify container-managed transactions.
ABOUT CONTAINER-MANAGED PERSISTENCE 111
red.
n:
4. For the transaction attributes of the business methods, specify Requi
5. For theStudentEJB andCourseEJB entity beans, specify theejb/Enrol-ler enterprise bean reference.
6. For theEnrollerClient, specify an enterprise reference for each beaejb/SimpleCourse, ejb/SimpleStudent, ejb/SimpleEnroller.
7. Use the JNDI names listed in the following table.
About Container-Managed PersistenceTBD
A Container-Managed PersistenceExample
TBD
Primary Key ClassYou specify the primary key class on the Entity tabbed pane of thedeploytool.When deploying theProductEJB bean, for example, you would specify a
Table 7 JNDI Names for the EnrollerEJB Example
Component orReference Name JNDI Name
EnrollerBean MyEnroller
StudentBean MyStudent
CourseBean MyCourse
jdbc/CollegeDB jdbc/Cloudscape
ejb/SimpleEnroller MyEnroller
ejb/SimpleStudent MyStudent
ejb/SimpleCourse MyCourse
112 ENTITY BEANS
ey
Forte a
java.lang.String as the primary key class. In most cases, your primary kclass will be aString or some other class that belongs to thejava package.
Creating a Primary Key ClassFor some entity beans, you will need to define your own primary key class.example, if a primary key is composed of multiple fields then you must creaprimary key class. In the following primary key class, theproductId andven-dorId fields together uniquely identify an entity bean:
public class ItemKey implements java.io.Serializable {
public String productId; public String vendorId;
public ItemKey() { };
public ItemKey(String productId, String vendorId) {
this.productId = productId; this.vendorId = vendorId; }
public String getProductId() {
return productId; }
public String getVendorId() {
return vendorId; }
public boolean equals(Object other) {
if (other instanceof ItemKey) { return (productId.equals(((ItemKey)other).productId)
&& vendorId.equals(((ItemKey)other).vendorId)); }
return false; }
public int hashCode() {
PRIMARY KEY CLASS 113
keyntity
e
return productId.hashCode(); }}
Class RequirementsA primary key class must meet these requirements:
• The access control modifier of the class ispublic.
• All fields are declared aspublic.
• For container-managed persistence, the field names in the primaryclass must match the corresponding container-managed fields in the ebean class.
• The class has a public default constructor.
• The class implements thehashCode() andequals(Object other) meth-ods.
• The class is serializable.
Bean-Managed Persistence and the Primary KeyClassWith bean-managed persistence, theejbCreate method returns the primary keyclass:
public ItemKey ejbCreate(String productId, String vendorId, String description) throws CreateException {
if (productId == null || vendorId == null) { throw new CreateException( “The productId and vendorId are required.”); }
this.productId = productId; this.vendorId = vendorId; this.description = description;
return new ItemKey(productId, vendorId);}
The ejbFindByPrimaryKey verifies the existence of the database row for thgiven primary key:
114 ENTITY BEANS
public ItemKey ejbFindByPrimaryKey(ItemKey primaryKey) throws FinderException {
try { if (selectByPrimaryKey(primaryKey)) return primaryKey; . . .}
private boolean selectByPrimaryKey(ItemKey primaryKey) throws SQLException {
String selectStatement = “select productid “ + “from item where productid = ? and vendorid = ?”; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, primaryKey.getProductId()); prepStmt.setString(2, primaryKey.getVendorId()); ResultSet rs = prepStmt.executeQuery(); boolean result = rs.next(); prepStmt.close(); return result;}
Container-Managed Persistence and the PrimaryKey ClassTBD
Getting the Primary KeyA client can fetch the primary key of an entity bean by invoking thegetPrima-
ryKey method of theEJBObject class:
Account account;. . .String id = (String)account.getPrimaryKey();
The entity bean retrieves its own primary key by calling thegetPrimaryKey
method of theEntityContext class:
EntityContext context;. . .String id = (String) context.getPrimaryKey();
HANDLING EXCEPTIONS 115
and
ppli-ction
sys-
-nce.m; it
risefined.
d
con-ndle
ackac-
Handling ExceptionsThe exceptions thrown by enterprise beans fall into two categories: systemapplication.
A system exception indicates a problem with the services that support an acation. Examples of these problems include the following: a database connecannot be obtained, a SQL insert fails because the database is full, alookup
method cannot find the desired object. If your enterprise bean encounters atem-level problem, it should throw ajavax.ejb.EJBException. The containerwill wrap theEJBException in a RemoteException, which it passes back to theclient. Because theEJBException is a subclass of theRuntimeException, youdo not have to specify it in thethrows clause of the method declaration. If a system exception is thrown, the EJB container might destroy the bean instaTherefore, a system exception cannot be handled by the bean’s client prograrequires intervention by a system administrator.
An application exception signals an error in the business logic of an enterpbean. There are two types of application exceptions: customized and predeA customized exception is one that you’ve coded yourself, such as theInsuffi-
centBalanceException thrown by the debit business method of theAccountEJB example. Thejavax.ejb package includes several predefineexceptions that are designed to handle common problems. For example, anejb-
Create method should throw aCreateException to indicate an invalid inputparameter. When an enterprise bean throws an application exception, thetainer does not wrap it in another exception. The client should be able to haany application exception it receives.
If a system exception occurs within a transaction, the EJB container rolls bthe transaction. However, if an application exception is thrown within a transtion, the container does not roll back the transaction.
The following table summarizes the exceptions of thejavax.ejb package. Allof these exceptions are application exceptions, except for theNoSuchEntityEx-
ception and theEJBException, which are system exceptions.
Table 8 Exceptions
Method Name Exception It Throws Reason for Throwing
ejbCreate CreateExceptionAn input parameter isinvalid.
116 ENTITY BEANS
ourenSee
time.
hilebjectan
path,
er’s
The Life Cycle of an Entity BeanThe life cycle of an entity bean is controlled by the EJB container, not by yapplication. However, you may find it helpful to learn about the life cycle whdeciding in which method your entity bean will connect to a database.Resource Connections (page 269) for more information.
Figure 12 shows the stages that an entity bean passes through during its lifeAfter the EJB container creates the instance, it calls thesetEntityContext
method of the entity bean class. ThesetEntityContext method passes theentity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. Win the pooled stage, the instance is not associated with any particular EJB oidentity. All instances in the pool are identical. The EJB container assignsidentity to an instance when moving it to the ready stage.
There are two paths from the pooled stage to the ready stage. On the firstthe client invokes thecreate method, causing the EJB container to call theejb-
Create and ejbPostCreate methods. On the second path, the EJB containinvokes theejbActivate method. While in the ready stage, an entity beanbusiness methods may be invoked.
ejbFindByPrimaryKey(and other findermethods that returna single object)
ObjectNotFoundException(subclass of FinderException)
The database row for therequested entity bean iscannot be found.
ejbRemove RemoveExceptionThe entity bean’s row can-not be deleted from thedatabase.
ejbLoad NoSuchEntityExceptionThe database row to beloaded cannot be found.
ejbStore NoSuchEntityExceptionThe database row to beupdated cannot be found.
(all methods) EJBExceptionA system problem hasbeen encountered.
Table 8 Exceptions (Continued)
Method Name Exception It Throws Reason for Throwing
THE LIFE CYCLE OF AN ENTITY BEAN 117
clienthe
the
There are also two paths from the ready stage to the pooled stage. First, amay invoke theremove method, which causes the EJB container to call tejbRemove method. Second, the EJB container may invoke theejbPassivate
method.
At the end of the life cycle, the EJB container removes the instance frompool and invokes theunsetEntityContext method.
Figure 12 Life Cycle of an Entity Bean
setEntityContext unsetEntityContext
ejbPassivateejbActivate
Does Not Exist
Pooled
Ready
1. remove 2. ejbRemove
1. create 2. ejbCreate 3. ejbPostCreate
118 ENTITY BEANS
bjects ant the
ut
u canm to
In the pooled state, an instance is not associated with any particular EJB oidentity. With bean-managed persistence, when the EJB container moveinstance from the pooled state to the ready state, it does not automatically seprimary key. Therefore, theejbCreate andejbActivate methods must set theprimary key. If the primary key is incorrect, theejbLoad andejbStore methodscannot synchronize the instance variables with the database. In theAccountEJB
example, theejbCreate method assigns the primary key from one of the inpparameters. TheejbActivate method sets the primary key (id) as follows:
id = (String)context.getPrimaryKey();
In the pooled state, the values of the instance variables are not needed. Yomake these instance variables eligible for garbage collection by setting thenull in theejbPasssivate method.
EEre areSP™)rocessat exe-tent.ngths.
suchmore
and
dures
eter-hat
is afea-
Web Componentsby Stephanie Bodoff
WHEN web-based clients of J2EE applications communicate with a J2server, they do so through server-side objects called web components. Thetwo types of web components: Java™ Servlets and JavaServer Pages™ (Jpages. Servlets are Java programming language classes that dynamically prequests and construct responses. JSP pages are text-based documents thcute as servlets, but allow a more natural approach to creating static conWhile servlets and JSP pages can be used interchangeably, each has its streServlets are best suited to managing the control functions of an application,as dispatching requests, and handling non-textual data. JSP pages areappropriate for generating text-based markup such as HTML, SVG, WML,XML.
This chapter describes the packaging, configuration, and deployment procecommon to servlets and JSP pages. Subsequent chapters,Java ServletTechnology (page 133) andJavaServer Pages™Technology (page 167), coverhow to develop the web components. Many features of JSP technology are dmined by Java Servlet technology so you should familiarize yourself with tmaterial, even if you do not intend to write servlets.
Most web-based J2EE clients use the HTTP protocol and support for HTTPmajor aspect of web components. For a brief summary of HTTP protocoltures seeHTTP Overview (page 307).
Web Component Life Cycle 120Packaging Web Components 122
Creating a WAR 122Adding a WAR to a J2EE Application 123Adding a Web Component to a WAR 123
119
120 WEB COMPONENTS
abili-use ita web
ency,J2EEexe-
ack-e in
t youa
rvlet
n be
ent
ple,
Configuring Web Components 124Application-Level Configuration 125WAR-Level Configuration 125Component-Level Configuration 127
Deploying Web Components 128Executing Web Components 128Updating Web Components 129
Web Component Life CycleThe J2EE platform provides many supporting services that enhance the capties of web components and make them easier to develop. However, becamust take into account these services, the process for creating and runningcomponent is different than that of traditional stand-alone Java classes.
Web components run within an environment called aweb container. The webcontainer provides services such as request dispatching, security, concurrand life cycle management. It also gives web components access to theplatform APIs such as naming, transactions, and email. Before it can becuted, a web component must be installed (ordeployed) into a web container.
Certain aspects of web component behavior can be configured when it is paged and deployed. The configuration information is maintained in a text filXML format called aweb application deployment descriptor. When you pack-age and deploy web components using the J2EE SDKdeploytool, it automati-cally generates or updates the deployment descriptor based on data thaenter indeploytool wizards and inspectors. You can also manually createdeployment descriptor according to the schema described in the Java Sespecification.
The process for creating, deploying, and executing a web component casummarized as follows:
1. Develop the web component code (including possibly a deploymdescriptor).
2. Package the web component along with any static resources (for examimages) referenced by the component.
3. Deploy the application.
4. Access a URL that references the web component.
WEB COMPONENT LIFE CYCLE 121
h theML
ks
These steps are expanded on in the following sections and are illustrated withello application. This application allows a user to enter a name into an HTform:
and then displays a greeting after the name is submitted:
Thehello application contains two web components:greeting andresponse.This tutorial has two versions of this application: a servlet version calledhello1
in which the web components are implemented by two servlet classes,Greet-
ingServlet.java andResponseServlet.java and a JSP version calledhello2in which the web components are implemented by two JSP pages,greet-
ing.jsp and response.jsp. The two versions are used to illustrate the tas
122 WEB COMPONENTS
om-
ssnts,
ofPd. The
lity
nd
ion
involved in packaging and deploying a J2EE application that contains web cponents.
Packaging Web ComponentsYou add web components to a J2EE application in a package called aweb appli-cation archive(WAR), which is a JAR similar to the package used for Java clalibraries. A WAR usually contains other resources besides web componeincluding:
• Server-side utility classes
• Static web resources (HTML, image, and sound files, and so on)
• Client-side classes (applets and utility classes)
A WAR has a specific hierarchical directory structure. The top-level directorya WAR is thedocument rootof the application. The document root is where JSpages, client-side classes and archives, and static web resources are storedocument root contains a subdirectory calledWEB-INF, which contains the fol-lowing files and directories:
• web.xml - the web application deployment descriptor
• Tag library descriptor files (seeTag Library Descriptors (page 210)).
• classes - a directory that contains server-side classes: servlet, uticlasses, and JavaBeans components.
• lib - a directory that contains JAR archives of libraries (tag libraries aany utility libraries called by server-side classes).
When you add files to a WAR,deploytool automatically packages them in thecorrect directory.
Note: The J2EE SDK version 1.3 betadeploytool packages client-side classesand archives in theWEB-INF subdirectory instead of the document root. As a con-sequence, the tutorial example that includes an applet (discussed inTheExampleJSP Pages(page 171)) uses a WAR created by theant make tool.
Creating a WARWhen you add the first web component to a J2EE application,deploytool auto-matically creates a new WAR to contain the component. A later sectdescribes how to add a web component.
PACKAGING WEB COMPONENTS 123
hetureion
od,t.
an
o
ick
theitspo-ationec-
You can also manually create a WAR with the JAR tool distributed with tJ2SE. If you arrange your application development directory in the strucrequired by the WAR format, it is straightforward to create a web applicatarchive file in the required format. You simply execute
jar cvf archiveName.war .
in the top-level directory of the application. Note that in order to use this methyou must also manually create a deployment descriptor in the correct forma
Adding a WAR to a J2EE ApplicationIf you manually create a WAR or you obtain a WAR from another party, you ceasily add it to an existing J2EE application as follows:
1. Select a J2EE application.
2. Select File->Add Web WAR to Application or click the Add Web WAR tApplication button.
3. Navigate to the directory containing the WAR, select the WAR, and clAdd Web WAR.
SeeThe Example JSP Pages (page 171) for an example.
Adding a Web Component to a WARThe following procedure describes how to add the web components inhello1 application to a WAR. Although the web component wizard solicWAR and component-level configuration information when you add the comnent, this chapter describes how to add the component and provide configurinformation at a later time using application, WAR, and web component insptors:
1. Go toexamples/src and build the example by runningant hello1 (seeHow to Build and Run the Examples (page xviii)).
2. Create a J2EE application calledhello1.
a. Select File->New Application or the New Application button.
b. Enterhello1.ear in the Application File Name field.
c. Click OK.
124 WEB COMPONENTS
m-
ct
.wav-
m-
1
tersd atme-
3. Add thegreeting web component and all the of thehello2 applicationcontent.
a. Invoke the web component wizard by selecting File->New Web Coponent or clicking the New Web Component button.
b. In the combo box labelled Create New WAR File in Application selethe hello1 application. Enterhello1 in the field labeled WAR DisplayName.
c. Click Add to add the content files.
d. In the Edit Contents dialog, navigate toexamples/build/web/hello1.Select GreetingServlet.class, ResponseServlet.class, and dukeing.gif, and click Add. Click OK.
e. Click Next.
f. Select the servlet radio button.
g. Click Next.
h. Select GreetingServlet from the Servlet Class combo box.
i. Typegreeting in the Web Component Name field.
j. Click Next and then click Finish.
4. Add theresponse web component.
a. Invoke the web component wizard by selecting File->New Web Coponent or clicking the New Web Component button.
b. In the combo box labelled Add to Existing WAR File select the helloWAR.
c. Click Next.
d. Select the servlet radio button.
e. Click Next.
f. Select ResponseServlet from the Servlet Class combo box.
g. Typeresponse in the Web Component Name field.
h. Click Next and then click Finish.
Configuring Web ComponentsThe following sections describe the web component configuration paramethat you will usually want to specify. Configuration parameters are specifiethree levels: application, WAR, and component. A number of security para
CONFIGURING WEB COMPONENTS 125
ecu-
lica-eb
n-
ntexts
ters can be applied at the WAR and component levels. For information on srity parameters, seeSecurity (page 253).
Application-Level Configuration
Context Root
A context rootis a path that gets mapped to the document root of a J2EE apption. If the entry URL of an application is the same as the base of the wserver’s URL namespace (for examplehttp://<host>:8000), the context rootis an empty string. If your application’s context root iscatalog, then a requestURL such ashttp://<host>:8000/catalog/index.html will retrieve the fileindex.html from the application’s document root.
To specify the context root for thehello1 application indeploytool,
1. Select the hello1 application.
2. Select the Web Context tab and enterhello1 in the Context Root field.
WAR-Level ConfigurationThe following sections give generic procedures for specifying WAR-level cofiguration information. For some specific examples, seeThe ExampleServlets (page 135).
Context Parameters
The web components in a WAR share an object that represents their web co(seeAccessingtheWebContext (page 159)). To specify initialization parameterthat are passed to the context,
1. Select the WAR.
2. Select the Context Parameters tab.
3. Click Add.
126 WEB COMPONENTS
ans,eclare
s or
ses
TTPcom-
-
xcep-
References to Environment Entries, Enterprise Beans, ResourceEnvironment Entries, or Resources
If your web components reference environment entries, enterprise beresource environment entries, or resources such as databases, you must dthe references as follows:
1. Select the WAR.
2. Select the Environment, Enterprise Bean Ref’s, Resource Env. Ref’Resource Ref’s tab.
3. Click Add in the panel to add a new reference.
Event Listeners
To add an event listener class (described inMonitoring Servlet Life CycleEvents (page 140)),
1. Select the WAR.
2. Select the Event Listeners tab.
3. Click Add.
4. Select the listener class from the new field in the Event Listener Claspanel.
Error Mapping
You can specify a mapping between the status code returned in an Hresponse or a Java programming language exception returned by any webponent and another web component or resource (seeHandlingErrors (page 142)). To set up the mapping,
1. Select the WAR.
2. Select the File Ref’s tab.
3. Click Add in the Error Mapping panel.
4. Enter the HTTP status code (seeHTTP Responses (page 308)) or fullyqualified class name of an exception in the Error/Exception field.
5. Enter the name of a resource to be invoked when the status code or etion is returned. The name should have a leading ‘/’.
CONFIGURING WEB COMPONENTS 127
rkes
ply
let asoern.la-t.
r to
the
Note: You can also define error pages for a JSP page contained in a WAR. If erropages are defined for both the WAR and a JSP page, the JSP page’s error page taprecedence.
Filter Mapping
A web container uses filter mapping declarations to decide which filters to apto a request, and in what order (seeFiltering Requests andResponses (page 151)). The container matches the request URI to a servdescribed inSpecifyingan Alias Path (page 128). To determine which filters tapply, it matches filter mapping declarations by servlet name or URL pattThe order in which filters are invoked is the order in which filter mapping decrations that match a request URI for a servlet appear in the filter mapping lis
You specify a filter mapping in thedeploytool as follows:
1. Select the WAR.
2. Select the Filter Mapping tab.
3. Add a filter
a. Click Edit Filter List.
b. Click Add.
c. Select the filter class.
d. Enter a filter name.
e. Add any filter initialization parameters.
f. Click OK.
4. Map the filter
a. Click Add.
b. Select the filter name.
c. Select the target type. A filter can be mapped to a specific servlet oall servlets that match a given URL pattern.
d. Specify the target. If the target is a servlet, select the servlet fromdrop-down list. If the target is a URL pattern, enter the pattern.
128 WEB COMPONENTS
itial-
webcon-root
musta ‘
speci-
the
Component-Level Configuration
Initialization Parameters
To specify parameters that are passed to the web component when it is inized,
1. Select the web component.
2. Select the Parameters tab.
3. Click Add to add a new parameter and value.
Specifying an Alias Path
When a request is received by a web container it must determine whichcomponent should handle the request. It does so by mapping the URL pathtained in the request to a web component. A URL path contains the context(described inContext Root (page 125)) and analias path:
http://<host>:8000/context root/alias path
Therefore, before your web component can be accessed, the web containerhave least one alias path for the component. The alias path must start with/’and end with a string or a wildcard expression with an extension (*.jsp forexample). Web containers automatically map an alias path that ends with*.jsp
to a servlet that transforms and compiles JSP pages, unless an applicationfies otherwise.
You set up the mappings for the servlet version of the Hello application usingweb component inspector as follows:
1. Select the greeting web component in the hello1 WAR.
2. Select the Aliases tab.
3. Click Add to add a new mapping.
4. Type/greeting in the aliases list.
5. Select the response web component in thehello1 WAR.
6. Click Add.
7. Type/response in the aliases list.
DEPLOYING WEB COMPONENTS 129
plica-the
to
at is
ur
Thethe
Deploying Web ComponentsThe next step after you have created, packaged, and configured a J2EE aption containing web components is to deploy the application. To deployhello1 application,
1. Select Tools->Deploy Application click the Deploy Application button.
2. Select the hello1 application from the combo box labeled ObjectDeploy.
3. Select a Target Server.
4. Click Next twice.
5. Click Finish.
Executing Web ComponentsA web component is executed when a web browser is pointed at a URL thmapped to the component. Once you have deployed thehello1 application, youcan run it by pointing a browser at:
http://<host>:8000/hello1/greeting
Replace<host> with the name of the host running the J2EE server. If yobrowser is running on the same host as the J2EE server, you may replace<host>
with localhost.
Updating Web ComponentsDuring development, you will often need to make changes to components.deploytool allows you to easily update the contents of a WAR and redeployJ2EE application.
To try this feature first build, package, and deploy the JSP version of thehello
application:
1. Go toexamples/src and build the example by runningant hello2.
2. Create a J2EE application calledhello2.
a. Select File->New Application or the New Application button.
b. Enterhello2.ear in the Application File Name field.
c. Click OK.
130 WEB COMPONENTS
m-
ct
dd.
m-
2
at
3. Add thegreeting web component and all the of thehello2 applicationcontent.
a. Invoke the web component wizard by selecting File->New Web Coponent or clicking the New Web Component button.
b. In the combo box labelled Create New WAR File in Application selethe hello2 application. Enterhello2 in the field labeled WAR DisplayName.
c. Click Add to add the content files.
d. In the Edit Contents dialog, navigate toexamples/build/web/hello2.Select greeting.jsp, response.jsp, and duke.waving.gif, and click AClick OK.
e. Click Next.
f. Select the JSP radio button.
g. Click Next.
h. Select greeting.jsp from the JSP Filename combo box.
i. Typegreeting in the Web Component Name field.
j. Click Next and then click Finish.
4. Add theresponse web component.
a. Invoke the web component wizard by selecting File->New Web Coponent or clicking the New Web Component button.
b. In the combo box labelled Add to Existing WAR File select the helloWAR.
c. Click Next.
d. Select the JSP radio button.
e. Click Next.
f. Select response.jsp from the JSP File Name combo box.
g. Typeresponse in the Web Component Name field.
h. Click Next and then click Finish.
5. Add the alias/greeting for thegreeting web component.
6. Specify the context roothello2.
7. Deploy thehello2 application.
8. Execute the application by pointing a web browserhttp://<host>:8000/hello2/greeting. Replace<host> with the nameof the host running the J2EE server.
UPDATING WEB COMPONENTS 131
ts of
that.
ploy
Now modify one of the JSP files. For example, you could replace the contenresponse.jsp with:
<h2><font color="red">Hello, <%=username%>!</font></h2>
To update the file in the WAR and redeploy the application:
1. Select the hello2 application.
2. Click the Update Files button. A message should appear indicatingresponse.jsp has changed and reminding you to save the application
3. Dismiss the message.
4. Select File->Save or the Save button.
5. Deploy thehello2 application.
You can also perform steps 2. through 5. by clicking the Update and Redebutton.
When you execute the application, the color of the greeting should be red:
132 WEB COMPONENTS
idersrliestus-
usingol-ech-lackated
Java ServletTechnology
by Stephanie Bodoff
AS soon as the web began to be used for delivering services, service provrecognized the need to serve dynamic content. Applets, one of the eaattempts towards this goal, focused on using the client platform to deliver ctomized user experiences. At the same time, developers also investigatedthe server platform for this purpose. Initially, CGI scripts were the main technogy used to generate dynamic content. Though widely used, CGI scripting tnology has a number of shortcomings including platform-dependence andof scalability. To address these limitations, Java Servlet technology was creas a portable way to provide dynamic, user-oriented content.
What is a Servlet? 134The Example Servlets 135
Troubleshooting 138Servlet Life Cycle 139
Monitoring Servlet Life Cycle Events 140Handling Errors 142
Sharing Information 142Scope Objects 142Controlling Concurrent Access to Shared Resources 143
Initializing a Servlet 145Writing Service Methods 145
Getting Information From Requests 146Constructing Responses 148
133
134 JAVA SERVLET TECHNOLOGY
es ofming
onlytions,
d
TTPmil-
Filtering Requests and Responses 151Defining the Filter Class 152Specifying Filter Mappings 155
Invoking Other Web Resources 156Including the Content of Another Resource in the Response 157Transferring a Control to Another Web Component 158
Accessing the Web Context 159Maintaining Client State 160
Accessing a Session 160Associating Attributes with a Session 161Session Management 162Session Tracking 162
Finalizing a Servlet 163Tracking Service Requests 164Providing a Clean Shutdown 165Creating Polite Long-Running Methods 166
What is a Servlet?A servlet is Java programming language class used to extend the capabilitiservers that host applications accessed via a request-response programmodel. Although servlets can respond to any type of request, they are commused to extend the applications hosted by web servers. For such applicaJava Servlet technology defines HTTP-specific servlet classes.
Thejavax.servlet andjavax.http.servlet packages provide interfaces anclasses for writing servlets. All servlets must implement theServlet interface,which defines life cycle methods.
When implementing a generic service, you can use or extend theGenericServ-
let class provided with the Java Servlet API. TheHttpServlet class providesmethods, such asdoGet anddoPost, for handling HTTP-specific services.
This chapter focuses on writing servlets that generate responses to Hrequests. Some knowledge of the HTTP protocol is assumed; if you are unfaiar with this protocol, you can get a brief introduction to HTTP inHTTPOverview (page 307).
THE EXAMPLE SERVLETS 135
alled
isious
base
g
The Example ServletsTo illustrate servlet capabilities, this chapter uses an example application cDuke’s Bookstore. The source for the application is located inexam-ples/src/web/bookstore1. As shown in Table 9, each bookstore functionprovided by a servlet. Different sections use the servlets to illustrate vartasks. For example,BookDetailsServlet illustrates how to handle HTTP GETrequests andCatalogServlet shows you how to track session information.
The data for the bookstore application is maintained in a Cloudscape dataand is accessed through the helper classdatabase.BookDB. Thedatabase pack-age also contains the classBookDetails which represents a book. The shoppincart and shopping cart items are represented by the classescart.ShoppingCart
andcart.ShoppingCartItem.
Table 9 Duke’s Bookstore Example Servlets
Function Servlet
Enter the bookstore BookStoreServlet
Create the bookstore banner BannerServlet
Browse the bookstore catalog CatalogServlet
Put a book in a shopping cart CatalogServlet and BookDetailsServlet
Get detailed information on a specificbook
BookDetailsServlet
Display the shopping cart ShowCartServlet
Remove one or more books from theshopping cart
ShowCartServlet
Buy the books in the shopping cart CashierServlet
Receive an acknowledgement for thepurchase
ReceiptServlet
136 JAVA SERVLET TECHNOLOGY
ct
e-ss,lass.ta-
To build, deploy, and run the example:
1. Go toexamples/src and build the example by runningant bookstore1
(SeeHow to Build and Run the Examples (page xviii)).
2. Start the Cloudscape database server by runningcloudscape -start.
3. Load the bookstore data into the database by runningant create-web-
db.
4. Start thej2ee server
5. Startdeploytool
6. Create a J2EE application calledbookstore1.
a. Select File->New Application or the New Application button.
b. Enterbookstore1.ear in the Application File Name field.
c. Click OK.
7. Add thebanner web component and all of theDuke’s Bookstore contentto thebookstore1 application.
a. Select File->New Web Component or the Web Component button.
b. Click the Create New WAR File in Application radio button and selethe bookstore1 application from the combo box. Enterbookstore1 inthe field labeled WAR Display Name.
c. Click Add to add the content files.
d. In the Edit Archive Contents dialog box, navigate toexam-ples/build/web/bookstore1. Select BannerServlet.class, BookStorServlet.class, BookDetailsServlet.class, CatalogServlet.claShowCartServlet.class, CashierServlet.class, and ReceiptServlet.cClick Add. Add errorpage.html and duke.books.gif. Add the cart, dabase, exception, filters, listeners, and util packages. Click OK.
e. Click Next.
f. Select the servlet radio button.
g. Click Next.
h. Select BannerServlet from the Servlet Class combo box.
i. Typebanner in the Web Component Name field.
j. Click Next twice.
k. In the Component Aliases panel click Add and then type/banner in thealias field.
l. Click Finish.
THE EXAMPLE SERVLETS 137
lickhe
the
8. Add each of the web components listed in Table 10. For each servlet, cthe Add to Existing WAR radio button and select bookstore1 from tcombo box.
9. Add a resource reference for the Cloudscape database.
a. Select thebookstore1 WAR.
b. Select the Resource Ref’s tab.
c. Click Add.
d. Select javax.sql.DataSource from the Type column
e. Enterjdbc/BookDB in the Coded Name field.
f. Enterjdbc/Cloudscape in the JNDI Name field.
10.Add the listener classlisteners.ContextListener (described inMoni-toring Servlet Life Cycle Events (page 140).
a. Select thebookstore1 WAR.
b. Select the Event Listeners tab.
c. Click Add.
d. Select the listeners.ContextListener class from drop down field inEvent Listener Classes panel.
11.Add an error page (described inHandling Errors (page 142)).
a. Select thebookstore1 WAR.
b. Select the File Ref’s tab.
Table 10 Duke’s Bookstore Web Components
Web Component Name Servlet Class Component Alias
enter BookStoreServlet /enter
catalog CatalogServlet /catalog
bookdetails BookDetailsServlet /bookdetails
showcart ShowCartServlet /showcart
cashier CashierServlet /cashier
receipt ReceiptServlet /receipt
138 JAVA SERVLET TECHNOLOGY
t is
oy
l. In
with
c. Click Add in the Error Mapping panel.
d. Enter exception.BookNotFoundException in the Error/Exceptionfield.
e. Enter/errorpage.html in the Resource to be Called field.
f. Repeat forexception.BooksNotFoundException and javax.serv-
let.UnavailableException.
12.Add the filtersfilters.HitCounterFilter andfilters.OrderFilter(described inFiltering Requests and Responses (page 151)).
a. Select thebookstore1 WAR.
b. Select the Filter Mapping tab.
c. Click Edit Filter List.
d. Click Add.
e. Select the filter class filters.HitCounterFilter.
f. Select the display nameHitCounterFilter.
g. Repeat for filters.OrderFilter.
h. Click OK.
i. Click Add.
j. Select the filter name HitCounterFilter.
k. Select URL Pattern for the Target Type.
l. Enter the target/enter.
m.Repeat for OrderFilter. The target type is URL Pattern and the targe/receipt.
13.Deploy the application. Select Tools->Deploy Application or the DeplApplication Button. Enter the context rootbookstore1.
14.Open the bookstore URLhttp://<host>:8000/bookstore1/enter.
TroubleshootingCommon Problemsand Their Solutions (page 61) (in particularWeb ClientRuntimeErrors (page 63)) lists some reasons why a web application can faiaddition,Duke’s Bookstore returns the following exceptions:
• BookNotFoundException - if a book can’t be located in the bookstoredatabase. This will occur if you haven’t loaded the bookstore database
SERVLET LIFE CYCLE 139
t
sun-ed
ted
e of
e in
asforms
er-
data by runningant create-web-db or if the Cloudscape server hasn’been started or it has crashed.
• BooksNotFoundException - if the bookstore data can’t be retrieved. Thiwill occur if you haven’t loaded the bookstore database with data by rning ant create-web-db or if the Cloudscape server hasn’t been startor it has crashed.
• UnavailableException - if a servlet can’t retrieve the web contexattribute representing the bookstore. This will occur if you haven’t addthe listener class to the application.
Since we have specified an error page, you will see the messageThe applica-
tion is unavailable. Please try later. If you don’t specify an error page,the web container generates a default page containing the messageA Servlet
Exception Has Occurred and a stack trace that can help diagnose the causthe exception. If you use theerrorpage.html, you will have to look in the webcontainer’s log to determine the cause of the exception. Web log files residthe directory:
$J2EE_HOME/<logs>/<host>/web
and are namedcatalina.<date>.log.
The<logs> element is the directory specified by thelog.directory entry in thedefault.properties file. The default value islogs. The<host> element is thename of the computer. See theConfiguration Guideprovided with the J2EESDK for more information about J2EE SDK log files.
Servlet Life CycleThe life cycle of a servlet is controlled by the container in which the servlet hbeen deployed. When a request is mapped to a servlet, the container perthe following steps:
1. If an instance of the servlet does not exist, the container:
a. Loads the servlet class
b. Instantiates an instance of the servlet class
c. Initializes the servlet instance by calling theinit method. Initializationis covered inInitializing a Servlet (page 145).
2. Invokes theservice method, passing a request and response object. Svice methods are discussed inWriting Service Methods (page 145).
140 JAVA SERVLET TECHNOLOGY
the
nerhese
le 11mustthatthe
If the container needs to remove the servlet, it finalizes the servlet by callingservlet’s destroy method. Finalization is discussed inFinalizing aServlet (page 163).
Monitoring Servlet Life Cycle EventsYou can monitor and react to events in a servlet’s life cycle by defining listeobjects whose methods get invoked when life cycle events occur. To use tlistener objects you must
• Define the listener class
• Specify the listener class
Defining The Listener Class
You define a listener class as an implementation of a listener interface. Tablists the events that can be monitored and the corresponding interface thatbe implemented. When a listener method is invoked it is passed an eventcontains information appropriate to the event. For example, the methods inHttpSessionListener interface are passed anHttpSessionEvent, which con-tains anHttpSession.
Table 11 Servlet Life Cycle Events
Object Event Listener Interface and Event Class
Web context(SeeAccessingthe WebContext (page 159))
Initializationand destruction
javax.servlet.ServletContextListener andServletContextEvent
Attribute added,removed, orreplaced
javax.servlet.ServletContextAttributesListener andServletContextAttributeEvent
Session(SeeMaintainingClientState(page 160))
Creation,invalidation,andtimeout
javax.servlet.http.HttpSessionListener andHttpSessionEvent
Attribute added,removed, orreplaced
javax.servlet.http.HttpSessionAttributesListener andHttpSessionBindingEvent
SERVLET LIFE CYCLE 141
se
The listeners.ContextListener class creates and removes the databahelper and counter objects used in theDuke’s Bookstore application. Themethods retrieve the web context object fromServletContextEvent and thenstore (and remove) the objects as servlet context attributes.import database.BookDB;import javax.servlet.*;import util.Counter;
public final class ContextListener implements ServletContextListener { private ServletContext context = null; public void contextInitialized(ServletContextEvent event) { context = event.getServletContext(); try { BookDB bookDB = new BookDB(); context.setAttribute("bookDB", bookDB); } catch (Exception ex) { System.out.println( "Couldn't create database: " + ex.getMessage()); } Counter counter = new Counter(); context.setAttribute("hitCounter", counter); context.log("Created hitCounter" + counter.getCounter()); counter = new Counter(); context.setAttribute("orderCounter", counter); context.log("Created orderCounter" + counter.getCounter()); }
public void contextDestroyed(ServletContextEvent event) { context = event.getServletContext(); BookDB bookDB = context.getAttribute( "bookDB"); bookDB.remove(); context.removeAttribute("bookDB"); context.removeAttribute("hitCounter"); context.removeAttribute("orderCounter"); }}
Specifying Event Listener Classes
You specify a listener class for a WAR in thedeploytool Event Listenersinspector (seeEvent Listeners (page 126)).
142 JAVA SERVLET TECHNOLOGY
con-
thecify
om-ivatets that. Thether
asthe
lists
Handling ErrorsAny number of exceptions can occur when a servlet is executed. The webtainer will generate a default page containing the messageA Servlet Excep-
tion Has Occurred when an exception occurs, but you can also specify thatcontainer should return a specific error page for a given exception. You speerror pages for a WAR in thedeploytool File Ref’s inspector (ErrorMapping (page 126)).
Sharing InformationWeb components, like most objects, usually work with other objects to accplish their tasks. There are several ways they can do this. They can use prhelper objects (for example, JavaBeans components), they can share objecare attributes of a public scope, and they can invoke other web resourcesJava Servlet technology mechanisms that allow a web component to invoke oweb resources are described inInvoking Other Web Resources (page 156).
Scope ObjectsCollaborating web components share information via objects maintainedattributes of four scope objects. These attributes are accessed with[get|set]Attribute methods of the class representing the scope. Table 12the scope objects.
Table 12 Scope Objects
ScopeObject Class Accessible From
web contextjavax.servlet.ServletContext
Web components within a Web context. SeeAccessing the Web Context (page 159).
sessionjavax.servlet.http.HttpSession
Web components handling a request that belongs tothe session. SeeMaintaining ClientState(page 160).
requestsubtype ofjavax.servlet.ServletRequest
Web components handling the request.
SHARING INFORMATION 143
con-mory, data-n sev-
t
Figure 13shows the scoped attributes maintained by theDuke’s Bookstore
application.
Figure 13 Duke’s Bookstore Scoped Attributes
Controlling Concurrent Access to Shared ResourcesIn a multithreaded server, it is possible for shared resources to be accessedcurrently. Besides scope object attributes, shared resources include in-medata such as instance or class variables and external objects such as filesbase connections, and network connections. Concurrent access can arise ieral situations:
• Multiple web components accessing objects stored in the web contex
• Multiple web components accessing objects stored in a session
pagejavax.servlet.jsp.PageContext
The JSP page that creates the object. SeeJavaServer Pages™ Technology(page 167).
Table 12 Scope Objects (Continued)
ScopeObject Class Accessible From
hitCounter bookDB orderCounter
Web contextattributes
Session attributecart
BookStoreServlet
ShowCartServlet
ReceiptServlet
CatalogServlet
CashierServlet
BookDetailsServlet
orderFilter
hitCounterFilter
144 JAVA SERVLET TECHNOLOGY
s. Ayoume, a
xe-cane ofdis-pre-sing
onsis-niza-
mul-s
• Multiple threads within a web component accessing instance variableweb container will typically create a thread to handle each request. Ifwant to ensure that a servlet instance handles only one request at a tiservlet can implement theSingleThreadModel interface. If a servletimplements this interface, you are guaranteed that no two threads will ecute concurrently in the servlet’s service method. A web containerimplement this guarantee by synchronizing access to a single instancthe servlet, or by maintaining a pool of web component instances andpatching each new request to a free instance. This interface does notvent synchronization problems that result from web components accesshared resources such as static class variables or external objects.
When resources can be accessed concurrently, they can be used in an inctent fashion. To prevent this, you must control the access using the synchrotion techniques described in the Threads lesson in the Java Tutorial.
The Duke’s Bookstore database helper objectBookDB maintains a databaseconnection that is referenced by an instance variable namedcon. Only one serv-let can use connection at a time. Since the servlets accessing this object aretithreaded, access to thecon variable is controlled by the synchronized methodgetConnection andreleaseConnection.
private Connection con;private boolean conFree = true;public BookDB () throws Exception { try { InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup(dbName); con = ds.getConnection(); } catch (Exception ex) { throw new Exception( "Couldn't open connection to database: " + ex.getMessage()); }}protected synchronized Connection getConnection() { while (conFree == false) { try { wait(); } catch (InterruptedException e) { ... } } conFree = false; notify(); return con;
INITIALIZING A SERVLET 145
re itcandata,thel-
web
}
protected synchronized void releaseConnection() { while (conFree == true) { try { wait(); } catch (InterruptedException e) { ... } } conFree = true; notify();}
Initializing a ServletAfter the web container loads and instantiates the servlet class and befodelivers requests from clients, the web container initializes the servlet. Youcustomize this process to allow the servlet to read persistent configurationinitialize resources, and perform any other one-time activities by overridinginit method of theServlet interface. A servlet that cannot complete its initiaization process should throwUnavailableException.
All the servlets that access the bookstore database (BookStoreServlet, Cata-logServlet, BookDetailsServlet, andShowCartServlet) initialize a variablein theirinit method that points to the database helper object created by thecontext listener:
public class CatalogServlet extends HttpServlet { private BookDB bookDB; public void init() throws ServletException { bookDB = (BookDB)getServletContext(). getAttribute("bookDB"); if (bookDB == null) throw new UnavailableException("Couldn't get database."); }}
Writing Service MethodsThe service provided by a servlet is implemented in theservice method of aGenericServlet, thedoMethod methods (whereMethod can take the valueGet,Delete, Options, Post, Put, Trace) of anHttpServlet, or any other protocol-
146 JAVA SERVLET TECHNOLOGY
in a
theon that
first, and
must
tent.ner-
uestsr
cli-
ionerv-
the
rcode
e the
specific methods defined by a class that implements theServlet interface. In therest of this chapter, the term “service method” will be used for any methodservlet class that provides a service to a client.
The general pattern for a service method is to extract information fromrequest, access external resources, and then populate the response basedinformation.
For HTTP servlets, the correct procedure for populating the response is tofill in the response headers, then retrieve an output stream from the responsefinally write any body content to the output stream. Response headersalways be set before aPrintWriter or ServletOutputStream is retrievedbecause the HTTP protocol expects to receive all headers before body conThe next two sections describe how to get information from requests and geate responses.
Getting Information From RequestsA request contains data passed between a client and the servlet. All reqimplement theServletRequest interface. This interface defines methods foaccessing the following information:
• Parameters, which are typically used to convey information betweenents and servlets
• Object-valued attributes, which are typically used to pass informatbetween the servlet container and a servlet or between collaborating slets
• Information about the protocol used to communicate the request andclient and server involved in the request
• Information relevant to localization
For example, inCatalogServlet the identifier of the book that a customewishes to purchase is included as a parameter to the request. The followingfragment illustrates how to use thegetParameter method to extract the identi-fier:
String bookId = request.getParameter("Add");if (bookId != null) { BookDetails book = bookDB.getBookDetails(bookId);
You can also retrieve an input stream from the request and manually parsdata. To read character data, use theBufferedReader object returned by the
WRITING SERVICE METHODS 147
lias
ath
on-
request’sgetReader method. To read binary data, use theServletInputStream
returned bygetInputStream.
HTTP servlets are passed an HTTP request object,HttpServletRequest, whichcontains the request URL, HTTP headers, query string, and so on.
An HTTP request URL contains the following parts:
http://[host]:[port][request path]?[query string]
The request path is further composed of the following elements:
• Context path: A concatenation of’/’with the context root of the servlet’sJ2EE application.
• Servlet path: The path section that corresponds to the component athat activated this request. This path starts with a’/’.
• Path info: The part of the request path that is not part of the context por the servlet path.
Table 14 gives some examples of how the URL will be broken down if the ctext path is/catalog, and the aliases are as listed in Table 13:
Table 13 Aliases
Pattern Servlet
/lawn/* LawnServlet
/*.jsp JSPServlet
Table 14 Request Path Elements
Request Path Servlet Path Path Info
/catalog/lawn/index.html /lawn /index.html
/catalog/help/feedback.jsp /help/feedback.jsp null
148 JAVA SERVLET TECHNOLOGY
ram-
L
ded
onsesat
arac-
het toingrs or
Query strings are composed of a set of parameters and values. Individual paeters are retrieved from a request with thegetParameter method. There are twoways to generate query strings:
• A query string can explicitly appear in a web page. For example, an HTMpage generated by theCatalogServlet could contain the link<ahref="/bookstore1/catalog?Add=101">Add To Cart</a>. Cata-
logServlet extracts the parameter namedAdd as follows:
String bookId = request.getParameter("Add");
• A query string is appended to a URL when a form with aGET HTTPmethod is submitted. In theDuke’s Bookstore application, Cash-ierServlet generates a form, a user name input to the form is appento the URL that maps toReceiptServlet, andReceiptServlet extractsthe user name using thegetParameter method.
Constructing ResponsesA response contains data passed between a server and the client. All respimplement theServletResponse interface. This interface defines methods thallow you to:
• Retrieve an output stream to use to send data to the client. To send chter data, use thePrintWriter returned by the response’sgetWritermethod. To send binary data in a MIME body response, use theServ-
letOutputStream returned bygetOutputStream. To mix binary and textdata, for example, to create a multipart response, use aServletOutput-
Stream and manage the character sections manually.
• Indicate the content type (for example,text/html), being returned by theresponse. A registry of content type names is kept by IANA at:
ftp://ftp.isi.edu/in-notes/iana/assignments/media-types
• Indicate whether to buffer output. By default, any content written to toutput stream is immediately sent to the client. Buffering allows contenbe written before anything is actually sent back to the client, thus providthe servlet with more time to set appropriate status codes and headeforward to another web resource.
• Set localization information.
WRITING SERVICE METHODS 149
t sat-
cli-g a
-Thebuffergener-the
ion.
m abookthatlling
HTTP response objects,HttpServletResponse, also have fields representingHTTP headers such as
• Status codes, which are used to indicate the reason of a request is noisfied.
• Cookies, which are used to store application-specific information at theent. Sometimes cookies are used to maintain an identifier for trackinuser’s session (seeMaintaining Client State (page 160)).
In Duke’s Bookstore, BookDetailsServlet generates an HTML page that displays information about a book which the servlet retrieves from a database.servlet first sets response headers: the context type of the response and thesize. The servlet buffers the page content because the database access canate an exception that would cause forwarding to an error page. By bufferingresponse, the client will not see a concatenation of part of aDuke’s Bookstore
page with the error page should an error occur. ThedoGet method then retrievesaPrintWriter from the response.
For filling in the response, the servlet first dispatches the request toBannerServ-
let, which generates a common banner for all the servlets in the applicatThis process is discussed inIncluding the Contentof AnotherResourcein theResponse (page 157). Then the servlet retrieves the book identifier frorequest parameter and uses the identifier to retrieve information about thefrom the bookstore database. Finally the servlet generates HTML markupdescribes the book information and commits the response to the client by catheclose method on thePrintWriter.
public class BookDetailsServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set headers before accessing the Writer response.setContentType("text/html"); response.setBufferSize(8192); PrintWriter out = response.getWriter();
// then write the response out.println("<html>" + "<head><title>Book Description</title></head>");
// Get the dispatcher; it gets the banner to the user RequestDispatcher dispatcher = getServletContext(). getRequestDispatcher("/banner"); if (dispatcher != null)
150 JAVA SERVLET TECHNOLOGY
dispatcher.include(request, response);
//Get the identifier of the book to display String bookId = request.getParameter("bookId"); if (bookId != null) { // and the information about the book try { BookDetails bd = bookDB.getBookDetails(bookId); ... //Print out the information obtained out.println("<h2>" + bd.getTitle() + "</h2>" + ... } catch (BookNotFoundException ex) { response.resetBuffer(); throw new ServletException(ex); } } out.println("</body></html>"); out.close(); }}
BookDetailsServlet generates a page that looks like:
FILTERING REQUESTS ANDRESPONSES 151
st orem-ncies
ableper-
n of
f the
ata on.
Filtering Requests and ResponsesA filter is an object that can transform the header and/or content of a requeresponse. Filters differ from web components in that they usually do not thselves create a response. In particular, a filter should not have any dependeon a web resource for which it is acting as a filter so that it can be composwith more than one type of web resource. The main tasks that a filter canform are:
• Modify the request headers and data by providing a customized versiothe request
• Modify the response headers data by providing a customized version oresponse
• Interact with external resources
Applications of filters include authentication, logging, image conversion, dcompression, encryption, tokenizing streams, XML transformations, and so
152 JAVA SERVLET TECHNOLOGY
zero,
t,ing
r
-
er, theextgnd
ted).l tong
ain
nd
erntext
nro-
You can configure web components and static resources to be filtered byone, or more filters in a specific order. Thus, to use filters you must:
• Define the filter class
• Specify the mapping of filters to web components or static resources
Defining the Filter ClassYou define a filter class by implementing theFilter interface. The most impor-tant method in this interface is thedoFilter method, which is passed requesresponse, and filter chain objects. This method can perform the followactions:
• Examine the request headers
• Wrap the request object with a customized implementation ofServletRe-
quest or HttpServletRequest if it wishes to modify request headers odata
• Wrap the response object with a customized implementation ofServlet-
Response or HttpServletResponse if it wishes to modify response headers or data
• Invoke the next entity in the filter chain. If the current filter is the last filtin the chain that ends with the target web component or static resourcenext entity is the resource at the end of the chain; otherwise, it is the nfilter that was configured in the WAR. It invokes the next entity by callinthe doFilter method on the chain object (passing in the request aresponse it was called with, or the wrapped versions it may have creaAlternatively, it can choose to block the request by not making the calinvoke the next entity. In the latter case, the filter is responsible for filliout the response.
• Examine response headers after it has invoked the next filter in the ch
• Throw an exception to indicate an error in processing
The Duke’s Bookstore application uses the filtersHitCounterFilter andOrderFilter to increment and log the value of a counter when the entry areceipt servlets are accessed.
In the doFilter method, both filters retrieve the servlet context from the filtconfiguration object so that they can access the counters stored as coattributes. When you write the filter, you must implement the [set|get]Filter-
Config methods. ThesetFilterConfig method is called by the container whethe filter is instantiated. After the filters have completed application-specific p
FILTERING REQUESTS ANDRESPONSES 153
l
the
ext
-
the
cessing, they invokedoFilter on the filter chain object passed into the originadoFilter method.
In addition to logging the value of the hit counter,HitCounterFilter alsoinserts the value of the counter into the response. It does this by wrappingresponse in an object CharResponseWrapper which extendsHttpServletResponseWrapper. The wrapped response is passed to the nobject in the filter chain, which isBookStoreServlet. WhenBookStoreServ-let calls getWriter on the wrapper, it receives a stand-in print writer implemented byFilterPrintWriter. This layering of print writers is necessarybecause normally a servlet closes a print writer when it completes and thenfilter would not be able to print to that writer.BookStoreServlet writes itsresponse into theFilterPrintWriter. When chain.doFilter returns,Hit-CounterFilter retrieves the servlet’s response fromFilterPrintWriter withthe getData method, and writes it to the originalPrintWriter. The filter theninserts the value of the counter into the originalPrintWriter.
public final class OrderFilter implements Filter { private FilterConfig filterConfig = null;
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return;
StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Counter counter = (Counter)filterConfig. getServletContext(). getAttribute("hitCounter"); writer.println(); writer.println("==============="); writer.println("The number of hits is: " + counter.incCounter()); writer.println("===============");
// Log the resulting string writer.flush(); filterConfig.getServletContext(). log(sw.getBuffer().toString());
PrintWriter out = response.getWriter(); CharResponseWrapper wrapper = new CharResponseWrapper( (HttpServletResponse)response); chain.doFilter(request, wrapper);
154 JAVA SERVLET TECHNOLOGY
out.write(wrapper.getData()); out.println("<center>You are visitor number <font color='red'>" + counter.getCounter() + "</font></center>"); } public FilterConfig getFilterConfig() { return (this.filterConfig); } public void setFilterConfig(FilterConfig filterConfig) { this.filterConfig = filterConfig; }}
public class CharResponseWrapper extends HttpServletResponseWrapper { private CharArrayWriter output; public char[] getData() { return output.toCharArray(); } public CharResponseWrapper(HttpServletResponse response){ super(response); output = new CharArrayWriter(); } public PrintWriter getWriter(){ return new FilterPrintWriter(output); }}
class FilterPrintWriter extends PrintWriter { private PrintWriter writer; public FilterPrintWriter(Writer output) { super(output); writer = new PrintWriter(output); } public void println(String s) { writer.println(s); }}
FILTERING REQUESTS ANDRESPONSES 155
ebr tod in
ou
Figure 14 shows the entry page for Duke’s Bookstore with the hit counter.
Figure 14 Duke’s Bookstore
Specifying Filter MappingsA web container uses filter mappings to decide how to apply filters to wresources. A filter mapping matches a filter to a web component by name oweb components and static resources by URL pattern. The filters are invokethe order that filter mappings appear in the filter mapping list of a WAR. Yspecify a filter mapping list for a WAR in thedeploytool Filter Mappinginspector (seeFilter Mapping (page 127)).
156 JAVA SERVLET TECHNOLOGY
one
and
s atheLs
ing.or it
ent,
t,the
e path
ple-
is
Table 15 contains the filter mapping list for theDuke’s Bookstore application.The filters are matched by URL mapping and each filter chain contains onlyfilter.
Invoking Other Web ResourcesWeb components can invoke other web resources in two ways: indirectdirect.
A web component indirectly invokes another web resource when it embedURL that points to another web component in content returned to a client. InDuke’s Bookstore application, most web components contain embedded URthat point to other web components. For example,ReceiptServlet indirectlyinvokes theCatalogServlet through the embedded URL/bookstore1/cata-log.
A web component can also directly invoke another resource while it is executThere are two possibilities: it can include the content of another resource,can forward a request to another resource.
To invoke a resource available on the server that is running a web componyou must first obtain aRequestDispatcher using the getRequestDis-
patcher("URL") method.
You can get aRequestDispatcher from either a request or the web contexhowever, the two methods have slightly different behavior. The method takespath to the requested resource as an argument. A request can take a relativ(that is, one that does not begin with a’/’), but the web context requires anabsolute path. If the resource is not available, or if the server has not immented aRequestDispatcher object for that type of resource,getRequestDis-patcher will return null. Your servlet should be prepared to deal with thcondition.
Table 15 Duke’s Bookstore Filter Mapping List
URL Pattern Filter
/enter HitCounterFilter
/receipt OrderFilter
INVOKING OTHER WEB RESOURCES 157
con-ent.
esend, anderv-ited
Including the Content of Another Resource in theResponseIt is often useful to include content of another resource, for example, bannertent or copyright information, in the response returned from a web componTo include the content of another resource, invoke theinclude method of aRequestDispatcher:
include(request, response);
If the resource is static, theinclude method enables programmatic server-sidincludes. If the resource is a web component, the effect of the method is tothe request to the included web component, execute the web componentthen include the result of the execution in the response from the containing slet. An included web component has access to the request object, but it is limin what it can do with the response object:
• It can write to the body of and commit a response.
• It cannot set headers or call any method (for example,setCookie) thataffects the headers of the response.
The banner for theDuke’s Bookstore application is generated byBannerServ-let. Note that bothdoGet anddoPost methods are implemented becauseBan-
nerServlet can be dispatched from either method in a calling servlet.
public class BannerServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter(); out.println("<body bgcolor=\"#ffffff\">" + "<center>" + "<hr> <br> " + "<h1>" + "<font size=\"+3\" color=\"#CC0066\">Duke's </font>" + <img src=\"" + request.getContextPath() + "/duke.books.gif\">" + "<font size=\"+3\" color=\"black\">Bookstore</font>" + "</h1>" + "</center>" + "<br> <hr> <br> "); }
public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
158 JAVA SERVLET TECHNOLOGY
aryexam-ther
toss-
ves
out.println("<body bgcolor=\"#ffffff\">" + "<center>" + "<hr> <br> " + "<h1>" + "<font size=\"+3\" color=\"#CC0066\">Duke's </font>" + <img src=\"" + request.getContextPath() + "/duke.books.gif\">" + "<font size=\"+3\" color=\"black\">Bookstore</font>" + "</h1>" + "</center>" + "<br> <hr> <br> "); }}
Each servlet in theDuke’s Bookstore application includes the result fromBan-nerServlet with the following code:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner");if (dispatcher != null) dispatcher.include(request, response);}
Transferring a Control to Another Web ComponentIn some applications you might want to have one web component do preliminprocessing of a request and another component generate the response. Forple, you might want to partially process a request and then transfer to anocomponent depending on the nature of the request.
To transfer control to another web component, you invoke theforward methodof aRequestDispatcher. When a request is forwarded, the request URL is setthe path of the forwarded page. If the original URL is required for any proceing you can save it as a request attribute. TheDispatcher servlet, used by a ver-sion of the Duke’s Bookstore application described inA Template TagLibrary (page 227), saves the path information from the original URL, retrieaRequestDispatcher from the request, and then forwards to the JSP pagetem-
plate.jsp.
public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { request.setAttribute("selectedScreen", request.getServletPath()); RequestDispatcher dispatcher = request. getDispatcher("/template.jsp"); if (dispatcher != null) dispatcher.forward(request, response);
ACCESSING THEWEB CONTEXT 159
for
an
the
pati-the
} public void doPost(HttpServletRequest request, ...}
Theforward method should be used to give another resource responsibilityreplying to the user. If you have already accessed aServletOutputStream orPrintWriter object within the servlet, you cannot use this method; it throwsIllegalStateException.
Accessing the Web ContextThe context in which web components execute is an object that implementsServletContext interface. You retrieve the web context with thegetServlet-Context method. The web context provides methods for accessing:
• Initialization parameters
• Resources associated with the web context
• Object-valued attributes
• Logging capabilities
The web context is used by theDuke’s Bookstore filters filters.Hit-
CounterFilter and OrderFilter discussed in Filtering Requests andResponses (page 151). The filters store a counter (util.Counter) as a contextattribute. The counter’s access methods are synchronized to prevent incomble operations by servlets that are running concurrently. A filter retrievescounter object with the context’sgetAttribute method. The incremented valueof the counter is recorded with the context’slog method.
public final class HitCounterFilter implements Filter { private FilterConfig filterConfig = null; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ... StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); ServletContext context = filterConfig. getServletContext(); Counter counter = (Counter)context. getAttribute("hitCounter"); ... writer.println("The number of hits is: " +
160 JAVA SERVLET TECHNOLOGY
with
ble fors.pro-ple-
yur-a ses-s
eve a
counter.incCounter()); ... context.log(sw.getBuffer().toString()); ... }}
public class Counter { private int counter; public Counter() { counter = 0; } public synchronized int getCounter() { return counter; } public synchronized int incCounter() { return(counter++); }}
Maintaining Client StateMany applications require a series of requests from a client to be associatedone another. For example, theDuke’s Bookstore application saves the state of auser’s shopping cart across requests. Web-based applications are responsimaintaining such state, called asession, because the HTTP protocol is statelesTo support applications that need to maintain state, Java Servlet technologyvides an API for managing sessions and allows several mechanisms for immenting sessions.
Accessing a SessionSessions are represented by anHttpSession object. You access a session bcalling thegetSession method of a request object. This method returns the crent session associated with this request, or, if the request does not havesion, creates one. SincegetSession may modify the response header (if cookieare the session tracking mechanism), it needs to be called before you retriPrintWriter or ServletOutputStream.
MAINTAINING CLIENT STATE 161
uchweb
es-and
rt,
ects
th a
this
d/orved
Associating Attributes with a SessionYou can associate object-valued attributes with a session by name. Sattributes are accessible by any web component that belongs to the samecontextand is handling a request that is part of the same session.
TheDuke’s Bookstore application stores a customer’s shopping cart as a ssion attribute. This allows the shopping cart to be saved between requestsalso allows cooperating servlets to access the cart.CatalogServlet adds itemsto the cart,ShowCartServlet displays, deletes items from, and clears the caandCashierServlet retrieves the total cost of the books in the cart.
public class CashierServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the user's session and shopping cart HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart)session. getAttribute("cart"); ... // Determine the total price of the user's books double total = cart.getTotal();
Notifying Objects That Are Added To a Session
Recall that your application can notify web context and session listener objof servlet life cycle events (Monitoring ServletLife Cycle Events (page 140)).You can also notify objects of certain events related to their association wisession:
• When the object is added to or removed from a session. To receivenotification, your object must implement thejavax.http.HttpSession-BindingListener interface.
• When the session to which the object is attached will be passivated anactivated. A session will be passivated and activated when it is mobetween VMs or saved to and restored from persistent storage. To receivethis notification, your object must implement thejavax.http.HttpSes-sionActivationListener interface.
162 JAVA SERVLET TECHNOLOGY
ses-an be
cesso-live
oveded.
-
, all ofainany
ssionthe
n ID
Session ManagementSince there is no way for an HTTP client to signal that it no longer needs asion, each session has an associated time-out so that its resources creclaimed. The time-out period can be accessed with a session’s[get|set]Max-
InactiveInterval methods. You can also set the time-out period indeploy-
tool:
1. Select the WAR.
2. Select the General tab.
3. Enter the time-out period in the Advanced box.
To ensure that an active session is not timed-out, you should periodically acthe session in service methods because this resets the session’s time-tcounter.
When a particular client interaction is finished, you use the session’sinvali-
date method to delete a session on the server side. The session data is remand when a new request is made to the servlet, a new session will be creat
The bookstore application’sReceiptServlet is the last servlet to access a client’s session, so it has responsibility for invalidating the session:
public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); // Payment received -- invalidate the session session.invalidate(); ...
Session TrackingA web container can use several methods to associate a session with a userwhich involve passing an identifier between the client and server. The mmethods require the client to accept cookies or the web component to rewriteURL that is returned to the client.
If your application makes use of session objects, you must ensure that setracking is enabled by allowing the application to rewrite a URL wheneverclient turns off cookies. You do this by calling the response’sencodeURL(URL)
method on all URLs returned by a servlet. This method includes the sessio
FINALIZING A SERVLET 163
L
fol-
ser-, or
e anyre-
is
in the URL only if cookies are disabled; otherwise it returns the URunchanged.
ThedoGet method ofShowCartServlet encodes the three URLs at the bottomof the shopping cart display page as follows:
out.println("<p> <p><strong><a href=\"" + response.encodeURL(request.getContextPath() + "/catalog") + "\">Continue Shopping</a> " + "<a href=\"" + response.encodeURL(request.getContextPath() + "/cashier") + "\">Check Out</a> " + "<a href=\"" + response.encodeURL(request.getContextPath() + "/showcart?Clear=clear") + "\">Clear Cart</a></strong>");
If cookies are turned off, the session is encoded in the Check Out URL aslows:
http://localhost:8080/bookstore1/cashier; jsessionid=c0o7fszeb1
If cookies are turned on, the URL is simply:
http://localhost:8080/bookstore1/cashier
Finalizing a ServletWhen a servlet container determines that a servlet should be removed fromvice (for example, when a container wants to reclaim memory resourceswhen it is being shut down) it calls thedestroy method of theServlet inter-face. In this method you release any resources the servlet is using and savpersistent state. The followingdestroy method releases the database object cated in theinit method described inInitializing a Servlet (page 145):
public void destroy() { bookDB = null;}
All of a servlet’s service methods should be complete when a servletremoved. The server tries to ensure this completion by calling thedestroy
164 JAVA SERVLET TECHNOLOGY
cific
ques
n
theized
hod. This
method only after all service requests have returned or after a server-spegrace period, whichever comes first.
If your servlet has potentially long-running service requests, use the technidescribed below to:
• Keep track of how many threads are currently running theservice method
• Provide a clean shutdown by having thedestroy method notify long-run-ning threads of the shutdown and wait for them to complete
• Have the long-running methods poll periodically to check for shutdowand, if necessary, stop working, clean up, and return
Tracking Service RequestsTo track service requests, include in your servlet class a field that countsnumber of service methods that are running. The field should have synchronaccess methods to increment, decrement, and return its value.
public ShutdownExample extends HttpServlet { private int serviceCounter = 0; ... //Access methods for serviceCounter protected synchronized void enteringServiceMethod() { serviceCounter++; } protected synchronized void leavingServiceMethod() { serviceCounter--; } protected synchronized int numServices() { return serviceCounter; }}
Theservice method should increment the service counter each time the metis entered and should decrement the counter each time the method returnsis one of the few times that yourHttpServlet subclass should override theser-vice method. The new method should callsuper.service to preserve all of theoriginalservice method’s functionality.
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException { enteringServiceMethod(); try { super.service(req, resp);
FINALIZING A SERVLET 165
dthisth-he
t-
} finally { leavingServiceMethod(); }}
Providing a Clean ShutdownTo ensure a clean shutdown, yourdestroy method should not release any shareresources until all of the service requests have completed. One part of doingis to check the service counter. Another part is to notify the long-running meods that it is time to shut down. For this notification another field is required. Tfield should have the usual access methods.
public ShutdownExample extends HttpServlet { private boolean shuttingDown; ... //Access methods for shuttingDown protected setShuttingDown(boolean flag) { shuttingDown = flag; } protected boolean isShuttingDown() { return shuttingDown; }}
An example of thedestroy method using these fields to provide a clean shudown follows:
public void destroy() { /* Check to see whether there are still service methods /* /* running, and if there are, tell them to stop. */ if (numServices() > 0) { setShuttingDown(true); }
/* Wait for the service methods to stop. */ while(numServices() > 0) { try { Thread.sleep(interval); } catch (InterruptedException e) { } }}
166 JAVA SERVLET TECHNOLOGY
odslue, if
Creating Polite Long-Running MethodsThe final step to provide a clean shutdown is to make any long-running methbehave politely. Methods that might run for a long time should check the vaof the field that notifies them of shutdowns and should interrupt their worknecessary.
public void doPost(...) { ... for(i = 0; ((i < lotsOfStuffToDo) && !isShuttingDown()); i++) { try { partOfLongRunningOperation(i); } catch (InterruptedException e) { ... } }}
ebjectsatu-y are:
s that
ners,
JavaServer Pages™Technology
by Stephanie Bodoff
JAVA SERVER Pages™ (JSP™) technology allows you to easily create wcontent that has both static and dynamic components. JSP technology proall the dynamic capabilities of Java Servlet technology but provides a more nral approach to creating static content. The main features of JSP technolog
• A language for developing JSP pages, which are text-based documentdescribe how to process a request and construct a response
• Constructs for accessing server-side objects
• Mechanisms for defining extensions to the JSP language
JSP technology also contains API that is used by developers of web contaibut this API is not covered in this chapter.
What is a JSP Page? 168The Example JSP Pages 171The Life Cycle of a JSP Page 173
Translation and Compilation 174Execution 175
Initializing and Finalizing a JSP Page 176Creating Static Content 178Creating Dynamic Content 179
Using Objects Within JSP Pages 179JSP Scripting Elements 181
Including Content in a JSP Page 185
167
168 JAVASERVER PAGES™ TECHNOLOGY
tem-ML,
.
ays
ticare
Transferring Control to Another Web Component 186Param Element 186
Including an Applet 186Extending the JSP Language 189
What is a JSP Page?A JSP page is a text-based document that contains two types of text: staticplate data, which can be expressed in any text-based format such as HTSVG, WML, and XML, and JSP elements, which construct dynamic content
The following web page is a form that allows you to select a locale and displthe date in a manner appropriate to the locale.
The source for this example is inexamples/src/web/date. The JSP pageindex.jsp used to create the form appears below; it is a typical mixture of staHTML markup and JSP elements. If you have developed web pages, youprobably familiar with the HTML document structure statements (<head>,<body>, and so on) and the HTML statements that create a form<form> and a
WHAT IS A JSP PAGE? 169
g
of
L
e
menu <select>. The highlighted lines in the example contain the followintypes of JSP constructs:
• Directives (<@page ... %>) import classes in thejava.util package andset the content type returned by the page.
• The jsp:useBean element creates an object containing a collectionlocales and initializes a variable that point to that object.
• Scriptlets (<% ... %> ) retrieve the value of thelocale request parameter,iterate over a collection of locale names, and conditionally insert HTMtext into the output.
• Expressions (<%= ... %>) insert the value of the locale name into thresponse.
• Thejsp:include element sends a request to another page (date.jsp) andincludes the response in the response from the calling page.
<%@ page import="java.util.*" %><%@ page contentType="text/html; charset=ISO-8859-5" %><html><head><title>Localized Dates</title></head><body bgcolor="white"><jsp:useBean id="locales" scope="application" class="MyLocales"/><form name="localeForm" action="index.jsp" method="post"><b>Locale:</b><select name=locale><% String selectedLocale = request.getParameter("locale"); Iterator i = locales.getLocaleNames().iterator(); while (i.hasNext()) { String locale = (String)i.next(); if (selectedLocale != null && selectedLocale.equals(locale)) {%>
<option selected><%=locale%></option><% } else {%>
<option><%=locale%></option><% } }%></select><input type="submit" name="Submit" value="Get Date">
170 JAVASERVER PAGES™ TECHNOLOGY
ton.
a-
,.
h.
oy
Getle.
</form><jsp:include page="date.jsp"/></body></html>
To build, deploy, and execute this JSP page:
1. Go toexamples/src and build the example by executingant date (seeHow to Build and Run the Examples (page xviii)).
2. Create a J2EE application calleddate.
a. Select File->New Application or the New Application button.
b. Enterdate.ear in the Application File Name field.
c. Click OK.
3. Add thedate web component to thedate application.
a. Select File->New Web Component or the New Web Component but
b. Select the date application from the Create new WAR File in Appliction combo box.
c. Enterdate in the WAR Display Name field.
d. Click Add.
e. Navigate to examples/build/web/date. Select index.jsp, date.jspMyDate.class and MyLocales.class and click Add, then click Finish
f. Click Next.
g. Click JSP in the Web Component radio box, then click Next.
h. Select index.jsp from the JSP Filename combo box. Typedate in theWeb Component Display Name text area. Click Next and click Finis
4. Deploy the application. Select Tools->Deploy Application or the DeplApplication Button. In the deploy wizard, set the context root todate.
5. Invoke the URLhttp://<host>:8000/date in a browser.
You will see a combo box whose entries are locales. Select a locale and clickDate. You will see the date expressed in a manner appropriate for that loca
THE EXAMPLE JSP PAGES 171
P
ata-
sign
ss thempo-
goesan isata-ause
The Example JSP PagesTo illustrate JSP technology, this chapter rewrites each servlet in theDuke’s
Bookstore application introduced inTheExampleServlets (page 135) as a JSpage:
The source for the application is located inexamples/src/web/bookstore2.The data for the bookstore application is still maintained in a Cloudscape dbase. However, two changes are made to the database helper objectdata-
base.BookDB:
• The helper object is rewritten to conform to JavaBeans component depatterns as described inJavaBeans™ Components in JSP™Pages (page 191). This change is made so that JSP pages can accehelper object using JSP language elements specific to JavaBeans conents.
• Instead of accessing the bookstore database directly, the helper objectthrough an enterprise bean. The advantage of using an enterprise bethat the helper object is no longer responsible for connecting to the dbase; this job is taken over by the enterprise bean. Furthermore, bec
Table 16 Duke’s Bookstore Example JSP Pages
Function JSP Page
Enter the bookstore bookstore.jsp
Create the bookstore banner banner.jsp
Browse the books offered for sale catalog.jsp
Put a book in a shopping cart catalog.jsp andbookdetails.jsp
Get detailed information on a specific book bookdetails.jsp
Display the shopping cart showcart.jsp
Remove one or more books from the shopping cartshowcart.jsp
Buy the books in the shopping cart cashier.jsp
Receive an acknowledgement for the purchase receipt.jsp
172 JAVASERVER PAGES™ TECHNOLOGY
nter-vant
C
igital
n.
ton.
lick
the EJB container maintains the pool of database connections, an eprise bean can get a connection quicker than the helper object. The releinterfaces and classes for the enterprise bean are thedatabase.BookDBE-
JBHome home interface,database.BookDBEJB remote interface, and thedatabase.BookDBEJB implementation class, which contains all the JDBcalls to the database.
Finally, this version of the example uses an applet to generate a dynamic dclock in the banner. SeeIncludinganApplet (page 186) for a description of theJSP element that generates HTML for downloading the applet.
To build, deploy, and run the example:
1. Go toexamples/src and build the example by runningant bookstore2.
2. Start the Cloudscape database by executingcloudscape -start.
3. If you have not already created the bookstore database, runant cre-
ate-web-db.
4. Start thej2ee server.
5. Startdeploytool.
6. Create a J2EE application calledbookstore2.
a. Select File->New Application or the New Application button.
b. Enterbookstore2.ear in the Application File Name field.
c. Click OK.
7. Add thebookstore2 WAR to thebookstore2 application.
a. Select File->Add to Application->Web WAR or the Web WAR butto
b. In the Add Web WAR dialog, navigate toexamples/build/web/bookstore2. Select bookstore2.war. Click Add Web WAR.
8. Add theBookDBEJB enterprise bean to the application.
a. Select File->New Enterprise Bean or the New Enterprise Bean but
b. Select bookstore2 from Enterprise Bean will Go In combo box.
c. TypeBookDBEJB in the JAR Display Name field.
d. Click Add to add the content files. Navigate to theexamples/build/
web/ejb directory and add the database and exception packages. CNext.
e. Chose Session and Stateless for the Bean Type.
f. Select BookDBEJBImpl for Enterprise Bean Class.
g. Select BookDBEJBHome for Home Interface.
THE LIFE CYCLE OF A JSP PAGE 173
oy
.
of thed byunc-
h. Select BookDBEJB for Remote Interface.
i. Enter BookDBEJB for Enterprise Bean Name.
j. TypeBookDBEJB in the JNDI Name field next to theBookDB component.
9. Add a resource reference for the Cloudscape database.
a. Select the BookDBEJB enterprise bean.
b. Select the Resource Ref’s tab.
c. Click Add.
d. Select javax.sql.DataSource from the Type column
e. Enterjdbc/BookDB in the Coded Name field.
f. Enterjdbc/Cloudscape in the JNDI Name field.
10.Add a reference to the enterprise beanBookDBEJB.
a. Select the bookstore2 WAR.
b. Select the EJB Ref’s tab.
c. Click Add.
d. Enterejb/BookDBEJB in the Coded Name field.
e. Enter Session in the Type field.
f. EnterBookDBEJBHome in the Home field.
g. EnterBookDBEJB in the Remote field.
h. EnterBookDBEJB in the JNDI Name field.
11.Deploy the application. Select Tools->Deploy Application or the DeplApplication Button. Click Next twice. TypeBookDBEJB in the Applica-tion->JNDI Name field andbookstore2 for the context root. Click Nextand Finish.
12.Open the bookstore URLhttp://<host>:8000/bookstore2/enter.
SeeTroubleshooting (page 138) for help with diagnosing common problems
The Life Cycle of a JSP PageA JSP page services requests as a servlet. Thus, the life cycle and manycapabilities of JSP pages (in particular the dynamic aspects) are determineJava Servlet technology and much of the discussion in this chapter refers to ftions described inJava Servlet Technology (page 133).
174 JAVASERVER PAGES™ TECHNOLOGY
t thatis, it
devel-pro-
ently.that
exe-
e
in
source
d:
onlyhilemal-
e a
to a
When a request is mapped to a JSP page, it is handled by a special servlefirst checks whether the JSP page’s servlet is older than the JSP page. If ittranslates the JSP page into a servlet class and compiles the class. Duringopment, one of the advantages of JSP pages over servlets is that the “build”cess is performed automatically.
Translation and CompilationDuring the translation phase each type of data in a JSP page is treated differTemplate data is transformed into code that will emit the data into the streamreturns data to the client. JSP elements are treated as follows:
• Directives are used to control how the web container translates andcutes the JSP page.
• Scripting elements are inserted into the JSP page’s servlet class. SeJSPScripting Elements (page 181) for details.
• Elements of the form<jsp:XXX ... /> are converted into method calls toJavaBeans components or invocations of the Java Servlet API.
For a JSP page namedpageName, the source for a JSP page’s servlet is keptthe file:
J2EE_HOME/repository/host/web/host_port%2Fcontext root/_0002fpageName_0002ejsppageName_jsp_v.java
Each time you change a JSP page, the web container generates a new Javafile and increments the version numberv.
For example, the source for the index page (namedindex.jsp) for the date
localization example discussed at the beginning the chapter would be name
J2EE_HOME/repository/host/web/host_8000%2Fdate/_0002findex_0002ejspindex_jsp_v.java
Both the translation and compilation phases can yield errors that areobserved when the page is requested for the first time. If an error occurs wthe page is being translated (for example, if the translator encounters aformed JSP element), the server will return aParseException and the servletclass source file will be empty or incomplete. The last incomplete line will givpointer to the incorrect JSP element.
If an error occurs while the JSP page is being compiled (for example, duesyntax error in a scriptlet), the server will return aJasperException and a mes-
THE LIFE CYCLE OF A JSP PAGE 175
error
or the
ct.
ssedtasks
mati-ge
entriateuffermore
y thaturs,
sage that includes the name of the JSP page’s servlet and the line where theoccurred.
Once the page has been translated and compiled, the JSP page’s servlet fmost part follows the servlet life cycle described inServlet LifeCycle (page 139):
1. If an instance of the JSP page’s servlet does not exist, the container:
a. Loads the JSP page’s servlet class
b. Instantiates an instance of the servlet class
c. Initializes the servlet instance by calling thejspInit method
2. Invokes the_jspService method, passing a request and response obje
If the container needs to remove the JSP page’s servlet, it calls thejspDestroy
method.
ExecutionYou can control various JSP page execution parameters usingpage directives.The directives that pertain to buffering output and handling errors are discuhere. Other directives are covered in the context of specific page authoringthroughout the chapter.
Buffering
When a JSP page is executed, output written to the response object is autocally buffered. You can adjust the size of the buffer with the following padirective:
<%@ page buffer="none|xxxkb" %>
A larger buffer allows more content to be written before anything is actually sback to the client, thus providing the JSP page with more time to set appropstatus codes and headers or forward to another web resource. A smaller bdecreases server memory load and allows the client to start receiving dataquickly.
Handling Errors
Any number of exceptions can arise when a JSP page is executed. To specifthe web container should forward control to an error page if an exception occinclude the followingpage directive at the beginning of your JSP page:
176 JAVASERVER PAGES™ TECHNOLOGY
e
pos-
rkes
rsis-ime
g
<%@ page errorPage="file_name" %>
TheDuke’s Bookstore application pageinitdestroy.jsp contains the direc-tive
<%@ page errorPage="errorpage.jsp"%>
The beginning oferrorpage.jsp indicates that it is serving as an error pagwith the following page directive:
<%@ page isErrorPage="true|false" %>
This directive makes the exception object (of typejavax.servlet.jsp.JspEx-
ception) available to the error page, so that you can retrieve, interpret, andsibly display information about the cause of the exception in the error page.
Note: You can also define error pages for the WAR that contains a JSP page. If erropages are defined for both the WAR and a JSP page, the JSP page’s error page taprecedence.
Initializing and Finalizing a JSP PageYou can customize the initialization process to allow the JSP page to read petent configuration data, initialize resources, and perform any other one-tactivities by overriding thejspInit method of theJspPage interface. Yourelease resources using thejspDestroy method. The methods are defined usinJSP declarations, discussed inDeclarations (page 182).
The bookstore example pageinitdestroy.jsp defines thejspInit method toretrieve or create a JavaBeans componentdatabase.BookDB that represents thebookstore database:
private BookDB bookDB;public void jspInit() { bookDB = (BookDB)getServletContext(). getAttribute("bookDB");
if (bookDB == null) { try { bookDB = new BookDB(); getServletContext().setAttribute(
INITIALIZING AND FINALIZING A JSP PAGE 177
the
ancen. The
"bookDB", bookDB); } catch (Exception ex) { System.out.println(ex.getMessage()); } }}
and thejspDestroy method to remove the JavaBeans component and releaseBookDB variable.
public void jspDestroy() { try { bookDB.remove(); } catch (Exception ex) { System.out.println(ex.getMessage()); } getServletContext().removeAttribute("bookDB"); bookDB = null;}
The implementation of the database bean follows. The bean has two instvariables: the current book and a reference to the database enterprise beareference is created using the techniques described inGetting Started (page 43).
public class BookDB { String bookId = "0"; private BookDBEJB database = null;
public BookDB () throws Exception { try { InitialContext ic = new InitialContext(); Object objRef = ic.lookup( "java:comp/env/ejb/BookDBEJB"); BookDBEJBHome home = (BookDBEJBHome)PortableRemoteObject. narrow(objRef, database.BookDBEJBHome.class); database = home.create(); } catch (RemoteException ex) { throw new Exception( "Couldn't create database bean."); } catch (CreateException ex) { throw new Exception( "Couldn't create database bean."); } catch (NamingException ex) { throw new Exception("Unable to lookup home: "+ "java:comp/env/ejb/BookDBEJB.");
178 JAVASERVER PAGES™ TECHNOLOGY
initial-ervletpur-ontext
tion.
eat-ed inis
fin thee:
} public void remove () throws Exception { try { database.remove(); database = null; } catch (RemoteException ex) { throw new Exception( "Error while removing database bean."); } catch (EJBException ex) { throw new Exception( "Error while removing database bean."); } catch (RemoveException ex) { throw new Exception( "Error while removing database bean."); } } public void setBookId(String bookId) { this.bookId = bookId; } ...}
Since the database bean is shared between all the JSP pages, it should beized when the application is started instead of in each JSP page. Java Stechnology provides application life cycle events and listener classes for thispose. As an exercise, you can move the code that manages the bean to a clistener class. SeeMonitoring ServletLife CycleEvents (page 140) for the con-text listener that initializes the Java Servlet version of the bookstore applica
Creating Static ContentYou create static content in a JSP page by simply writing it as if you were cring a page that consists only of that content. Static content can be expressany text-based format such as HTML, WML, and XML. The default formatHTML. If you want to use a format other than HTML you include apage direc-tive with thecontentType attribute set to the format type at the beginning oyour JSP page. For example, if you want a page to contain data expressedwireless markup language (WML), you need to include the following directiv
<%@ page contentType="text/vnd.wap.wml"%>
A registry of content type names is kept by IANA at:
ftp://ftp.isi.edu/in-notes/iana/assignments/media-types
CREATING DYNAMIC CONTENT 179
jects
eansome
bjects.
tedd byed atcit
Creating Dynamic ContentYou create dynamic content by accessing Java programming language obfrom within scripting elements.
Using Objects Within JSP PagesYou can access a variety of objects, including enterprise beans and JavaBcomponents, within a JSP page. JSP technology automatically makes sobjects available and you can also create and access application-specific o
Implicit Objects
Implicit objects are created by the web container and contain information relato a particular request, page, or application. Many of the objects are definethe Java Servlet technology underlying JSP technology and are discusslength inJava ServletTechnology (page 133). Table 17 summarizes the impliobjects.
Table 17 Implicit Objects
Variable Class Description
applicationjavax.servlet.ServletContext
The context for the JSP page’s servlet and any webcomponents contained in the same application. SeeAccessing the Web Context (page 159).
configjavax.servlet.ServletConfig
Initialization information for the JSP page’s servlet.
exceptionjava.lang.Throwable
Accessible only from an error page. SeeHan-dling Errors(page 175).
outjavax.servlet.jsp.JspWriter
The output stream.
pagejava.lang.Object
The instance of the JSP page’s servlet processingthe current request. Not typically used by JSP pageauthors.
180 JAVASERVER PAGES™ TECHNOLOGY
thatdevel-data-ithin a
ted in
ed in
d
ed JSP
om-ans
I
Application-Specific Objects
When possible, application behavior should be encapsulated in objects sopage designers can focus on presentation issues. Objects can be created byopers who are proficient in the Java programming language and accessingbases and other services. There are four ways to create and use objects wJSP page:
• Instance and class variables of the JSP page’s servlet class are creadeclarations and accessed inscriptlets andexpressions.
• Local variables of the JSP page’s servlet class are created and usscriptlets andexpressions.
• Attributes of scope objects (seeScopeObjects (page 142)) are created anused inscriptlets andexpressions.
• JavaBeans components can be created and accessed using streamlinelements. These elements are discussed in the chapterJavaBeans™Com-ponentsin JSP™Pages (page 191). You can also create a JavaBeans cponent in a declaration or scriptlet and invoke the methods of a JavaBecomponent in a scriptlet or expression.
Declarations, scriptlets, and expressions are described inJSP ScriptingElements (page 181).
pageContextjavax.servlet.jsp.PageContext
The context for the JSP page. Provides a single APto manage the various scoped attributes describedin Sharing Information(page 142).This API is used extensively when implementingtag handlers (seeTag Handlers(page 209)).
requestsubtype ofjavax.servlet.ServletRequest
The request triggering the execution of the JSPpage. SeeGetting Information FromRequests(page 146).
responsesubtype ofjavax.servlet.ServletResponse
The response to be returned to the client. Not typi-cally used by JSP page authors.
sessionjavax.servlet.http.HttpSession
The session object for the client. SeeAccessingthe Web Context (page 159).
Table 17 Implicit Objects (Continued)
Variable Class Description
CREATING DYNAMIC CONTENT 181
un asatch
h
aredlara-
heto be
n or
ds, andepa-ntent,thated in
call
nts insed bya
Shared Objects
The conditions affecting concurrent access to shared objects described inShar-ing Information (page 142) apply to objects accessed from JSP pages that rmultithreaded servlets. You can indicate how a web container should dispmultiple client requests with the followingpage directive:
<%@ page isThreadSafe="true|false" %>
WhenisThreadSafe is set totrue, the web container may choose to dispatcmultiple concurrent client requests to the JSP page. This is thedefaultsetting. Ifusingtrue, you must ensure that you properly synchronize access to any shobjects defined at the page level. This includes objects created within dections, JavaBeans components with page scope, and attributes of thepage scopeobject.
If isThreadSafe is set tofalse, requests are dispatched one at a time, in torder they were received and access to page level objects does not havecontrolled. However, you still must ensure that access to attributes of theappli-
cation or session scope objects and JavaBeans components with applicatiosession scope is properly synchronized.
JSP Scripting ElementsJSP scripting elements are used to create and access objects, define methomanage the flow of control. Since one of the goals of JSP technology is to srate static template data from the code needed to dynamically generate covery sparing use of JSP scripting is recommended. Much of the workrequires the use of scripts can be eliminated by using custom tags, describExtending the JSP Language (page 189).
JSP technology allows a container to support any scripting language that canJava objects. If you wish to use a scripting language other than the default,java,you must specify it in apage directive at the beginning of a JSP page:
<%@ page language="scripting language" %>
Since scripting elements are converted to programming language statemethe JSP page’s servlet class, you must declare any classes and packages ua JSP page. If the page language isjava, you declare that a JSP page will useclass or package with thepage directive:
<%@ page import="packagename.*, fully_qualified_classname" %>
182 JAVASERVER PAGES™ TECHNOLOGY
d
lan-
andt class.
an-
arviceated
mct to
For example, bookstore example pageshowcart.jsp imports the classes needeto implement the shopping cart with the following directive:
<%@ page import="java.util.*, cart.*" %>
Declarations
A declaration is used to declare variables and methods in a page’s scriptingguage. The syntax for a declaration is:
<%! scripting language declaration %>
When the scripting language is the Java programming language, variablesmethods in JSP declarations become declarations in the JSP page’s servle
The bookstore example pageinitdestroy.jsp defines an instance variablenamedbookDB and the initialization and finalization methodsjspInit andjsp-Destroy discussed earlier in a declaration:
<%! private BookDB bookDB;
public void jspInit() { ... } public void jspDestroy() { ... }%>
Scriptlets
A scriptlet is used to contain any code fragment that is valid for the scripting lguage used in a page. The syntax for a scriptlet is:
<% scripting language statements%>
When the scripting language is set tojava, a scriptlet is transformed into a Javprogramming language statement fragment and is inserted into the semethod of the JSP page’s servlet. A programming language variable crewithin a scriptlet is accessible from anywhere within the JSP page.
The JSP pageshowcart.jsp contains a scriptlet that retrieves an iterator frothe collection of items maintained by a shopping cart and sets up a constru
CREATING DYNAMIC CONTENT 183
rop-theat
loop through all the items in the cart. Inside the loop, the JSP page extracts perties of the book objects and formats them using HTML markup. Sincewhile loop opens a block, the HTML markup is followed by a scriptlet thcloses the block.
<% Iterator i = cart.getItems().iterator(); while (i.hasNext()) { ShoppingCartItem item = (ShoppingCartItem)i.next(); BookDetails bd = (BookDetails)item.getItem();%>
<tr> <td align="right" bgcolor="#ffffff"> <%=item.getQuantity()%> </td> <td bgcolor="#ffffaa"> <strong><a href=" <%=request.getContextPath()%>/bookdetails?bookId= <%=bd.getBookId()%>"><%=bd.getTitle()%></a></strong> </td> ...<% // End of while }%>
184 JAVASERVER PAGES™ TECHNOLOGY
sion,the
rans-
ame
The output appears below:
Expressions
A JSP expression is used to insert the value of a scripting language expresconverted into a string, into the data stream returned to the client. Whenscripting language is the Java programming language, an expression is tformed into a statement that converts the value of the expression into aString
object and inserts it into the implicitout object.
The syntax for an expression is:
<%= scripting language expression %>
Note that a semicolon is not allowed within a JSP expression, even if the sexpression has a semicolon when you use it within a scriptlet.
The following scriptlet retrieves the number of items in a shopping cart:
<% // Print a summary of the shopping cart int num = cart.getNumberOfItems(); if (num > 0) {%>
INCLUDING CONTENT IN A JSP PAGE 185
JSP
file,ould-ge.
bean
ore
hetic,st isresult
Expressions are then used to insert the value ofnum into the output stream anddetermine the appropriate string to include after the number:
<font size="+2">You have <%= num %> <%= (num==1 ? " item" : " items") %> in your shopping cart.</font>
Including Content in a JSP PageThere are two mechanisms for including content from another source in apage: theinclude directive and the jsp:include element.
Theinclude directive is processed when the JSP page istranslatedinto a servletclass. The effect of the directive to the insert the text contained in anothereither static content or another JSP page, in the including JSP page. You wprobably use theinclude directive to include banner content, copyright information, or any chunk of content that you might want to reuse in another paThe syntax for theinclude directive is:
<%@ include file="filename" %>
For example, all the bookstore application pages include the filebanner.jsp
containing the banner content with the following directive:
<%@ include file="banner.jsp" %>
In addition, the pagesbookstore.jsp, bookdetails.jsp, catalog.jsp, andshowcart.jsp include JSP elements that create and destroy a databasewith the element:
<%@ include file="initdestroy.jsp" %>
Because you must statically put aninclude directive in each file that reuses theresource referenced by the directive, this approach has its limitations. For a mflexible approach to building pages out of content chunks, seeA TemplateTagLibrary (page 227).
The include element is processed when a JSP page isexecuted. Theinclude
action allows you to include either a static or dynamic file in a JSP file. Tresults of including static and dynamic files are quite different. If the file is staits content is inserted into the calling JSP file. If the file is dynamic, the requesent to the included JSP page, the included page is executed, and then the
186 JAVASERVER PAGES™ TECHNOLOGY
the
theent:
JSPd inis
isge,
g thepri-
ent
is included in the response from the calling JSP page. The syntax forjsp:include element is:
<jsp:include page="includedPage" />
The date application introduced at the beginning of this chapter includespage that generates the display of the localized date with the following elem
<jsp:include page="date.jsp"/>
Transferring Control to Another WebComponent
The mechanism for transferring control to another web component from apage uses the functionality provided by the Java Servlet API as describeTransferringa Control to AnotherWeb Component (page 158). You access thfunctionality from a JSP page with thejsp:forward element:
<jsp:forward page="/main.jsp" />
Note that if any data has already been returned to a client, thejsp:forward ele-ment will fail with anIllegalStateException.
Param ElementWhen aninclude or forward element is invoked, the original request objectprovided to the target page. If you wish to provide additional data to that payou can append parameters to the request object with theparam element:
<jsp:include page="..." > <jsp:param param1="value1" ... /></jsp:include>
Including an AppletYou can include an applet or JavaBeans component in a JSP page usinjsp:plugin element. This element generates HTML that contains the approate client browser dependent constructs (<object> or <embed>) that will result inthe download of the Java Plugin software (if required) and client-side compon
INCLUDING AN APPLET 187
the
on-f the
po-nt
nd orly a
and subsequent execution of an client-side component. The syntax forjsp:plugin element follows:
<jsp:plugin type="bean|applet" code="objectCode" codebase="objectCodebase" { align="alignment" } { archive="archiveList" } { height="height" } { hspace="hspace" } { jreversion="jreversion" } { name="componentName" } { vspace="vspace" } { width="width" } { nspluginurl="url" } { iepluginurl="url" } > { <jsp:params> { <jsp:param name="paramName" value= paramValue" /> }+ </jsp:params> } { <jsp:fallback> arbitrary_text </jsp:fallback> }</jsp:plugin>
Thejsp:plugin tag is replaced by either an<object> or <embed> tag, as appro-priate for the requesting client. The attributes of the jsp:plugin tag provide cfiguration data for the presentation of the element as well as the version oplugin required. Thenspluginurl andiepluginurl attributes specify the URLwhere the plugin can be downloaded.
Thejsp:param elements indicate parameters to the applet or JavaBeans comnent. Thejsp:fallback element indicates the content to be used by the cliebrowser if the plugin cannot be started (either because<object> or <embed> isnot supported by the client or due to some other problem).
If the plugin can start but the applet or JavaBeans component cannot be foustarted, a plugin-specific message will be presented to the user, most likepopup window reporting aClassNotFoundException.
188 JAVASERVER PAGES™ TECHNOLOGY
a
The Duke’s Bookstore pagebanner.jsp that creates the banner displaysdynamic digitial clock generated byDigitalClock:Thejsp:plugin element used to download the applet follows:
<jsp:plugin type="applet" code="DigitalClock.class" codebase="/bookstore2" jreversion="1.3" align="center" height="25" width="300" nspluginurl="http://java.sun.com/products/plugin/1.3.0_01/plugin-install.html" iepluginurl="http://java.sun.com/products/plugin/1.3.0_01/jinstall-130_01-win32.cab#Version=1,3,0,1" > <jsp:params> <jsp:param name="language"value="<%=request.getLocale().getLanguage()%>" /> <jsp:param name="country"value="<%=request.getLocale().getCountry()%>" /> <jsp:param name="bgcolor" value="FFFFFF" /> <jsp:param name="fgcolor" value="CC0066" /> </jsp:params>
EXTENDING THE JSP LANGUAGE 189
singcon-
aw-lt to
areenefits
ts of
ting
<jsp:fallback> <p>Unable to start plugin.</p> </jsp:fallback></jsp:plugin>
Extending the JSP LanguageYou can perform a wide variety of dynamic processing tasks including accesdatabases, using enterprise services such as email and directories, and flowtrol with JavaBeans components in conjunction with scriptlets. One of the drbacks of scriptlets however, is that they tend to make JSP pages more difficumaintain. Alternatively, JSP technology provides a mechanism, calledcustomtags, that allows you to encapsulate dynamic functionality in objects thataccessed through extensions to the JSP language. Custom tags bring the bof another type of componentization to JSP pages.
For example, recall the scriptlet used to loop through and display the contentheDuke’s Bookstore shopping cart:
<% Iterator i = cart.getItems().iterator(); while (i.hasNext()) { ShoppingCartItem item = (ShoppingCartItem)i.next(); ...%> <tr> <td align="right" bgcolor="#ffffff"> <%=item.getQuantity()%> </td> ...<% }%>
An iterate custom tag eliminates the code logic and manages the scripvariableitem that references elements in the shopping cart:
<logic:iterate id="item" collection="<%=cart.getItems()%>" <tr> <td align="right" bgcolor="#ffffff">
190 JAVASERVER PAGES™ TECHNOLOGY
amely
<%=item.getQuantity()%> </td> ...</logic:iterate>
Custom tags are packaged and distributed in a unit called atag library. Thesyntax of custom tags is the same as that used for the JSP elements, n<prefix:tag>, but for custom tags, the prefix is defined by theuserof the taglibrary and the tag is defined by thetag developer. Custom Tags in JSP™Pages (page 199) explains how to use and develop custom tags.
com-con-
nentsd gettiong Java-ava-
JavaBeans™Components in JSP™
Pagesby Stephanie Bodoff
JAVA BEANS components are Java classes that can be easily reused andposed together into applications. Any Java class that follows certain designventions can be a JavaBeans component.
JavaServer Pages™ technology directly supports using JavaBeans compowith JSP language elements. You can easily create and initialize beans anand set the values of their properties. This chapter provides basic informaabout JavaBeans components and the JSP language elements for accessinBeans components in your JSP pages. For further information about the JBeans component model seehttp://java.sun.com/products/javabeans.
JavaBeans Component Design Conventions 190Why Use a JavaBeans Component? 191Creating and Using a JavaBeans Component 192Setting JavaBeans Component Properties 192Retrieving JavaBeans Component Properties 195
191
192 JAVABEANS™ COMPONENTS IN JSP™ PAGES
f the
ans
able;to
orm:
:
con-
ntn-
tive
ce
JavaBeans Component DesignConventions
JavaBeans component design conventions govern the public attributes oclass, which are also known as itsproperties, and the public methods that giveaccess to the properties.
A JavaBeans component property can be:
• Read/write, read-only, or write-only.
• Simple, which means it contains a single value, or indexed, which meit represents an array of values.
There is no requirement that a property be implemented by an instance varithe property must simply be accessible using public methods that conformcertain conventions:
• For each readable property, the bean must have a method of the fPropertyClass getProperty() { ... }
• For each writable property, the bean must have a method of the formsetProperty(PropertyClass pc) { ... }
In addition to the property methods, a JavaBeans component must define astructor that takes no parameters.
The Duke’s Bookstore application JSP pagesenter.jsp, bookdetails.jsp,catalog.jsp, showcart.jsp use thedatabase.BookDB and database.Book-
Details JavaBeans components.BookDB provides a JavaBeans component froend to the enterprise beanBookDBEJB. Both beans are used extensively by beaoriented custom tags (seeTagsThatDefineScriptingVariables (page 218)). TheJSP pagesshowcart.jsp andcashier.jsp usecart.ShoppingCart to repre-sent a user’s shopping cart.
The JSP pagescatalog.jsp, showcart.jsp, and cashier.jsp use theutil.Currency JavaBeans component to format currency in a locale-sensimanner. The bean has two writable properties,locale andamount, and one read-able property,format. Theformat property does not correspond to any instanvariable, but returns a function of thelocale andamount properties.
public class Currency { private Locale locale; private double amount; public Currency() { locale = null;
WHY USE A JAVABEANS COMPONENT? 193
objectore
s can
amount = 0.0; } public void setLocale(Locale l) { locale = l; } public void setAmount(double a) { amount = a; } public String getFormat() { NumberFormat nf = NumberFormat.getCurrencyInstance(locale); return nf.format(amount); }}
Why Use a JavaBeans Component?A JSP page can create and use any type of Java programming languagewithin a declaration or scriptlet. The following scriptlet creates the bookstshopping cart and stores it as a session attribute:
<% ShoppingCart cart = (ShoppingCart)session. getAttribute("cart"); // If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.setAttribute("cart", cart); }%>
If the shopping cart object conforms to JavaBeans conventions, JSP pageuse JSP elements to create and access the object. For example, theDuke’s
Bookstore pagesbookdetails.jsp, catalog.jsp, andshowcart.jsp replacethe scriptlet with the much more concise JSPuseBean element:
<jsp:useBean id="cart" class="cart.ShoppingCart" scope="session"/>
194 JAVABEANS™ COMPONENTS IN JSP™ PAGES
r one
red
ean
.
ut
:
Creating and Using a JavaBeansComponent
You declare that your JSP page will use a JavaBeans component using eitheof the following formats:
<jsp:useBean id="beanName" class="fully_qualified_classname" scope="scope"/>
or
<jsp:useBean id="beanName" class="fully_qualified_classname" scope="scope"> <jsp:setProperty .../></jsp:useBean>
The second format is used when you want to includejsp:setProperty state-ments, described in the next section, for initializing bean properties.
The jsp:useBean element declares that the page will use a bean that is stowithin and accessible from the specified scope, which can beapplication,session, request or page. If no such bean exists, the statement creates the band stores it as an attribute of the scope object (seeScopeObjects (page 142)).The value of theid attribute determines thenameof the bean in the scope andthe identifier used to reference the bean in other JSP elements and scriptlets
The following element creates an instance ofCurrency if none exists, stores it asan attribute of theapplication object, and makes the bean available throughothe application by the identifiercurrency:
<jsp:useBean id="currency" class="util.Currency" scope="application"/>
Setting JavaBeans Component PropertiesThere are two ways to set JavaBeans component properties in a JSP page
• With thejsp:setProperty element
• With a scriptlet:<%= beanName.setPropName(value) %>
SETTING JAVABEANS COMPONENT PROPERTIES 195
p-ava-
d incon-
ionst be
The syntax of thejsp:setProperty element depends on the source of the proerty value. Table 18 summarizes the various ways to set a property of a JBeans component using thejsp:setProperty element:
A property set from a constant or request parameter must have a type listeTable 19. Since both a constant and request parameter are strings, the webtainer automatically converts the value to the property’s type; the conversapplied is shown in the table. The value assigned to an indexed property muan array, and the rules just described apply to the elements.
Table 18 Setting JavaBeans Component Properties
Value Source Element Syntax
String constant<jsp:setProperty name="beanName" property="propName" value="string constant">
Request parameter<jsp:setProperty name="beanName" property="propName" param="paramName"/>
Request parameter namematches bean property
<jsp:setProperty name="beanName" property="propName"/>
<jsp:setProperty name="beanName" property="*"/>
Expression<jsp:setProperty name="beanName" property="propName" value="<%= expression%>"/>
1.beanName must be the same as that specified for theid attribute in auseBean ele-ment.2. There must be asetPropName method in the JavaBeans component.3.paramName must be a request parameter name.
Table 19 Valid Value Assignments
Property Type Conversion on String Value
boolean or Boolean As indicated injava.lang.Boolean.valueOf(String)
byte or Byte As indicated injava.lang.Byte.valueOf(String)
196 JAVABEANS™ COMPONENTS IN JSP™ PAGES
is amof a
thef the
. For
sted
You can use a runtime expression to set the value of a property whose typecompound Java programming language type. Recall froExpressions (page 184) that a JSP expression is used to insert the valuescripting language expression, converted into aString, into the stream returnedto the client. When used within asetProperty element, an expression simplyreturns its value;no automatic conversion is performed. As a consequence,type returned from an expression must match or be castable to the type oproperty.
TheDuke’s Bookstore application demonstrates how to use thesetProperty
element and a scriptlet to set the current book for the database helper beanexample,bookstore3/bookdetails.jsp uses the form:
<jsp:setProperty name="bookDB" property="bookId"/>
while bookstore2/bookdetails.jsp uses the form:
<% bookDB.setBookId(bookId) %>
The following fragments from the pagebookstore3/showcart.jsp illustratehow to initialize a currency bean with aLocale object and amount determinedby evaluating request-time expressions. Because the first initialization is nein auseBean element, it is only executed when the bean is created.
<jsp:useBean id="currency" class="util.Currency" scope="application"> <jsp:setProperty name="currency" property="locale" value="<%= request.getLocale() %>"/></jsp:useBean>
char or Character As indicated injava.lang.Character.valueOf(String)
double or Double As indicated injava.lang.Double.valueOf(String)
int or Integer As indicated injava.lang.Integer.valueOf(String)
float or Float As indicated injava.lang.Float.valueOf(String)
long or Long As indicated injava.lang.Long.valueOf(String)
Table 19 Valid Value Assignments (Continued)
Property Type Conversion on String Value
RETRIEVING JAVABEANS COMPONENT PROPERTIES 197
of the
ing
n hasthe
tothe
an
<jsp:setProperty name="currency" property="amount" value="<%=cart.getTotal()%>"/>
Retrieving JavaBeans ComponentProperties
There are several ways to retrieve JavaBeans component properties. Twomethods convert the value of the property into aString and insert the value intothe current implicitout object: thejsp:getProperty element and an expres-sion:
• <jsp:getProperty name="beanName" property="propName"/>
• <%= beanName.getPropName() %>
For both methods,beanName must be the same as that specified for theid
attribute in auseBean element and there must be agetPropName method in theJavaBeans component.
If you need to retrieve the value of a property without converting it and insertit into the out object, you must use a scriptlet:
<% Object o = beanName.getPropName(); %>
Note the differences between the expression and the scriptlet; the expressioan ‘=’ after the opening ‘%’ and does not terminate with a semicolon, as doesscriptlet.
The Duke’s Bookstore application demonstrates how to use both formsretrieve the formatted currency from the currency bean and insert it intopage. For example,bookstore3/showcart.jsp uses the form:
<jsp:getProperty name="currency" property="format"/>
while bookstore2/showcart.jsp uses the form:
<%= currency.getFormat() %>
The Duke’s Bookstore application pagebookstore2/showcart.jsp uses thefollowing scriptlet to retrieve the number of books from the shopping cart beand open a conditional insertion of text into the output stream:
198 JAVABEANS™ COMPONENTS IN JSP™ PAGES
tagsndple,
those
ed bytedervlet
<% // Print a summary of the shopping cart int num = cart.getNumberOfItems(); if (num > 0) {%>
Although scriptlets are very useful for dynamic processing, using custom(seeCustomTagsin JSP™Pages (page 199)) to access object properties aperform flow control is considered to be a better approach. For exambookstore3/showcart.jsp replaces the scriptlet with the following customtags:
<bean:define id="num" name="cart" property="numberOfItems" /><logic:greaterThan name="num" value="0" >
Figure 15 summarizes where various types of objects are stored and howobjects can be accessed from a JSP page. Objects created by thejsp:useBean
tag are stored as attributes of the scope objects and can be accessjsp:[get|set]Property tags and in scriptlets and expressions. Objects creain declarations and scriptlets are stored as variables of the JSP page’s sclass and can be accessed in scriptlets and expressions.
Figure 15 Accessing Objects From a JSP Page
Session attribute1 attribute2
Web context attribute1 attribute2
Request attribute1 attribute2
Page context attribute1 attribute2
jsp:useBeanjsp:getPropertyjsp:setProperty
JSP pageservlet class object1 object2
<%! declaration %><% scriptlet %><%= expression %>
entsinte-
ating
ple-
tionsrprise
cre-andsign-hoween
cap-plica-
om-ly-
Custom Tags in JSP™Pages
by Stephanie Bodoff
THE standard JSP tags for invoking operations on JavaBeans™ componand performing request dispatching simplify JSP page development and manance. In addition, JSP technology provides a mechanism for encapsulother types of dynamic functionality incustom tags, which are extensions to theJSP language. Custom tags are usually distributed in the form of atag library,which defines a set of related custom tags and contains the objects that imment the tags.
Some examples of tasks that can be performed by custom tags include operaon implicit objects, form processing, accessing databases and other enteservices such as email and directories, and flow control. JSP tag libraries areated by developers who are proficient at the Java programming languageexpert in accessing data and other services and used by web application deers who can focus on presentation issues rather than being concerned withto access enterprise services. As well as encouraging division of labor betwlibrary developers and library users, custom tags increase productivity by ensulating recurring tasks so that they can be reused across more than one aption.
Tag libraries are receiving a great deal of attention in the JSP technology cmunity. For more information about tag libraries and pointers to some freeavailable libraries seehttp://java.sun.com/products/jsp/taglibrar-ies.html.
What is a Custom Tag? 200
199
200 CUSTOM TAGS IN JSP™ PAGES
ntain-s onns
ansthen
a
apter
The Example Tags 200Using Tags 204
Declaring Tag Libraries 204Types of Tags 205
Defining Tags 208Tag Handlers 209Tag Library Descriptors 210Simple Tags 212Tags With Attributes 213Tags With Bodies 216Tags That Define Scripting Variables 218Cooperating Tags 222
Examples 224An Iteration Tag 224A Template Tag Library 227
How Is a Tag Handler Invoked? 233
What is a Custom Tag?A custom tag is a user-defined JSP language element. When a JSP page coing a custom tag is translated into a servlet, the tag is converted to operationan object called atag handler. The servlet engine then invokes those operatiowhen the JSP page’s servlet is executed.
Custom tags have a rich set of features. They can
• Be customized via attributes passed from the calling page.
• Access all the objects available to JSP pages.
• Modify the response generated by the calling page.
• Communicate with each other. You can create and initialize a JavaBecomponent, create a variable that refers to that bean in one tag, anduse the bean in another tag.
• Be nested within one another, allowing for complex interactions withinJSP page.
The Example TagsThis chapter describes the tasks involved in using and defining tags. The chillustrates the tasks with excerpts from the JSP version of theDuke’s Bookstore
application discussed inJavaServer Pages™Technology (page 167) rewritten to
THE EXAMPLE TAGS 201
for
ebuts
tioned torame-me-JSP
et of
inag
take advantage of two tag libraries: Struts and tutorial-template. The sourcethe application is located inexamples/src/web/bookstore3.
The Struts tag library provides a framework for building internationalized wapplications that implement the Model-View-Controller design pattern. Strincludes a comprehensive set of utility custom tags for handling:
• HTML forms
• Templates
• JavaBeans components
• Logic processing
The Duke’s Bookstore application uses tags from the Strutsbean andlogicsublibraries.
The tutorial-template tag library defines a set of tags for creating an applicatemplate. The template is a JSP page, with place holders for the parts that nechange with each screen. Each of these place holders is referred to as a pater of the template. For example, a simple template could include a title parater for the top of the generated screen and a body parameter to refer to apage for the custom content of the screen. The template is created with a snested tags—definition, screen, and parameter—that are used to build atable of screen definitions forDuke’s Bookstore and aninsert tag to insertparameters from the table into the screen.
The third section in the chapter,Examples (page 224), describes two tagsdetail: theiterate tag from Struts and the set of tags in the tutorial-template tlibrary.
To build, deploy, and run the example:
1. Go to examples/src and build the application by executingantbookstore3 (seeHow to Build and Run the Examples (page xviii)).
2. Download and unpack Struts version 1.0 from
http://jakarta.apache.org/builds/jakarta-struts/release/v1.0-b1/
Copy struts-bean.tld, struts-logic.tld, and struts.jar fromjakarta-struts-1.0-b1/lib to examples/build/web/bookstore3.
3. Start the Cloudscape database by executingcloudscape -start.
4. If you have not already created the bookstore database, runant create-
web-db.
202 CUSTOM TAGS IN JSP™ PAGES
ct
ate
.jsp,em-.gif,dd
ton.
Go
5. Start thej2ee server
6. Startdeploytool
7. Create a J2EE application calledbookstore3.
a. Select File->New Application or the New Application button.
b. Enterbookstore3.ear in the Application File Name field.
c. Click OK.
8. Add thedispatcher web component and all of theDuke’s Bookstore
content to thebookstore3 application.
a. Select File->New Web Component or the Web Component button.
b. Click the Create New WAR File in Application radio button and selethe bookstore3 application from the combo box. Enterbookstore3 inthe field labeled WAR Display Name.
c. Click Add to add the content files. In the Edit Contents dialog, navigto examples/build/web/bookstore3. Select Dispatcher.class andclick Add. Add the JSP pages banner.jsp, bookstore.jsp, bookdetailscatalog.jsp, showcart.jsp, cashier.jsp, receipt.jsp, initdestroy.jsp, tplate.jsp, screendefinitions.jsp, and errorpage.jsp. Add duke.booksstruts-bean.tld, struts-logic.tld, tutorial-template.tld, and struts.jar. Athe cart, database, taglib, and util packages. Click OK.
d. Click Next.
e. Select the servlet radio button.
f. Click Next.
g. Select Dispatcher from the Servlet class combo box.
h. Typedispatcher in the Web Component Name field.
i. Click Next twice.
j. In the Component Aliases panel click Add and then type/enter in thealias field. Repeat to add the aliases/catalog, /bookdetails, /show-cart, /cashier, and/receipt.
k. Click Finish.
9. Add the BookDBEJB enterprise bean to the application.
a. Select File->New Enterprise Bean or the New Enterprise Bean but
b. Select bookstore3 from the combo box labeled Enterprise Bean willIn.
c. TypeBookDBEJB in the JAR Display Name field.
THE EXAMPLE TAGS 203
on
d. Click Add to add the content files. Navigate to theexam-ples/build/web/ejb directory and add the database and exceptipackages. Click Next.
e. Click Next.
f. Chose Session and Stateless for the Bean Type.
g. Select BookDBEJBImpl for Enterprise Bean Class.
h. Select BookDBEJBHome for Home Interface.
i. Select BookDBEJB for Remote Interface.
j. EnterBookDBEJB for Enterprise Bean Name.
10.Add a resource reference for the Cloudscape database.
a. Select the BookDBEJB enterprise bean.
b. Select the Resource Ref’s tab.
c. Click Add.
d. Select javax.sql.DataSource from the Type column
e. Enterjdbc/BookDB in the Coded Name field.
f. Enterjdbc/Cloudscape in the JNDI Name field.
11.Add a reference to the enterprise beanBookDBEJB.
a. Select the bookstore3 WAR.
b. Select the EJB Ref’s tab.
c. Click Add.
d. Enterejb/BookDBEJB in the Coded Name field.
e. Enter Session in the Type field.
f. EnterBookDBEJBHome in the Home field.
g. EnterBookDBEJB in the Remote field.
h. EnterBookDBEJB in the JNDI Name field.
12.Add the tag library URI to location mappings (seeDeclaring TagLibraries (page 204)):
a. Select the bookstore3 WAR.
b. Select the File Ref’s tab
c. Click the Add button in the JSP Tag Libraries subpanel.
d. Enter the relative URI/tutorial-template in the Coded Referencefield.
204 CUSTOM TAGS IN JSP™ PAGES
oy
.
a tag
g a
in
tag
D:
e. Enter the absolute location/WEB-INF/tutorial-template.tld in theTag Library field.
f. Repeat for /struts-bean to /WEB-INF/struts-bean.tld and/struts-logic to /WEB-INF/struts-logic.tld.
13.Deploy the application. Select Tools->Deploy Application or the DeplApplication Button. Click Next twice. TypeBookDBEJB in the Application->JNDI Name field andbookstore3 for the context root. Click Next andFinish.
14.Open the bookstore URLhttp://<host>:8000/bookstore3/enter.
SeeTroubleshooting (page 138) for help with diagnosing common problems
Using TagsThis section describes how a page author specifies that a JSP page is usinglibrary and introduces the different types of tags.
Declaring Tag LibrariesYou declare that a JSP page will use tags defined in a tag library by includintaglib directive in the page before any custom tag is used:
<%@ taglib uri="/WEB-INF/tutorial-template.tld" prefix="tt" %>
Theuri attribute refers to a URI that uniquely identifies the TLD, describedTagLibrary Descriptors (page 210). This URI can be direct or indirect. Thepre-
fix attribute defines the prefix that distinguishes tags defined by a givenlibrary from those provided by other tag libraries.
Tag library descriptor filenames must have the extension.tld. TLD files arestored in theWEB-INF directory of the WAR or in a subdirectory ofWEB-INF. Youcan reference a TLD directly and indirectly.
The followingtaglib directive directly references a TLD filename:
<%@ taglib uri="/WEB-INF/tutorial-template.tld" prefix="tt" %>
Thistaglib directive uses a short logical name to indirectly reference the TL
USING TAGS 205
pli-
end
havea
hod.
n0;
<%@ taglib uri="/tutorial-template" prefix="tt" %>
1. A logical name must be mapped to an absolute location in the web apcation deployment descriptor. To map the logical name/tutorial-tem-
plate to the absolute location/WEB-INF/tutorial-template.tld,Selectthe bookstore3 WAR.
2. Select the File Ref’s tab
3. Click the Add button in the JSP Tag Libraries subpanel.
4. Enter the relative URI/tutorial-template in the Coded Referencefield.
5. Enter the absolute location/WEB-INF/tutorial-template.tld in theTag Library field.
Types of TagsJSP custom tags are written using XML syntax. They have a start tag andtag, and possibly a body:
<tt:tag> body</tt:tag>
A custom tag with no body is expressed as follows:
<tt:tag />
Simple Tags
A simple tag contains no body and no attributes:
<tt:simple />
Tags With Attributes
A custom tag can have attributes. Attributes are listed in the start tag andthe syntaxattr="value". Attribute values serve to customize the behavior ofcustom tag just as parameters are used to customize the behavior of a met
An attribute value can be set from aString constant or a runtime expression. Aattribute value set from aString constant must have a type listed in Table 2
206 CUSTOM TAGS IN JSP™ PAGES
exeds.
typeom
of a
s itsypethe
fuest
over
the conversion applied is shown in the table. The value assigned to an indattribute must be an array and the rules just described apply to the element
You can also use a runtime expression to set the value of an attribute whoseis a compound Java programming language type. Recall frExpressions (page 184) that a JSP expression is used to insert the valuescripting language expression, converted into aString, into the stream returnedto the client. When used within a custom tag, an expression simply returnvalue; no automatic conversion is performed. As a consequence, the treturned from an expression must match or be castable to the type ofattribute, which is specified in the object that implements the tag.
The attributes of the Strutslogic:present tag determine whether the body othe tag is evaluated. In the following example, an attribute specifies a reqparameter namedClear:
<logic:present parameter="Clear">
The Duke’s Bookstore application pagecatalog.jsp uses a runtime expres-sion to set the value of the attribute that determines the collection of bookswhich the Strutslogic:iterate tag iterates:
<logic:iterate collection="<%=bookDB.getBooks()%>" id="book" type="database.BookDetails">
Table 20 Valid Tag Attribute Value Assignments
Attribute Type Conversion on String Value
boolean or Boolean As indicated injava.lang.Boolean.valueOf(String)
byte or Byte As indicated injava.lang.Byte.valueOf(String)
char or Character As indicated injava.lang.Character.valueOf(String)
double or Double As indicated injava.lang.Double.valueOf(String)
int or Integer As indicated injava.lang.Integer.valueOf(String)
float orFloat As indicated injava.lang.Float.valueOf(String)
long or Long As indicated injava.lang.Long.valueOf(String)
USING TAGS 207
text,
t
as anis abest
low-s anrise
om
Tags With Bodies
A custom tag can contain custom and core tags, scripting elements, HTMLand tag-dependent body content between the start and end tag.
In the following example, theDuke’s Bookstore application pageshow-cart.jsp uses the Strutslogic:present tag to clear the shopping cart and prina message if the request contains a parameter namedClear:
<logic:present parameter="Clear"> <% cart.clear(); %> <font color="#ff0000" size="+2"><strong> You just cleared your shopping cart! </strong><br> <br></font></logic:present>
Choosing Between Passing Information as Attributes or Body
As shown in the last two sections, it is possible to pass a given piece of dataattribute of the tag or to the tag’s body. Generally speaking, any data thatsimple string or can be generated by evaluating a simple expression ispassed as an attribute.
Tags That Define Scripting Variables
A tag can define a variable that can be used in scripts within a page. The foling example illustrates how to define and use a scripting variable that containobject returned from a JNDI lookup. Examples of such objects include enterpbeans, transactions, databases, environment entries, and so on:
<tt:lookup id="tx" type="UserTransaction" name="java:comp/UserTransaction" /><% tx.begin(); %>
In theDuke’s Bookstore application, several pages use bean-oriented tags frStruts to define scripting variables. For example,bookdetails.jsp uses thebean:parameter tag to retrieve the value of thebookId request parameter, anddefine the result as the scripting variablebookId. Thebean:define tag is usedto retrieve the value of the bookstore database propertybookDetails and definethe result as the scripting variablebook:
<bean:parameter id="bookId" name="bookId" /><jsp:setProperty name="bookDB" property="bookId"/><bean:define id="book" name="bookDB" property="bookDetails" type="database.BookDetails"/><font color="#ff00000" size="+2">You just removed:
208 CUSTOM TAGS IN JSP™ PAGES
hatef-
stedl forof
o
howtro-
<strong><jsp:getProperty name="book" property="title"></strong><br> <br></font>
Cooperating Tags
Tags can cooperate with each other through shared objects.
In the following example,tag1 creates a named object calledobj1, which isthen reused bytag2. The convention encouraged by the JSP specification is ta tag with attribute namedid creates and names an object and that object is rerenced by other tags with an attribute namedname.
<tt:tag1 id="obj1" attr2="value" /><tt:tag2 name="obj1" />
In the next example, an object created by the enclosing tag of a group of netags is available to all inner tags. Since the object is not named, the potentianaming conflicts is reduced. The following example illustrates how a setcooperating nested tags would appear in a JSP page.
<tt:outerTag> <tt:innerTag /></tt:outerTag>
The Duke’s Bookstore pagetemplate.jsp uses a set of cooperating tags tdefine the screens of the application. These tags are described inA TemplateTagLibrary (page 227).
Defining TagsTo define a tag, you need to:
• Develop a tag handler and helper classes for the tag
• Declare the tag in a tag library descriptor (TLD)
This section describes the properties of tag handlers and TLDs and explainsto develop tag handlers and library descriptor elements for each type of tag induced in the previous section.
DEFINING TAGS 209
tagmust
an, youse
theds to
tagseeerthat
JSP
Tag HandlersA tag handleris an object invoked by a web container to evaluate a customduring the execution of the JSP page that references the tag. Tag handlersimplement either theTag or BodyTag interface. Interfaces can be used to takeexisting Java object and make it a tag handler. For newly created handlerscan use theTagSupport and BodyTagSupport classes as base classes. Theclasses and interfaces are contained in thejavax.servlet.jsp.tagext pack-age.
Tag handler methods defined by theTag andBodyTag interfaces are called by theJSP page’s servlet at various points during the evaluation of the tag. Whenstart tag of a custom tag is encountered, the JSP page’s servlet calls methoinitialize the appropriate handler and then invokes the handler’sdoStartTag
method. When the end tag of a custom tag is encountered, the handler’sdoEnd-
Tag method is invoked. Additional methods are invoked in between when ahandler needs to interact with the body of the tag. For further information,How Is a Tag HandlerInvoked? (page 233). In order to provide a tag handlimplementation, you must implement the methods, summarized in Table 21,are invoked at various stages of processing the tag.
A tag handler has access to an API that allows it to communicate with thepage. The entry point to the API is the page context object (javax.serv-
Table 21 Tag Handler Methods
Tag Handler Type Methods
Simple doStartTag, doEndTag, release
AttributesdoStartTag, doEndTag, set/getAttribute1...N,release
Body, Evaluation andNo Interaction
doStartTag, doEndTag, release
Body, Iterative Evalua-tion
doStartTag, doAfterBody, doEndTag, release
Body, InteractiondoStartTag, doEndTag, release, doInitBody,doAfterBody, release
210 CUSTOM TAGS IN JSP™ PAGES
erge.
utes
and
.on-and
of
ver,ersion
heent
let.jsp.PageContext) through which a tag handler can retrieve all the othimplicit objects (request, session, and application) accessible from a JSP pa
Implicit objects can have named attributes associated with them. Such attribare accessed using[set|get]Attribute methods.
If the tag is nested, a tag handler also has access to the handler (called thepar-ent) associated with the enclosing tag.
A set of related tag handler classes (a tag library) is usually packageddeployed as a JAR archive.
Tag Library DescriptorsA tag library descriptor(TLD) is an XML document that describes a tag libraryA TLD contains information about a library as a whole and about each tag ctained in the library. TLDs are used by a web container to validate the tagsby JSP page development tools.
TLD filenames must have the extension.tld. TLD files are stored in theWEB-INF directory of the WAR file or a subdirectory ofWEB-INF. When you add aTLD to a WAR using deploytool,
A TLD must begin with an XML document prolog that specifies the versionXML and the document type definition (DTD):
<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP TagLibrary 1.2//EN""http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_2.dtd">
The J2EE SDK version 1.3 can understand 1.1 and 1.2 version DTDs. Howethis chapter documents the 1.2 version because you should use the newer vin any tag libraries that you develop. The template library TLD,tutorial-tem-
plate.tld, conforms to the 1.2 version. The Struts library TLDs conform to t1.1 version of the DTD, which has fewer elements and uses slightly differnames for some of the elements.
DEFINING TAGS 211
asandliked is
ss.
tagma-tly
te
The root of a TLD is thetaglib element. The subelements oftaglib are listedin Table 22:
Listener Element
A tag library can specify some classes that are event listeners (seeMonitoringServletLife Cycle Events (page 140)). The listeners are listed in the TLDlistener elements and the web container will instantiate the listener classesregister them in a way analogous to listeners defined at the WAR level. UnWAR-level listeners, the order in which the tag library listeners are registereundefined. The only subelement of thelistener element is thelistener-class element, which must contain the fully-qualified name of the listener cla
Tag Element
Each tag in the library is described by giving its name and the class of itshandler, information on the scripting variables created by the tag, and infortion on the tag’s attributes. Scripting variable information can be given direcin the TLD or through a tag extra info class (seeTagsThat Define Scripting
Table 22 taglib Subelements
Element Description
tlib-version The tag library’s version.
jsp-version The JSP specification version the tag library requires.
short-name Optional name that could be used by a JSP page authoring tool to creanames with a mnemonic value.
uri A URI that uniquely identifies the tag library.
display-name Optional name intended to be displayed by tools.
small-icon Optional small-icon that can be used by tools.
large-icon Optional large-icon that can be used by tools.
description Optional tag-specific information.
listener SeeListener Element(page 211).
tag SeeTag Element(page 211).
212 CUSTOM TAGS IN JSP™ PAGES
ofd by
in
ou
t
Variables (page 218)). Each attribute declaration contains an indicationwhether the attribute is required or not, whether its value can be determinerequest-time expressions, and the type of the attribute (seeTags WithAttributes (page 213)).
A tag is specified in a TLD in atag element. The subelements of tag are listedTable 23:
The following sections will describe the methods and TLD elements that yneed to develop for each type of tag introduced inUsing Tags (page 204).
Simple Tags
Tag Handlers
The handler for a simple tag must implement thedoStartTag and doEndTag
methods of theTag interface. ThedoStartTag method is invoked when the star
Table 23 tag Subelements
Element Description
name The unique tag name.
tag-class The fully-qualified name of the tag handler class.
tei-class Optional subclass ofjavax.servlet.jsp.tagext.TagExtraInfo.SeeTagExtraInfo Class(page 221).
body-content The body content type. SeeBody-content Element(page 213) andBody-content Element(page 218).
display-name Optional name intended to be displayed by tools.
small-icon Optional small-icon that can be used by tools.
large-icon Optional large-icon that can be used by tools.
description Optional tag-specific information.
variable Optional scripting variable information. SeeVariableElement(page 220).
attribute Tag attribute information. SeeAttribute Element(page 214).
DEFINING TAGS 213
ohe
e
the
s thatxam-
tag is encountered. This method returnsSKIP_BODY because a simple tag has nbody. ThedoEndTag method is invoked when the end tag is encountered. TdoEndTag method needs to returnEVAL_PAGE if the rest of the page needs to bevaluated; otherwise it should returnSKIP_PAGE.
The simple tag discussed in the first section:
<tt:simple />
would be implemented by the following tag handler:
public SimpleTag extends Tag Support { public int doStartTag() throws JspException { try { pageContext.getOut().print("Hello."); } catch (Exception ex) { throw new JspTagException("SimpleTag: " + ex.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; }}
Body-content Element
Tags without bodies must declare that their body content is empty usingbody-content element:
<body-content>empty</body-content>
Tags With Attributes
Defining Attributes in a Tag Handler
For each tag attribute, you must define a property and get and set methodconform to the JavaBeans architecture conventions in the tag handler. For eple, the tag handler for the Strutslogic:present tag
<logic:present parameter="Clear">
214 CUSTOM TAGS IN JSP™ PAGES
eth-
be
o antext
therf the
.
such
contains the following declaration and methods:
protected String parameter = null;public String getParameter() { return (this.parameter);}public void setParameter(String parameter) { this.parameter = parameter;}
Note that if your attribute is namedid, and your tag handler inherits from theTagSupport class, you do not need to define the property and set and get mods as these are already defined byTagSupport.
A tag attribute whose value is aString can name an attribute of one of theimplicit objects available to tag handlers. An implicit object attribute wouldaccessed by passing the tag attribute value to the [set|get]Attribute methodof the implicit object. This is a good way to pass scripting variable names ttag handler where they are associated with objects stored in the page co(SeeTags That Define Scripting Variables (page 218)).
Attribute Element
For each tag attribute you must specify whether the attribute is required, whethe value can be determined by an expression, and optionally, the type oattribute. For static values the type is alwaysjava.lang.String. If the rtex-
prvalue element istrue or yes, then thetype element defines the return typeexpected from any expression specified as the value of the attribute.
<attribute> <name>attr1</name> <required>true|false|yes|no</required> <rtexprvalue>true|false|yes|no</rtexprvalue> <type>fully-qualified_type</type></attribute>
If a tag attribute is not required, a tag handler should provide a default value
Thetag element for thelogic:present tag declares thatparameter attribute isnot required (because the tag can also test for the presence of other entitiesas bean properties), and that its value can be set by a runtime expression.
DEFINING TAGS 215
tagcon-
h the
thed at
<tag> <name>present</name> <tag-class>org.apache.struts.taglib. logic.PresentTag</tag-class> <body-content>JSP</body-content> ... <attribute> <name>parameter</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> ...</tag>
Attribute Validation
The documentation for a tag library should describe valid values forattributes. When a JSP page is translated, a web container will enforce anystraints contained in the TLD element for each attribute.
The attributes passed to a tag can also be validated at translation time witisValid method of a class derived fromTagExtraInfo. This class is also usedto provide information about scripting variables defined by the tag (seeTagsThat Define Scripting Variables (page 218)).
The isValid method is passed the attribute information in aTagData object,which contains attribute-value tuples for each of the tag’s attributes. Sincevalidation occurs at translation time, the value of an attribute that is computerequest time will be set toTagData.REQUEST_TIME_VALUE.
The tag<tt:twa attr1="value1"/> has the following TLDattribute ele-ment:
<attribute> <name>attr1</name> <required>true</required> <rtexprvalue>true</a></attribute
This declaration indicates that the value ofattr1 can be determined at runtime.
The followingisValid method checks that the value ofattr1 is a valid booleanvalue. Note that since the value ofattr1 can be computed at runtime,isValidmust check whether the tag user has chosen to provide a runtime value.
216 CUSTOM TAGS IN JSP™ PAGES
on, we
the
t
the
tag
public class TwaTEI extends TagExtraInfo { public boolean isValid(Tagdata data) { Object o = data.getAttribute("attr1"); if (o != null && o != TagData.REQUEST_TIME_VALUE) { if (o.toLowerCase().equals("true") || o.toLowerCase().equals("false") ) return true; else return false; } else return true; }}
Tags With Bodies
Tag Handlers
A tag handler for a tag with a body is implemented differently dependingwhether the tag handler needs to interact with the body or not. By interactmean that the tag handler reads or modifies the contents of the body.
Tag Handler Does Not Interact With the Body. If the tag handler doesnot need to interact with the body, the tag handler should implement theTag
interface (or be derived fromTagSupport). If the body of the tag needs to beevaluated, thedoStartTag method needs to returnEVAL_BODY_INCLUDE; other-wise it should returnSKIP_BODY.
If a tag handler needs to iteratively evaluate the body it should implementIterationTag interface or be derived fromTagSupport. It should returnEVAL_BODY_AGAIN from thedoStartTag anddoAfterBody methods if it deter-mines that the body needs to be evaluated again.
Tag Handler Interacts With the Body. If the tag handler needs to interacwith the body, the tag handler must implementBodyTag (or be derived fromBodyTagSupport). Such handlers typically implement thedoInitBody and thedoAfterBody methods. These methods interact with body content passed totag handler by the JSP page’s servlet.
A body content supports several methods to read and write its contents. Ahandler can use the body content’sgetString or getReader methods to extractinformation from the body and thewriteOut(out) method to write the bodycontents to an out stream. The writer supplied to thewriteOut method is
DEFINING TAGS 217
ler.
ishat
ated
n the
QLes not
obtained using the tag handler’sgetPreviousOut method. This method is usedto ensure that a tag handler’s results are available to an enclosing tag hand
If the body of the tag needs to be evaluated, thedoStartTag method needs toreturnEVAL_BODY_TAG; otherwise it should returnSKIP_BODY.
doInitBody Method
The doInitBody method is called after the body content is set but before itevaluated. You generally use this method to perform any initialization tdepends on the body content.
doAfterBody Method
ThedoAfterBody method is calledafter the body content is evaluated.
Like the doStartTag method, doAfterBody must return an indication ofwhether to continue evaluating the body. Thus, if the body should be evaluagain, as would be the case if you were implementing an iteration tag,doAfter-
Body should returnEVAL_BODY_TAG; otherwise doAfterBody should returnSKIP_BODY.
release Method
A tag handler should reset its state and release any private resources irelease method.
The following example reads the content of the body (which contains an Squery) and passes it to a object that executes the query. Since the body doneed to be reevaluated,doAfterBody returnsSKIP_BODY.
public class QueryTag extends BodyTagSupport { public int doAfterBody() throws JspTagException { BodyContent bc = getBodyContent(); // get the bc as string String query = bc.getString(); // clean up bc.clearBody(); try { Statement stmt = connection.createStatement(); result = stmt.executeQuery(query); } catch (SQLException e) { throw new JspTagException("QueryTag: " + e.getMessage()); } return SKIP_BODY; }}
218 CUSTOM TAGS IN JSP™ PAGES
MLse-
-y an
thesing
on
tag
per-value
Body-content Element
For tags that have a body, you must specify the type of the body content:
<body-content>JSP|tagdependent</body-content>
Body content containing custom and core tags, scripting elements, and HTtext is categorized asJSP. This is the value declared for the Strutlogic:present tag. All other types of body content, for example, SQL statments passed to the query tag, would be labeledtagdependent.
Note that the value of thebody-content element does not affect the interpretation of the body by the tag handler; the element is only intended to be used bauthoring tool for rendering the body content.
Tags That Define Scripting Variables
Tag Handlers
A tag handler is responsible for creating and setting the object referred to byscripting variable into a context accessible from the page. It does this by uthe pageContext.setAttribute(name, value, scope) or pageCon-
text.setAttribute(name, value) methods. Typically an attribute passed tthe custom tag specifies thename of the scripting variable object; this name cabe retrieved by invoking the attribute’s get method described inDefiningAttributes in a Tag Handler (page 213).
If the value of the scripting variable is dependent on an object present in thehandler’s context it can retrieve the object using thepageContext.getAt-
tribute(name, scope) method.
The usual procedure is that the tag handler retrieves a scripting variable,forms some processing on the object, and then sets the scripting variable’susing thepageContext.setAttribute(name, object) method.
DEFINING TAGS 219
con-
eratesari-
nfor-
The scope that an object can have is summarized in Table 24. The scopestrains the accessibility and lifetime of the object.
Providing Information About the Scripting Variable
The example described inTags That Define Scripting Variables (page 207)defines a scripting variablebook that is used for accessing book information:
<bean:define id="book" name="bookDB" property="bookDetails" type="database.BookDetails"/><font color="#ff00000" size="+2">You just removed:<strong><jsp:getProperty name="book" property="title"/></strong><br> <br></font>
When the JSP page containing this tag is translated, the web container gencode to synchronize the scripting variable with the object referenced by the vable. In order to do the code generation, the web container requires certain imation about the scripting variable:
• Variable name
• Variable class
• Whether the variable refers to a new or existing object.
• The availability of the variable.
Table 24 Scope of Objects
Name Accessible From Lifetime
page Current pageUntil the response has been sent backto the user or the request is passed toa new page
requestCurrent page and any included orforwarded pages
Until the response has been sent backto the user
sessionCurrent request and any subsequentrequest from the same browser(subject to session lifetime).
The life of the user’s session
applicationCurrent and any future request fromthe same web application
The life of the application
220 CUSTOM TAGS IN JSP™ PAGES
e
.
th-
-JSP
There are two ways to provide this information: by specifying thevariable
TLD subelement or by defining a tag extra info class and including thetei-
class element in the TLD. Using thevariable element is simpler, but slightlyless flexible.
Variable Element. Thevariable element has the following subelements:
• name-given - The variable name as a constant
• name-from-attribute The name of an attribute whose translation-timvalue will give the name of the variable.
One ofname-given or name-from-attribute is required. The following sub-elements are optional:
• variable-class Fully-qualified name of the class of the variablejava.lang.String is the default.
• declare - Whether the variable refers to a new object.True is the default.
• scope - The scope of the scripting variable defined.NESTED is default.Table 25 describes the availability of the scripting variable and the meods where the value of the variable must be set or reset.
The implementation of the Strutsbean:define tag conforms to the JSP specification version 1.1, which requires you to define a tag extra info class. Thespecification version 1.2 adds thevariable element. You could define the fol-lowing variable element for thebean:define tag:
Table 25 Scripting Variable Availability
Value Availability Methods
NESTEDBetween the starttag and the end tag.
In doInitBody anddoAfterBody for a tag handlerimplementingBodyTag; otherwise indoStartTag.
AT_BEGINFrom the start taguntil the end of thepage.
In doInitBody, doAfterBody, anddoEndTag for atag handler implementingBodyTag; otherwise indoStartTag anddoEndTag.
AT_ENDAfter the end taguntil the end of thepage.
In doEndTag.
DEFINING TAGS 221
ss
hese
teded
<tag> <variable> <name-from-attribute>id</name-from-attribute> <variable-class>database.BookDetails</variable-class> <declare>true</declare> <scope>AT_BEGIN</scope> </variable></tag>
TagExtraInfo Class. You define a tag extra info class by extending the clajavax.servlet.jsp.TagExtraInfo. A TagExtraInfo must implement thegetVariableInfo method to return an array ofVariableInfo objects contain-ing the following information:
• Variable name
• Variable class
• Whether the variable refers to a new object
• The availability of the variable
The web container passes a parameter calleddata to the getVariableInfo
method that contains attribute-value tuples for each of the tag’s attributes. Tattributes can be used to provide theVariableInfo object with a scripting vari-able’s name and class.
The Struts tag library provides information about the scripting variable creaby thebean:define tag in theDefineTei tag extra info class. Since the nam(book) and class (database.BookDetails) of the scripting variable are passein as tag attributes, they can be retrieved with thedata.getAttributeString
method and used to fill in theVariableInfo constructor. To allow the scriptingvariablebook to be used in the rest of the page, the scope ofbook is set to beAT_BEGIN.
public class DefineTei extends TagExtraInfo { public VariableInfo[] getVariableInfo(TagData data) { String type = data.getAttributeString("type"); if (type == null) type = "java.lang.Object"; return new VariableInfo[] { new VariableInfo(data.getAttributeString("id"), type, true, VariableInfo.AT_BEGIN) }; }}
222 CUSTOM TAGS IN JSP™ PAGES
ri-
bject
con-lers).
han-of
bjects,
ain its
aran-aticallyf thets can
andfor a
lerndlernec-
The fully-qualified name of the tag extra info class defined for a scripting vaable must be declared in the TLD in thetei-class subelement of thetag ele-ment. Thus, thetei-class element forDefineTei would be:
<tei-class>org.apache.struts.taglib.bean.DefineTagTei<tei-class>
Cooperating TagsTags cooperate by sharing objects. JSP technology supports two styles of osharing.
The first style requires that a shared object be named and stored in the pagetext (one of the implicit objects accessible to both JSP pages and tag handTo access objects created and named by another tag, a tag handler uses thepage-
Context.getAttribute(name, scope) method.
In the second style of object sharing, an object created by the enclosing tagdler of a group of nested tags is available to all inner tag handlers. This formobject sharing has the advantage that it uses a private namespace for the othus reducing the potential for naming conflicts.
To access an object created by an enclosing tag, a tag handler must first obtenclosing tag with the static methodTagSupport.findAncestorWith-Class(from, class) or the TagSupport.getParent method. The formermethod should be used when a specific nesting of tag handlers cannot be guteed. Once the ancestor has been retrieved, a tag handler can access any stor dynamically created objects. Statically created objects are members oparent. Private objects can also be created dynamically created. Such objecbe stored in a tag handler with thesetValue method and retrieved with thegetValue method.
The following example illustrates a tag handler that supports both the namedprivate object approaches to sharing objects. In the example, the handlerquery tag checks whether an attribute namedconnection has been set in thedoStartTag method. If the connection attribute has been set, the handretrieves the connection object from the page context. Otherwise, the tag hafirst retrieves the tag handler for the enclosing tag, and then retrieves the contion object from that handler.
public class QueryTag extends BodyTagSupport { private String connectionId; public int doStartTag() throws JspException { String cid = getConnection();
DEFINING TAGS 223
fol-
is
if (cid != null) { // there is a connection id, use it connection =(Connection)pageContext. getAttribute(cid); } else { ConnectionTag ancestorTag = (ConnectionTag)findAncestorWithClass(this, ConnectionTag.class); if (ancestorTag == null) { throw new JspTagException("A query without a connection attribute must be nested within a connection tag."); } connection = ancestorTag.getConnection(); } }}
The query tag implemented by this tag handler could be used in either of thelowing ways:
<tt:connection id="con01" ....> ... </tt:connection><tt:query id="balances" connection="con01"> SELECT account, balance FROM acct_table where customer_number = <%= request.getCustno()%></tt:query>
<tt:connection ...> <x:query id="balances"> SELECT account, balance FROM acct_table where customer_number = <%= request.getCustno()%> </x:query></tt:connection>
The TLD for the tag handler must indicate that the connection attributeoptional with the following declaration:
<tag> ... <attribute> <name>connection</name> <required>false</required> </attribute></tag>
224 CUSTOM TAGS IN JSP™ PAGES
rringro-
plica-first
oftentrold in
a-e tagthe
pt
n.i-con-
ExamplesThe custom tags described in this section demonstrate solutions to two recuproblems in developing JSP applications: minimizing the amount of Java pgramming in JSP pages and ensuring a common look and feel across aptions. In doing so, they illustrate many of the styles of tags discussed in thesection.
An Iteration TagConstructing page content that is dependent on dynamically generated datarequires the use of flow control scripting statements. By moving the flow conlogic to tag handlers, flow control tags reduce the amount of scripting needeJSP pages.
The Struts logic:iterate tag retrieves objects from a collection stored in a JavBeans component and assigns them to a scripting variable. The body of thretrieves information from the scripting variable. While elements remain incollection, theiterate tag causes the body to be reevaluated.
JSP Page
Two Duke’s Bookstore application pages,catalog.jsp and showcart.jsp,use thelogic:iterate tag to iterate over collections of objects. An excerfrom catalog.jsp is shown below. The JSP page initializes theiterate tagwith a collection (named by theproperty attribute) of thebookDB bean. Theiterate tag sets thebook scripting variable on each iteration over the collectioThe bookId property of thebook variable is exposed as another scripting varable. Properties of both variables are used to dynamically generate a tabletaining links to other pages and book catalog information.
<logic:iterate name="bookDB" property="books" id="book" type="database.BookDetails"> <bean:define id="bookId" name="book" property="bookId" type="java.lang.String"/>
<tr> <td bgcolor="#ffffaa"> <a href="<%=request.getContextPath()%> /bookdetails?bookId=<%=bookId%>"> <strong><jsp:getProperty name="book" property="title"/> </strong></a></td>
<td bgcolor="#ffffaa" rowspan=2>
EXAMPLES 225
san
s:n ore inct.ro-
st is
ated;
ed innts,ent
<jsp:setProperty name="currency" property="amount" value="<%=book.getPrice()%>"/> <jsp:getProperty name="currency" property="format"/> </td>
<td bgcolor="#ffffaa" rowspan=2> <a href="<%=request.getContextPath()%> /catalog?bookId=<%=bookId%>"> Add to Cart </a></td></tr>
<tr> <td bgcolor="#ffffff"> by <em> <jsp:getProperty name="book" property="firstName"/> <jsp:getProperty name="book" property="surname"/></em></td></tr></logic:iterate>
Tag Handler
The implementation of the Strutslogic:iterate tag conforms to JSP version1.1 specification capabilities, which requires you to extend theBodyTagSupport
class. The JSP version 1.2 specification adds features (described inTagHandlerDoesNot InteractWith the Body (page 216)) that simplify programming tagthat iteratively evaluate their body. The following discussion is based onimplementation that uses these features.
The logic:iterate tag supports initializing the collection in a several wayfrom a collection provided as a tag attribute or from a collection that is a beaa property of a bean. Our example uses the latter method. Most of the coddoStartTag is concerned with constructing an iterator over the collection objeThe method first checks if the handler’s collection property is set and if not, pceeds to checking the bean and property attributes. If thebean andproperty
attributes are both set, thedoStartTag calls a utility method that uses JavaBeanintrospection methods to retrieve the collection. Once the collection objecdetermined, the method constructs the iterator.
If the iterator contains more elements,doStartTag sets the value of the scriptingvariable to the next element and then indicates that the body should be evaluotherwise it ends the iteration by returningSKIP_BODY.
After the body has been evaluated, thedoAfterBody method retrieves the bodycontent and writes it to the out stream. The body content object is then clearpreparation for another body evaluation. If the iterator contains more elemedoAfterBody again sets the value of the scripting variable to the next elem
226 CUSTOM TAGS IN JSP™ PAGES
d
and returnsEVAL_BODY_AGAIN to indicate that the body should be evaluateagain. This causes the re-execution ofdoAfterBody. When there are no remain-ing elements,doAfterBody terminates the process by returningSKIP_BODY.public class IterateTag extends TagSupport { protected Iterator iterator = null; protected Object collection = null; protected String id = null; protected String name = null; protected String property = null; protected String type = null; public int doStartTag() throws JspException { Object collection = this.collection; if (collection == null) { try { Object bean = pageContext.findAttribute(name); if (bean == null) { ... throw an exception } if (property == null) collection = bean; else collection = PropertyUtils. getProperty(bean, property); if (collection == null) { ... throw an exception } } catch ... catch exceptions thrown by PropertyUtils.getProperty } } // Construct an iterator for this collection if (collection instanceof Collection) iterator = ((Collection) collection).iterator(); else if (collection instanceof Iterator) iterator = (Iterator) collection; ... } // Store the first value and evaluate, // or skip the body if none if (iterator.hasNext()) { Object element = iterator.next(); pageContext.setAttribute(id, element); return (EVAL_BODY_AGAIN); } else return (SKIP_BODY);
EXAMPLES 227
s tag
eachuttingand
} public int doAfterBody() throws JspException { if (bodyContent != null) { try { JspWriter out = getPreviousOut(); out.print(bodyContent.getString()); bodyContent.clearBody(); } catch (IOException e) { ... } } if (iterator.hasNext()) { Object element = iterator.next(); pageContext.setAttribute(id, element); return (EVAL_BODY_AGAIN); } else return (SKIP_BODY); } }}
Tag Extra Info Class
Information about the scripting variable is provided in theIterateTei tag extrainfo class. The name and class of the scripting variable are passed in aattributes and used to fill in theVariableInfo constructor.
public class IterateTei extends TagExtraInfo { public VariableInfo[] getVariableInfo(TagData data) { String type = data.getAttributeString("type"); if (type == null) type = "java.lang.Object";
return new VariableInfo[] { new VariableInfo(data.getAttributeString("id"), type, true, VariableInfo.AT_BEGIN) }; }}
A Template Tag LibraryA template provides a way to separate the common elements that are part ofscreen from the elements that change with each screen of an application. Pall the common elements together into one file makes it easier to maintain
228 CUSTOM TAGS IN JSP™ PAGES
mentreenpor-
angeof ther theor the
d thenon
ute
enforce a consistent look and feel in all the screens. It also makes developof individual screens easier since the designer can focus on portions of a scthat are specific to that screen while the template takes care of the commontions.
The template is a JSP page, with place holders for the parts that need to chwith each screen. Each of these place holders is referred to as a parametertemplate. For example, a simple template could include a title parameter fotop of the generated screen and a body parameter to refer to a JSP page fcustom content of the screen.
The template uses a set of nested tags—definition, screen, andparameter—to define a table of screen definition for an application screen and aninsert tagto insert parameters from a screen definition into the application screen.
JSP Page
The template for theDuke’s Bookstore example,template.jsp, is shownbelow. This page includes a JSP page that creates the screen definition anuses theinsert tag to insert parameters from the definition into the applicatiscreen.
<%@ taglib uri="/tutorial-template.tld" prefix="tt" %><%@ page errorPage="errorpage.jsp" %><%@ include file="screendefinitions.jsp" %><html> <head> <title> <tt:insert definition="bookstore" parameter="title"/> </title> </head> <tt:insert definition="bookstore" parameter="banner"/> <tt:insert definition="bookstore" parameter="body"/> </body></html>
screendefinitions.jsp creates a screen definition based on a request attribselectedScreen:
<tt:definition name="bookstore" screen="<%= (String)request. getAttribute(\"selectedScreen\") %>"> <tt:screen id="/enter"> <tt:parameter name="title"
EXAMPLES 229
essary
-
value="Duke’s Bookstore" direct="true"/> <tt:parameter name="banner" value="/banner.jsp" direct="false"/> <tt:parameter name="body" value="/bookstore.jsp" direct="false"/> </tt:screen> <tt:screen id="/catalog"> <tt:parameter name="title" value="Book Catalog" direct="true"/> ...</tt:definition>
The template is instantiated by theDispatcher servlet.Dispatcher first gets therequested screen and stores as an attribute of the request. This is necbecause when the request is forwarded totemplate.jsp, the request URLdoesn’t contain the original request (for example,/bookstore3/catalog), butinstead reflects the path (/bookstore3/template.jsp) of the forwarded page.Finally the servlet dispatches the request totemplate.jsp:
public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { request.setAttribute("selectedScreen", request.getServletPath()); RequestDispatcher dispatcher = request.getRequestDispatcher("/template.jsp"); if (dispatcher != null) dispatcher.forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) { request.setAttribute("selectedScreen", request.getServletPath()); RequestDispatcher dispatcher = request.getRequestDispatcher("/template.jsp"); if (dispatcher != null) dispatcher.forward(request, response); }}
Tag Handlers
The template tag library contains four tag handlers—DefinitionTag,ScreenTag, ParameterTag, andInsertTag—that demonstrate the use of cooperating tags.DefinitionTag, ScreenTag, andParameterTag comprise a set of
230 CUSTOM TAGS IN JSP™ PAGES
of a
f the
n
nested tag handlers that share public and private objects.DefinitionTag createsa public named object calleddefinition that is used byInsertTag.
In doStartTag, DefinitionTag creates a public object namedscreens thatcontains a hash table of screen definitions. A screen definition consistsscreen identifier and a set of parameters associated with the screen.
public int doStartTag() { HashMap screens = null; screens = (HashMap) pageContext.getAttribute("screens"); if (screens == null) pageContext.setAttribute("screens", new HashMap(), pageContext.APPLICATION_SCOPE); return EVAL_BODY_INCLUDE;}
The table of screen definitions is filled in byScreenTag andParameterTag fromtext provided as attributes to these tags. Table 26 shows the contents oscreen definitions hash table for theDuke’s Bookstore application.
In doEndTag, DefinitionTag creates a public object of classDefinition,selects a screen definition from thescreens object based on the URL passed ithe request, and uses it to initialize theDefinition object.
public int doEndTag()throws JspTagException { try { Definition definition = new Definition(); Hashtable screens = null;
Table 26 Screen Definitions
Screen Id Title Banner Body
/enter Duke’s Bookstore /banner.jsp /bookstore.jsp
/catalog Book Catalog /banner.jsp /catalog.jsp
/bookdetails Book Description /banner.jsp /bookdetails.jsp
/showcart Your Shopping Cart /banner.jsp /showcart.jsp
/cashier Cashier /banner.jsp /cashier.jsp
/receipt Receipt /banner.jsp /receipt.jsp
EXAMPLES 231
s
ArrayList params = null; TagSupport screen = null; screens = (HashMap) pageContext.getAttribute("screens", pageContext.APPLICATION_SCOPE); if (screens != null) params = (ArrayList) screens.get(screenId); else ... if (params == null) ... Iterator ir = null; if (params != null) ir = params.iterator(); while ((ir != null) && ir.hasNext()) definition.setParam((Parameter) ir.next()); // put the definition in the page context pageContext.setAttribute( definitionName, definition); } catch (Exception ex) { ex.printStackTrace(); } return EVAL_PAGE;}
If the URL passed in the request is /enter, theDefinition contains the itemsfrom the first row of Table 26:
The definition for the URL/enter is shown in Table 27. The definition specifiethat the value of theTitle parameter,Duke’s Bookstore, should be inserted
Title Banner Body
Duke’s Bookstore /banner.jsp /bookstore.jsp
232 CUSTOM TAGS IN JSP™ PAGES
to
it ismeter
directly into the output stream, but the values ofBanner and Body should bedynamically included.
InsertTag uses theDefinition to insert parameters of the screen definition inthe response. In thedoStartTag method it retrieves the definition object fromthe page context.
public int doStartTag() { // get the definition from the page context definition = (Definition) pageContext. getAttribute(definitionName); // get the parameter if (parameterName != null && definition != null) parameter = (Parameter)definition. getParam(parameterName); if (parameter != null) directInclude = parameter.isDirect(); return SKIP_BODY;}
ThedoEndTag method inserts the parameter value. If the parameter is direct,directly inserted into the response; otherwise the request is sent to the paraand the response is dynamically included into the overall response.
public int doEndTag()throws JspTagException { try { if (directInclude && parameter != null) pageContext.getOut().print(parameter.getValue()); else { if ((parameter != null) && (parameter.getValue() != null)) pageContext.include(parameter.getValue());
Table 27 Screen Definition for URL/enter
ParameterName Parameter Value isDirect
title Duke’s Bookstore true
banner /banner.jsp false
body /bookstore.jsp false
HOW IS A TAG HANDLER INVOKED? 233
JSPthe
n-e.
g
} } catch (Exception ex) { throw new JspTagException(ex.getMessage()); } return EVAL_PAGE;}
How Is a Tag Handler Invoked?The Tag interface defines the basic protocol between a tag handler andpage’s servlet. It defines the life cycle and the methods to be invoked whenstart and end tags are encountered.
The JSP page’s servlet invokes thesetPageContext, setParent, and attributesetting methods before callingdoStartTag. The JSP page’s servlet also guaratees thatrelease will be invoked on the tag handler before the end of the pag
Here is a typical tag handler method invocation sequence:
ATag t = new ATag();t.setPageContext(...);t.setParent(...);t.setAttribute1(value1);t.setAttribute2(value2);t.doStartTag();t.doEndTag();t.release();
TheBodyTag interface extendsTag by defining additional methods that let a tahandler access its body. The interface provides three new methods:
setBodyContent - creates body content and adds to tag handler
doInitBody - called before evaluation of tag body
doAfterBody - called after evaluation of tag body
A typical invocation sequence is:
t.doStartTag();out = pageContext.pushBody();t.setBodyContent(out);// perform any initialization needed after body content is sett.doInitBody();t.doAfterBody();// while doAfterBody returns EVAL_BODY_TAG we// iterate body evaluation
234 CUSTOM TAGS IN JSP™ PAGES
...t.doAfterBody();t.doEndTag();t.pageContext.popBody();t.release();
orest bemsbe
eaverios,rrentsac-
b-
Transactionsby Dale Green
A typical enterprise application accesses and stores information in one or mdatabases. Because this information is critical for business operations, it muaccurate, current, and reliable. Data integrity would be lost if multiple prograwere allowed to simultaneously update the same information. Also, it wouldlost if a system that failed while processing a business transaction were to lthe affected data only partially updated. By preventing both of these scenasoftware transactions ensure data integrity. Transactions control the concuaccess of data by multiple programs. In the event of a system failure, trantions make sure that after recovery the data will be in a consistent state.
Note: Currently, this chapter discusses transactions only for enterprise beans. Susequent versions will also discuss transactions for web components.
What is a Transaction? 236Container-Managed Transactions 236
Transaction Attributes 237Rolling Back a Container-Managed Transaction 241Synchronizing a Session Bean’s Instance Variables 242Methods Not Allowed in Container-Managed Transactions 243
Bean-Managed Transactions 243JDBC Transactions 244JTA Transactions 245Returning Without Committing 246Methods Not Allowed in Bean-Managed Transactions 247
Summary of Transaction Options 247Transaction Timeouts 248Isolation Levels 249
235
236 TRANSACTIONS
steps.unt
ise,le, a
ac-tate-s ofrive
ata,
eter-d or
ainernsac-sim-
k then and
Updating Multiple Databases 250
What is a Transaction?To emulate a business transaction, a program may need to perform severalA financial program, for example, might transfer funds from a checking accoto a savings account with the steps listed in the following pseudo-code.
begin transaction debit checking account credit savings account update history logcommit transaction
Either all three of these steps must complete, or none of them at all. Otherwdata integrity is lost. Because the steps within a transaction are a unified whotransaction is often defined as an indivisible unit of work.
A transaction can end in two ways: with a commit or a rollback. When a transtion commits, the data modifications made by its statements are saved. If a sment within a transaction fails, the transaction rolls back, undoing the effectall statements in the transaction. In the pseudo-code, for example, if a disk dcrashed during thecredit step, the transaction rolls back and undoes the dmodifications made by thedebit statement. Although the transaction faileddata integrity is intact because the accounts still balance.
In the preceding pseudo-code, thebegin and commit statements mark theboundaries of the transaction. When deploying an enterprise bean, you dmine how the boundaries are set by specifying either container-managebean-managed transactions.
Container-Managed TransactionsIn an enterprise bean with container-managed transactions, the EJB™ contsets the boundaries of the transactions. You can use container-managed trations with both session and entity beans. Container-managed transactionsplify development because the enterprise bean code does not explicitly martransaction’s boundaries. The code does not include statements that begiend the transaction.
CONTAINER-MANAGED TRANSACTIONS 237
riseEachsac-
withods
atesns-es itcutete of
Typically, the container begins a transaction immediately before an enterpbean method starts. It commits the transaction just before the method exits.method can be associated with a single transaction. Nested or multiple trantions are not allowed within a method.
Container-managed transactions do not require all methods to be associatedtransactions. When deploying a bean, you specify which of the bean’s methare associated with transactions by setting the transaction attributes.
Transaction AttributesA transaction attribute controls the scope of a transaction. Figure 16 illustrwhy controlling the scope is important. In the diagram, method-A begins a traaction and then invokes method-B of Bean-2. When method-B executes, dorun within the scope of the transaction started by method-A or does it exewith a new transaction? The answer depends on the transaction attribumethod-B.
Figure 16 Transaction Scope
.
.
. method-A() { . . . bean-2.method-B() }
Bean-1
.
.
. method-B() { . . . }
Bean-2
TX1TX?
238 TRANSACTIONS
n’snotrun-
anttrans-.
n’s
new
t the
n’snot
Transaction Attribute Values
A transaction attribute may have one of the following values:
• Required
• RequiresNew
• Mandatory
• NotSupported
• Supports
• Never
Required
If the client is running within a transaction and it invokes the enterprise beamethod, the method executes within the client’s transaction. If the client isassociated with a transaction, the container starts a new transaction beforening the method.
The Required attribute will work for most transactions. Therefore, you may wto use it as a default, at least in the early phases of development. Becauseaction attributes are declarative, you can easily change them at a later time
RequiresNew
If the client is running within a transaction and it invokes the enterprise beamethod, the container takes the following steps:
1. Suspends the client’s transaction
2. Starts a new transaction
3. Delegates the call to the method
4. Resumes the client’s transaction after the method completes
5. If the client is not associated with a transaction, the container starts atransaction before running the method.
You should use the RequiresNew attribute when you want to ensure thamethod always runs within a new transaction.
Mandatory
If the client is running within a transaction and it invokes the enterprise beamethod, the method executes within the client’s transaction. If the client isassociated with a transaction, the container throws theTransactionRequire-
dException.
CONTAINER-MANAGED TRANSACTIONS 239
nsac-
n’sthe
ent’s
art a
will
n’snotction
e the
n’s
ning
d T2withnt is
efore
notbase
Use the Mandatory attribute if the enterprise bean’s method must use the tration of the client.
NotSupported
If the client is running within a transaction and it invokes the enterprise beamethod, the container suspends the client’s transaction before invokingmethod. After the method has completed, the container resumes the clitransaction.
If the client is not associated with a transaction, the container does not stnew transaction before running the method.
Use the NotSupported attribute when you want to ensure that the methodnever run within a transaction generated by the container.
Supports
If the client is running within a transaction and it invokes the enterprise beamethod, the method executes within the client’s transaction. If the client isassociated with a transaction, the container does not start a new transabefore running the method.
Because the transactional behavior of the method may vary, you should usSupports attribute with caution.
Never
If the client is running within a transaction and it invokes the enterprise beamethod, the container throws aRemoteException. If the client is not associatedwith a transaction, the container does not start a new transaction before runthe method.
Summary of Transaction Attributes
Table 28 summarizes the effects of the transaction attributes. Both the T1 antransactions are controlled by the container. A T1 transaction is associatedthe client that calls a method in the enterprise bean. In most cases, the clieanother enterprise bean. A T2 transaction is started by the container just bthe method executes.
In the last column, the word “none” means that the business method doesexecute within a transaction controlled by the container. However, the data
240 TRANSACTIONS
ager
y canrpriserprisetingperrson.
r forher
calls in such a business method might be controlled by the transaction manof the DBMS.
Setting Transaction Attributes
Because transaction attributes are stored in the deployment descriptor, thebe changed during several phases of J2EE™ application development: entebean creation, application assembly, and deployment. However, as an entebean developer, it is your responsibility to specify the attributes when creathe bean. The attributes should be modified only by an application develowho is assembling components into larger applications. Do not expect the pewho is deploying the J2EE™ application to specify the transaction attributes
You can specify the transaction attributes for the entire enterprise bean oindividual methods. If you’ve specified one attribute for a method and anot
Table 28 Transaction Attributes and Scope
TransactionAttribute
Client’sTransaction
Business Method’sTransaction
Requirednone T2
T1 T1
RequiresNewnone T2
T1 T2
Mandatorynone error
T1 T1
NotSupportednone none
T1 none
Supportsnone none
T1 T1
Nevernone none
T1 error
CONTAINER-MANAGED TRANSACTIONS 241
fyingeansdo nots for
sys-ac-
n. Ifmay
ow a
to-
for the bean, the attribute for the method takes precedence. When speciattributes for individual methods, the requirements for session and entity bvary. Session beans need the attributes defined for business methods, butallow them for the create methods. Entity beans require transaction attributethe business,create, remove, and finder methods.
Rolling Back a Container-Managed TransactionThere are two ways to roll back a container-managed transaction. First, if atem exception is thrown, the container will automatically roll back the transtion. Second, by invoking thesetRollbackOnly method of theEJBContextinterface, the bean method instructs the container to roll back the transactiothe bean throws an application exception, the roll back is not automatic, butbe initiated by a call tosetRollbackOnly. for For a description of system andapplication exceptions, seeHandling Exceptions (page 115).
The source code for the following example is in theexamples/src/ejb/bank
directory. To compile the code, go to theexamples/src directory and typeantbank. To create the database tables, typeant create-bank-table.
The transferToSaving method of theBankEJB example illustrates theset-RollbackOnly method. If a negative checking balance occurs,transferToSav-
ing invokes setRollBackOnly and throws an application exception(InsufficientBalanceException). The updateChecking and updateSaving
methods update database tables. If the updates fail, these methods thrSQLException and thetransferToSaving method throws anEJBException.Because theEJBException is a system exception, it causes the container to aumatically roll back the transaction. Here is the code for thetransferToSaving
method:
public void transferToSaving(double amount) throws InsufficientBalanceException {
checkingBalance -= amount; savingBalance += amount;
try { updateChecking(checkingBalance); if (checkingBalance < 0.00) { context.setRollbackOnly(); throw new InsufficientBalanceException(); } updateSaving(savingBalance); } catch (SQLException ex) {
242 TRANSACTIONS
es toansauto-
mustsiest
-ase.
un.sles
d
tion
throw new EJBException (“Transaction failed due to SQLException: “ + ex.getMessage()); }}
When the container rolls back a transaction, it always undoes the changdata made by SQL calls within the transaction. However, only in entity bewill the container undo changes made to instance variables. (It does so bymatically invoking the entity bean’sejbLoad method, which loads the instancevariables from the database.) When a rollback occurs, a session beanexplicitly reset any instance variables changed within the transaction. The eaway to reset a session bean’s instance variables is by implementing theSession-
Synchonization interface.
Synchronizing a Session Bean’s Instance VariablesThe SessionSynchonization interface, which is optional, allows you to synchronize the instance variables with their corresponding values in the databThe container invokes theSessionSynchonization methods—afterBegin,beforeCompletion, and afterCompletion—at each of the main stages of atransaction.
TheafterBegin method informs the instance that a new transaction has begThe container invokesafterBegin immediately before it invokes the businesmethod. TheafterBegin method is a good place to load the instance variabfrom the database. TheBankEJB class, for example, loads thecheckingBalanceandsavingBalance variables in theafterBegin method:
public void afterBegin() {
System.out.println(“afterBegin()”); try { checkingBalance = selectChecking(); savingBalance = selectSaving(); } catch (SQLException ex) { throw new EJBException(“afterBegin Exception: “ + ex.getMessage()); }}
The container invokes thebeforeCompletion method after the business methohas finished, but just before the transaction commits. ThebeforeCompletion
method is the last opportunity for the session bean to roll back the transac
BEAN-MANAGED TRANSACTIONS 243
e
. It
an
ion
trans-
t markaged
(by callingsetRollbackOnly). If it hasn’t already updated the database with thvalues of the instance variables, the session bean may do so in thebeforeCom-
pletion method.
The afterCompletion method indicates that the transaction has completedhas a singleboolean parameter, whose value istrue if the transaction was com-mitted andfalse if it was rolled back. If a rollback occurred, the session becan refresh its instance variables from the database in theafterCompletion
method:
public void afterCompletion(boolean committed) {
System.out.println(“afterCompletion: “ + committed); if (committed == false) { try { checkingBalance = selectChecking(); savingBalance = selectSaving(); } catch (SQLException ex) {
throw new EJBException(“afterCompletion SQLException:“ + ex.getMessage()); } }}
Methods Not Allowed in Container-ManagedTransactionsYou should not invoke any method that might interfere with the transactboundaries set by the container. The list of prohibited methods follows:
• Thecommit, setAutoCommit, androllback methods ofjava.sql.Con-nection
• ThegetUserTransaction method ofjavax.ejb.EJBContext
• Any method ofjavax.transaction.UserTransaction
You may, however, use these methods to set boundaries in bean-managedactions.
Bean-Managed TransactionsIn a bean-managed transaction, the session bean code invokes methods thathe boundaries of the transaction. An entity bean may not have bean-man
244 TRANSACTIONS
oughe onengles-
anthe
n the
useand
ussion
sostt
transactions; it must use container-managed transactions instead. Althbeans with container-managed transactions require less coding, they havlimitation: When a method is executing, it can be associated with either a sitransaction or no transaction at all. If this limitation will make coding your sesion bean difficult, you should consider using bean-managed transactions.
The following pseudo-code illustrates the kind of fine-grained control you cobtain with bean-managed transactions. By checking various conditions,pseudo-code decides whether to start and stop different transactions withibusiness method.
begin transaction...update table-a...if (condition-x) commit transactionelse if (condition-y) update table-b commit transactionelse rollback transaction begin transaction update table-c commit transaction
When coding a bean-managed transaction, you must decide whether toJDBC or JTA transactions. The sections that follow discuss the techniquesmerits of both approaches.
JDBC TransactionsA JDBC transactionis controlled by the transaction manager of the DBMS. Yomay want to use JDBC transactions when wrapping legacy code inside a sebean. To code a JDBC transaction, you invoke thecommit androllback meth-ods of thejavax.sql.Connection interface. The beginning of a transaction iimplicit. A transaction begins with the first SQL statement that follows the mrecentcommit, rollback, or connect statement. (This rule is generally true, bumay vary with DBMS vendor.)
The source code for the following example is in theexamples/src/ejb/ware-
house directory. To compile the code, go to theexamples/src directory andtype ant bank. To create the database tables, typeant create-warehouse-
table.
BEAN-MANAGED TRANSACTIONS 245
esThe
ryesac-k.
toman-withhodsTS
antfrom
ithve one
start
The following code is from theWarehouseEJB example, a session bean that ustheConnection interface’s methods to delimit bean-managed transactions.ship method starts by invokingsetAutoCommit on the Connection objectnamedcon. This invocation tells the DBMS not to automatically commit eveSQL statement. Next, theship method calls routines that update thorder_item andinventory database tables. If the updates succeed, the trantion is committed. But if an exception is thrown, the transaction is rolled bac
public void ship (String productId, String orderId, intquantity) {
try { con.setAutoCommit(false); updateOrderItem(productId, orderId); updateInventory(productId, quantity); con.commit(); } catch (Exception ex) { try { con.rollback(); throw new EJBException(“Transaction failed: “ + ex.getMessage()); } catch (SQLException sqx) { throw new EJBException(“Rollback failed: “ + sqx.getMessage()); } }}
JTA TransactionsJTA is the abbreviation for the Java™ Transaction API. This API allows youdemarcate transactions in a manner that is independent of the transactionager implementation. The J2EE SDK implements the transaction managerthe Java Transaction Service (JTS). But your code doesn’t call the JTS metdirectly. Instead, it invokes the JTA methods, which then call the lower-level Jroutines.
A JTA transactionis controlled by the J2EE transaction manager. You may wto use a JTA transaction because it can span updates to multiple databasesdifferent vendors. A particular DBMS’s transaction manager may not work wheterogeneous databases. However, the J2EE transaction manager does halimitation-- it does not support nested transactions. In other words, it cannota transaction for an instance until the previous transaction has ended.
246 TRANSACTIONS
tes
ethodses-
n theen ifonnec-.
The source code for the following example is in theexamples/src/ejb/teller
directory. To compile the code, go to theexamples/src directory and typeantteller. To create the database tables, typeant create-bank-teller.
To demarcate a JTA transaction, you invoke thebegin, commit, androllbackmethods of theUserTransaction interface. The following code, taken from theTellerEJB example program, demonstrates theUserTransaction methods. Thebegin andcommit invocations delimit the updates to the database. If the updafail, the code invokes therollback method and throws anEJBException.
public void withdrawCash(double amount) {
UserTransaction ut = context.getUserTransaction();
try { ut.begin(); updateChecking(amount); machineBalance -= amount; insertMachine(machineBalance); ut.commit(); } catch (Exception ex) { try { ut.rollback(); } catch (SystemException syex) { throw new EJBException (“Rollback failed: “ + syex.getMessage()); } throw new EJBException (“Transaction failed: “ + ex.getMessage()); }}
Returning Without CommittingIn a stateless session bean with bean-managed transactions, a business mmust commit or roll back a transaction before returning. However, a statefulsion bean does not have this restriction.
In a stateful session bean with a JTA transaction, the association betweebean instance and the transaction is retained across multiple client calls. Eveach business method called by the client opens and closes the database ction, the association is retained until the instance completes the transaction
SUMMARY OF TRANSACTIONOPTIONS 247
tainsultiple
ged
ctionnter-
-man-the
sac-
There. You
DBCse it
e’s ahen,will
In a stateful session bean with a JDBC transaction, the JDBC connection rethe association between the bean instance and the transaction across mcalls. If the connection is closed, the association is not retained.
Methods Not Allowed in Bean-ManagedTransactionsDo not invoke thegetRollbackOnly and setRollbackOnly methods of theEJBContext interface. These methods should be used only in container-manatransactions. For bean-managed transactions you invoke thegetStatus androllback methods of theUserTransaction interface.
Summary of Transaction OptionsThe decision tree in Figure 17 shows the different approaches to transamanagement that you may take. Your first choice depends on whether the eprise bean is an entity or a session bean. An entity bean must use containeraged transactions. With container-managed transactions, you specifytransaction attributes in the deployment descriptor and you roll back a trantion with thesetRollbackOnly method of theEJBContext interface. A sessionbean may have either container-managed or bean-managed transactions.are two types of bean-managed transactions: JDBC and JTA transactionsdelimit JDBC transactions with thecommit androllback methods of theCon-nection interface. To demarcate JTA transactions, you invoke thebegin, com-mit, androllback methods of theUserTransaction interface.
In a session bean with bean-managed transactions, it is possible to mix Jand JTA transactions. This practice is not recommended, however, becaucould make your code difficult to debug and maintain.
If you’re unsure about how to set up transactions in an enterprise bean, hertip: In the deployment descriptor specify container-managed transactions. Tset the Required transaction attribute for the entire bean. This approachwork most of the time.
248 TRANSACTIONS
erval
o
EJB
Figure 17 Options in Specifying Transactions
Transaction TimeoutsFor container-managed transactions, you control the transaction timeout intby setting the value of thetransaction.timeout property in the con-
fig/default.properties file. For example, you would set the timeout value t5 seconds as follows:
transaction.timeout=5
With this setting, if the transaction has not completed within 5 seconds, thecontainer manager rolls it back.
When J2EE is first installed, the timeout value is set to 0:
Enterprise Bean
Session Bean Entity Bean
Bean-Managed Transaction Container-Managed Transaction
JDBC Transaction JTA Transaction
declare tx attributes in deployment descriptor
invoke Connection methods in bean
invoke UserTransaction methods in bean
ISOLATION LEVELS 249
y theTA
ntsee to
mber,num-
mbertheata,
untilther
gedch is
, youer-d
h aiso-S
transaction.timeout=0
If the value is 0, the transaction will not time out.
Only enterprise beans with container-managed transactions are affected btransaction.timeout property. For enterprise beans with bean-managed, Jtransactions, you invoke thesetTransactionTimeout method of theUser-Transaction interface.
Isolation LevelsTransactions not only ensure the full completion (or rollback) of the statemethat they enclose, they also isolate the data modified by the statements. Thiso-lation level describes the degree to which the data being updated is visiblother transactions.
Suppose that a transaction in one program updates a customer’s phone nubut before the transaction commits another program reads the same phoneber. Will the second program read the updated and uncommitted phone nuor will it read the old one? The answer depends on the isolation level oftransaction. If the transaction allows other programs to read uncommitted dperformance may improve because the other programs don’t have to waitthe transaction ends. But there’s a tradeoff—if the transaction rolls back, anoprogram might read the wrong data.
You cannot modify the isolation level of a entity beans with container-manapersistence. These beans use the default isolation level of the DBMS, whiusuallyREAD_COMMITTED.
For entity beans with bean-managed persistence and for all session beanscan set the isolation level programmatically with the API provided by the undlying DBMS. A DBMS, for example, might allow you to permit uncommittereads by invoking thesetTransactionIsolation method:
Connection con;...con.setTransactionIsolation(TRANSACTION_READ_UNCOMMITTED);
Do not change the isolation level in the middle of a transaction. Usually, succhange causes the DBMS software to issue an implicit commit. Because thelation levels offered by DBMS vendors may vary, you should check the DBMdocumentation for more information.
250 TRANSACTIONS
xceptws anuresns-
ess, anddatesom-
ion.
ans-n-B,base-
Updating Multiple DatabasesThe J2EE transaction manager controls all enterprise bean transactions efor bean-managed JDBC transactions. The J2EE transaction manager alloenterprise bean to update multiple databases within a transaction. The figthat follow show two scenarios for updating multiple databases in a single traaction.
In Figure 18, the client invokes a business method in Bean-A. The businmethod begins a transaction, updates Database-X, updates Database-Yinvokes a business method in Bean-B. The second business method upDatabase-Z and returns control to the business method in Bean-A, which cmits the transaction. All three database updates occur in the same transact
Figure 18 Updating Multiple Databases
In Figure 19, the client calls a business method in Bean-A, which begins a traction and updates Database-X. Then, Bean-A invokes a method in Beawhich resides in a remote J2EE server. The method in Bean-B updates Data
Client
J2EE Server
Databases
Bean-A Bean-B
X Y Z
UPDATING MULTIPLE DATABASES 251
es are
Y. The transaction managers of the J2EE servers ensure that both databasupdated in the same transaction.Figure 19 Updating Multiple Databases Across J2EE Servers
Client
Databases
J2EE Server
Bean-A
X
J2EE Server
Bean-B
Y
252 TRANSACTIONS
ha-thisorta-rse
p andoper-id-in arityin a
con-ent
. The
onal-erenal-the
es-nt-
d thebil-for
Securityby Eric Jendrock
THE J2EE application programming model insulates developers from mecnism-specific implementation details of application security. J2EE providesinsulation in a manner that has the complementary affect of enhancing the pbility of applications in a way that the applications may be deployed in divesecurity environments.
The J2EE platform defines declarative contracts between those who develoassemble application components and those who configure applications inational environments. In the context of application security, application provers are required to declare the security requirements of their applicationsway that they may be satisfied during application configuration. The securequirements of an application are communicated in a declarative syntaxdocument called a deployment descriptor. An application deployer employstainer-specific tools to map application requirements captured in a deploymdescriptor to security mechanisms that are implemented by J2EE containersJ2EE SDK provides this functionality with thedeploytool.
In many cases, J2EE containers can provide an application's security functiity completely outside of the application implementation. In other cases, thmust be a programmatic aspect to realizing an applications security functioity. The declarative contract that accompanies an application must conveysecurity requirements of the application, including identifying where it is necsary to bind implementation-embedded security functionality to environmespecific mechanisms or values.
J2EE security mechanisms combine the concepts of container hosting andeclarative specification of application security requirements with the availaity of application-embedded mechanisms. This provides a powerful modelsecure, portable, distributed component computing.
253
254 SECURITY
ts
ton the
entictab-
-
tity
an
Authentication 254J2EE Users, Realms, and Groups 255Authentication Mechanisms 257Controlling Access to J2EE Resources 259Client Authentication 260Web Client Authentication 261Application Client Authentication 261Setting Component Security Identities 262Container Authentication 262Configuring EJB Target Security Requirements 263Configuring Resource Signon (Connectors) 264
Authorization 264Declaring Roles 265Declaring Method Permissions 265Declaring Role References 266Mapping Roles to J2EE Users and Groups 266Linking Role References to Roles 267Configuring J2SE Security Policy Files 267Determining the Caller Identity 267Making Portable Access Decisions Programmatically from Componen267
Protecting Messages 268Application Scenarios 268
J2EE Application Client 268Web Browser Client 268
AuthenticationAuthenticationis the mechanism by which callers and service providers proveone another that they are acting on behalf of specific users or systems. Wheproof is bidirectional, it is referred to asmutual authentication.Authenticationestablishes the call identities and proves that the participants are authinstances of these identities. An entity that participates in a call without eslishing or proving an identity (that is,anonymously), is calledunauthenticated.
When calls are made from a clientprogrambeing run by a user, the caller identity is likely to be that of theuser. When the caller is anapplication componentacting as an intermediary in a call chain that originated with a user, the idenmay be associated with that of the user. In this case, the componentimpersonatesthe user. Alternatively, one application component may call another withidentity of its own and unrelated to that of its caller.
AUTHENTICATION 255
ome
d or
enti-llow-an
d by
ntexte that
sersJ2EEvide
s noturity
tioncate
cli-tion
e is
kingept
Authentication is carried out in two phases:
1. Service-independent authentication that requires knowledge of ssecret is performed to establish anauthentication contextthat encapsulatesthe identity and is able to create proofs of identity, calledauthenticators.
2. The authentication context is then used to authenticate with other callecalling entities.
Controlling access to the authentication context, and thus the ability to authcate as the associated identity, becomes the basis of authentication. The foing policies and mechanisms can be used for controlling access toauthentication context:
• Once the user performs an initial authentication, all processes startethe user inherit access to the authentication context.
• When a component is authenticated, access to the authentication comay be available to other related or trusted components, such as thosare part of the same application.
• When a component is expected toimpersonateits caller, the caller maydelegateits authentication context to the called component.
J2EE Users, Realms, and GroupsA J2EE user is similar to an operating system user. Typically, both types of urepresent people. However, these two types of users are not the same. Theauthentication service has no knowledge of the user and password you prowhen you log on to the operating system. The J2EE authentication service iconnected to the security mechanism of the operating system. The two secservices manage users that belong to different realms.
A realm is a collection of users that are controlled by the same authenticapolicy. The J2EE authentication service governs users in two realms: certifiand default.
Certificates are used with the HTTPS protocol to authenticate web browserents. To verify the identity of a user in the certificate realm, the authenticaservice verifies a X509 certificate. For step-by-step instructions, seeSettingUp aServer Certificate (page 262). The common name field of the X509 certificatused as the principal name.
In most cases, the J2EE authentication service verifies user identity by checthe default realm. This realm is used for the authentication of all clients excfor web browser clients that use the HTTPS protocol and certificates.
256 SECURITY
cer-nn e-
ittion,ans.
Eand
, and
cer-
rd:
A J2EE user of the default realm may belong to J2EE group. (A user in thetificate realm may not.) Agroup is a category of users, classified by commotraits such as job title or customer profile. For example, most customers of acommerce application might belong to theCUSTOMER group, but the big spenderswould belong to thePREFERRED group. Categorizing users into groups makeseasier to control the access of large numbers of users. A later secAuthorization (page 264), discusses controlling user access to enterprise be
Managing J2EE Users and Groups
The realmtool utility is a command-line program that ships with the J2ESDK. You can use this utility to add to and remove users from the defaultcertificate realms.
To display all users in the default realm, type this command:
realmtool -list default
To add a user to the default realm, specify the-add flag. The following com-mand adds a user named rover who is protected by the password redincludes rover in the customer and preferred groups:
realmtool -add rover red customer,preferred
To add a user to the certificate realm, you import a file containing the X509tificate that identifies the user:
realmtool -import certificate-file
To remove a user, you specify the-remove flag. For example, to remove a usenamed tjones from the default realm, you would type the following comman
realmtool -remove default tjones
To add a group to the default realm, you specify the-addGroup flag. The follow-ing command adds the customer group:
realmtool -addGroup customer
You cannot add a group to the certificate realm.
To remove a group from the default realm, you specify the-removeGroup flag:
realmtool -removeGroup customer
AUTHENTICATION 257
ractble toished
ofds tost theandby antion
cu-riza-
urce,the
r thebeenurce.urce
acti-ainerstion,d, to
ser
along-wayient’sand
errm-
Authentication MechanismsIn a typical J2EE application, a user goes through a client container to intewith enterprise resources in the web or EJB tiers. Resources that are availathe user may be protected or unprotected. Protected resources are distinguby the presence ofauthorization rules, rules that restrict access to a subsetnon-anonymous identities. To access a protected resource, a user neepresent a non-anonymous credential so its identity can be evaluated againresource authorization policy. If a trust relationship between the clientresource containers does not exist, the credential must be accompaniedauthenticator that confirms its validity. This section describes authenticamechanisms that the J2EE platform supports and explains how to usedeploy-
tool to configure those mechanisms.
Web-Tier Authentication
You can protect a collection of web resources (web components, HTML doments, image files, compressed archives, and so on) by specifying an authotion constraint (described inControlling Accessto Web Resources (page 259))for the collection. If an anonymous user tries to access a protected web resothe web container will prompt that user for a password to authenticate withweb container. The request will only be accepted by the web container afteuser identity has been proven to the web container and that identity hasshown to be one of the identities granted permission to access the resoCaller authentication that is performed on the first access to a protected resois calledlazy authentication.
When you try to access a protected web-tier resource, the web containervates the authentication mechanism that has been defined. J2EE web contare required to support HTTP basic authentication, form-based authenticaand HTTPS mutual authentication, and are encouraged, but are not requiresupport HTTP digest authentication.
In basic authentication,the web server authenticates a principal using the uname and password obtained from the web client. Indigest authenticationa webclient authenticates to a web server by sending the server a message digestwith its HTTP request message. The digest is computed by employing a onehash algorithm to a concatenation of the HTTP request message and the clpassword. The digest is typically much smaller than the HTTP request,doesn’t contain the password.
Form-based authenticationlets developers customize the authentication usinterface presented by an HTTP browser. Like HTTP basic authentication, fo
258 SECURITY
ent asron-tica-tomspe-
b-tedion,sup-
ctor
ser
ge
sedtionntent,
ctor
based authentication is not secure, since the content of the user dialog is splain text, and the target server is not authenticated. In single-signon enviments, discretion must be exercised in customizing an application’s authention interface. It may be preferable to provide a single enterprise-wide cususer authentication interface, rather than implementing a set of application-cific interfaces.
With mutual authentication, the client and server use X.509 certificates to estalish their identity. Mutual authentication occurs over a channel that is protecby SSL. Hybrid mechanisms that feature either HTTP basic authenticatform-based authentication, or HTTP digest authentication over SSL are alsoported.
Configuring A Web Component’s Authentication Mechanism
To configure the authentication mechanism that a web component will use:
1. Select the web component in the tree view. The Web Component inspewill be displayed.
2. Select the Security tab.
3. Choose one of the following authentication mechanisms from the UAuthentication Method pulldown menu:
• Basic
• Form Based
• Client Certificate
• None
a. If you chose Basic authentication, you must enterDefault in the Realmname field.
b. If you chose Form Based authentication, you must fill in the Login Paand Error Page fields.
Using Hybrid Authentication to Enhance Confidentiality
Passwords are not protected for confidentiality with HTTP basic or form-baauthentication. To overcome this limitation, you can run these authenticaprotocols over an SSL-protected session and ensure that all message coincluding client authenticators, are protected for confidentiality.
To configure HTTP basic or form-based authentication over SSL:
1. Select the web component in the tree view. The Web Component inspewill be displayed.
AUTHENTICATION 259
have
ll-
ithurcespres-mousymous
pol-to
urity
.
ddcol-the
ant of
eitherof
thed to
2. From the Security tabbed pane, make sure that Basic or Form Basedbeen selected in the User Authentication Method menu pulldown.
3. Click on the Add button in the Security constraint section.
4. Click on the Security constraint that was added.
5. Select CONFIDENTIAL in the Network Security Requirement menu pudown.
Controlling Access to J2EE ResourcesIn a typical J2EE application, a client goes through its container to interact wenterprise resources in the web or EJB tiers. Protected and unprotected resomay be available to the user. Protected resources are distinguished by theence of authorization rules that restrict access to some subset of non-anonyidentities. To access a protected resource, a user must present a non-anoncredential so its identity can be evaluated against the resource authorizationicy. In other words, caller authentication is required any time a caller triesaccess a protected component.
Controlling Access to Web Resources
To control access to a web resource, you use the deploytool to specify a secconstraint:
1. Select the web component in the tree view.
2. Select the Security tabbed pane.
3. Click the Add button in the Security Constraints section of the screen
4. Click the Edit button adjacent to the Web Resource Collection field to aa web resource collection to the security constraint. the web resourcelection describes a URL pattern and HTTP method pair that refer toresources that need to be protected.
5. Click the Edit button adjacent to the Authorized Roles field to addauthorization constraint to the security constraint. You specify the seroles that can access the web resource collection.
6. From the Transport Guarantee menu, select the user data constraint,None, Integral, or Confidential. This setting indicates with what degreeprotection the resource can be accessed.
Controlling Access to Enterprise Beans
If you defined security roles for an enterprise bean, you can also specifymethods of the remote and home interface that each security role is allowe
260 SECURITY
henticated
allerprisee of acessre-ittedation.
ents:ts.
dowation
serfter
cli-
ductso,to
ctedtheirn, the
invoke. This is done in the form ofmethod-permission elements. Ultimately, it isthe assignment of users to roles that determines if a resource is protected. Wthe roles required to access the enterprise bean are assigned only to authenusers, the bean is protected.
Unprotected Resources
Many applications feature unprotected web-tier content, available to any cwithout authentication. Some applications also feature unprotected enterbeans. In either tier, unprotected resources are characterized by the absencrequirement that their caller be authenticated. In the web tier, unrestricted acis provided simply by leaving out an authentication rule. In the EJB tier, unstricted access is accomplished by mapping at least one role, which is permaccess to the resource, to the universal set of users independent of authentic
Client AuthenticationThe J2EE authentication service controls access from all types of bean cliJ2EE application clients, stand-alone Java applications, and web componen
When a J2EE application client starts running, its container pops open a winthat requests the J2EE user name and password. If you run the J2EE applicclient described inRunningtheJ2EE™ApplicationClient (page 58) you’ll seethis log-on window in action. The authentication service verifies that the uname and password from the log-on window exist in the default realm. Aauthentication, the user’s security context is associated with any call that theent makes to enterprise beans deployed in the J2EE server.
Many applications do not require authentication. For example, an online procatalog would not force customers to log on if they are merely browsing. Alwhen you first start developing an application, you may find it convenientallow an unauthenticated and anonymous user namedguest to access the appli-cation’s components.
During deployment, you specify whether or not a web component is a proteresource. If the web component is unprotected, anyone may access it frombrowser. If an unprotected web component accesses an enterprise beaauthentication service assigns it a certificate for theguest user. Any subsequentcalls to enterprise beans are associated with theguest user.
AUTHENTICATION 261
possi-o set
theirs tons,tectpro-
tion.
ha-
. Iton-
m,tion
ent
li-
ion
Auto-Registration of Users
Many e-commerce applications have been designed to make it as easy asble for a user to become a customer. Instead of waiting for an administrator tup a user’s account, many e-commerce applications enable users to set upown accounts without any administrative intervention. A user usually needprovide his or her identity and location, agree to some contractual obligatioprovide credit card information for payment, and establish a password to prothe account. After completing the registration dialog, the user can access thetected resources of the site.
The J2EE platform does not specify mechanisms to support auto-registraTherefore, these mechanisms are specific to the container implementation.
Web Client AuthenticationThis section will describe how to declare the web tier authentication mecnisms.
Data Protection
TBD. This section will describe how to use SSL to provide data protectionwill talk about declaring data protection in the web tiers and explain the relatiship between data protection and authentication.
Developing a Custom Web Tier User Authentication Interface
TBD. After briefly describing the form-based login authentication mechanisthis section will describe how to create a custom web-tier user authenticainterface and explain how to install the interface.
Application Client AuthenticationTBD. This section will describe the declarative aspects of application cliauthentication.
This section will also explain how to configure a JAAS login module in an appcation client.
Application client authentication to the web tier will be shown, but the sectwill concentrate on application client authentication to the EJB tier.
262 SECURITY
ing
ub-rding
ithSSL.
cli-rtifi-ps:
hipsro-hasort
his
Setting Component Security IdentitiesTBD. This section will explain the configuration and declaration aspects of usrun-as-specified-identity andRunAs caller.
Capturing a Security Context (Servlet)
TBD. This section will describe how to set up a servlet security context for ssequent EJB invocations. This is done by using the session object, and recothe session id in the servlet, so that you can use it.
Container AuthenticationTBD. This section will describe how a container authenticates to its clients wthe J2EE SDK for a web server using SSL and an EJB server using CSIV2/
Setting Up a Server Certificate
Certificates are used with the HTTPS protocol to authenticate web browserents. The HTTPS service of the J2EE server will not run unless a server cecate has been installed. To set up a J2EE server certificate, follow these ste
1. Generate a key pair and a self-signed certificate.
Thekeytool utility enables you to create the certificate. Thekeytool util-ity that ships with the J2EE SDK has the same syntax as the one that swith the Java 2™ Standard Edition. However, the J2EE SDK version pgrammatically adds a Java™ Cryptographic Extension provider thatimplementations of RSA algorithms. This provider enables you to impRSA signed certificates.
To generate the certificate, run thekeytool utility as follows, substituting<certificate-alias> with the alias of your certificate:
keytool -genkey -keyalg RSA -alias <certificate-alias>
2. Thekeytool utility prompts you for the following information:
a. keystore password - The default value of this password ischangeit.You can change the password by editing theconfig/auth.properties
file.
b. first and last name - Enter the fully-qualified name of your server. Tfully-qualified name includes the host name and the domain name.
c. organizational unit - Enter the appropriate value.
d. organization - Enter the appropriate value.
AUTHENTICATION 263
is
rayA,
file.
runs
a
:
re-
e. city or locality - Enter the appropriate value.
f. state or province - Enter the unabbreviated name.
g. two-letter country code - For the USA, the two-letter country codeUS.
h. key password for alias - Do not enter a password. Press Return.
3. Import the certificate.
If your certificate will be signed by a Certification Authority (CA) othethan Verisign, you must import the CA certificate. Otherwise, you mskip this step. (Even if your certificate will be signed by verisign Test Cyou must import it.)
To import the certificate, perform these tasks:
a. Request the CA certificate from your CA. Store the certificate in a
b. To install the CA certificate in the Java 2 Platform, Standard Edition,thekeytool utility as follows. (You must have the required permissionto modify the$JAVA_HOME/jre/lib/security/cacerts file.)
keytool -import -trustcacerts -alis <ca-cert-alias> -file <ca-cert-filename>
4. Generate a Certificate Signing Request (CSR).
keytool -certreq -sigalg MD5withRSA -alias <cert-alias> -file<csr-filename>
5. Send the contents of the<csr-filename> for signing
If you are using Verisign CA, go tohttp://digitalid.verisign.com/.Verisign will send the signed certificate in email. Store this certificate infile.
6. Import the signed certificate that you recieved in email into the server
keytool -import -alias <cert-alias> -file <signed-cert-file>
Configuring EJB Target Security RequirementsTBD. This section will describe how to configure EJB target security requiments in relation to authentication and message protection.
264 SECURITY
theJBged
ofail-to
ed toand
ingallednet ofllerthe
den-In
butesen-tes
hips)andetherfritythe
nt.
daryxistssid-iner
ntrol
Configuring Resource Signon (Connectors)TBD. This section will describe how to plug a connector into a container, forJ2EE SDK. It will explain how to declare the use of the container in the Edeployment descriptor. The section will also describe how to do bean-manaprogrammatic resource sign on via the connector.
AuthorizationAuthorizationmechanisms limit interactions with resources to collectionsusers or systems for the purpose of enforcing integrity, confidentiality, or avability constraints. Such mechanisms allow only authentic caller identitiesaccess components. Mechanisms provided by the J2SE platform can be uscontrol access to code based on identity properties, such as the locationsigner of the calling code. In the J2EE distributed component programmmodel, additional authorization mechanisms are required to limit access to ccomponents based on who isusingthe calling code. As mentioned in the sectioon authentication, caller identity can be established by selecting from the sauthentication contexts available to the calling code. Alternatively, the camay propagate the identity of its caller, select an arbitrary identity, or makecall anonymously.
In all cases, a credential is made available to the called component. The cretial contains information describing the caller through its identity attributes.the case of anonymous callers, a special credential is used. These attriuniquely identify the caller in the context of the authority that issued the credtial. Depending on the type of credential, it may also contain other attribuwhich define shared authorization properties (for example, group membersthat distinguish collections of related credentials. The identity attributesshared authorization attributes appearing in the credential are referred to togas the caller’ssecurity attributes.In the J2SE platform, the identity attributes othe code used by the caller may also be included in the caller’s secuattributes. Access to the called component is determined by comparingcaller’s security attributes with those required to access the called compone
In the J2EE architecture, a container serves as an authorization bounbetween callers and the components it hosts. The authorization boundary einside the container’s authentication boundary, so that authorization is conered in the context of successful authentication. For inbound calls, the contacompares security attributes from the caller’s credential with the access co
AUTHORIZATION 265
th-
do.plica-, the
of
s ofht bee user
copea role
po-te a
f anoke
th-
ole
rules for the target component. If the rules are satisfied, the call is allowed. Oerwise, the call is rejected.
There are two fundamental approaches to defining access control rules:capabili-tiesandpermissions. The capabilities approach focuses on what a caller canThe permissions approach focuses on who can do something. The J2EE aption programming model focuses on permissions. In the J2EE architectureDeployer maps the permission model of the application to the capabilitiesusers in the operational environment.
Declaring RolesWhen you design an enterprise bean, you should keep in mind what typeusers will access the bean. For example, an Account enterprise bean migaccessed by customers, bank tellers, and branch managers. Each of thescategories is called a role.
A J2EE group also represents a category of users, but it has a different sthan a role. A J2EE group is designated for the entire J2EE server, whereascovers only a specific application in a J2EE server.
To create a role for an application, you declare it for the EJB JAR or web comnent WAR files that are contained in the application. For example, to crearole for an enterprise bean, follow this procedure in the deploytool:
1. In the tree view, select the enterprise bean’s EJB JAR file.
2. In the Roles tabbed pane, click Add.
3. In the table, enter values for the Name and Description fields.
Declaring Method PermissionsAfter you’ve defined the roles, you can define the method permissions oenterprise bean. Method permissions indicate which roles are allowed to invwhich methods.
You usedeploytool to specify method permissions by mapping roles to meods:
1. Select the enterprise bean in the tree view.
2. Select the Security tabbed pane.
3. In the Method Permissions table, select a role’s checkbox if that rshould be allowed to invoke a method.
266 SECURITY
byis
s, in
ref-ppli-
umn.
ot
rop-
opri-
yourer-or offaultuserle.
by
ole
Declaring Role ReferencesA security role is an application-specific logical grouping of users, classifiedcommon traits such as customer profile or job title. When an applicationdeployed, roles are mapped to security identities, such as principals or groupthe operational environment.
A security role reference references a security role name. This security roleerence is linked to the security role name that is defined for an assembled acation.
To add a security role reference, you usedeploytool:
1. Select the enterprise bean in the tree view.
2. Select the Security tabbed pane.
3. Click the Add button.
4. Enter the name of the security role reference in the Coded Name col
5. Click Edit Roles if the security role name to which you want to map is nlisted in the Role Name column.
6. Select the security role name that maps to the coded name from the ddown menu in the Role Name column.
7. Indicate which role has access to which methods by selecting the apprate checkboxes in the Method permissions panel.
Mapping Roles to J2EE Users and GroupsWhen you are developing an enterprise bean, you should know the roles ofusers, but you probably won’t know exactly who the users will be. That’s pfectly all right, because after your bean has been deployed, the administratthe J2EE server will map the roles to the J2EE users (or groups) of the derealm. In the Account bean example, the administrator might assign theSally to the Manager role, and the users Bob, Ted, and Clara to the Teller ro
Using deploytool, the administrator maps roles to J2EE users and groupsfollowing these steps:
1. In the tree view, select the J2EE application.
2. In the Security tabbed pane, select the appropriate role from the RName list.
3. Click Add.
AUTHORIZATION 267
ng to-line
heNEs of
,
is-
kingined
byivi-testare
4. In the Users dialog box, select the users and groups that should belothe role. (The users and groups were created with the commandrealmtool.)
By default, the Role Name table assigns the ANYONE role to a method. Tguest user, which is anonymous and unauthenticated, belongs to the ANYOrole. Therefore, if you do not map the roles, any user may invoke the methodan enterprise bean.
Linking Role References to RolesTBD.
Configuring J2SE Security Policy FilesThe J2EE server policy file is namedserver.policy. It resides in the$J2EE_HOME/lib/security directory. The J2EE application client policy fileclient.policy, resides in the same directory.
For more information on setting up security policy files to grant required permsions, see Security in JDK 1.2.
Determining the Caller IdentityTBD.
Making Portable Access DecisionsProgrammatically from ComponentsTBD. This section will describe how to use theisCallerInRole method fromcomponents. This section is related to a previous section that described linrole references. We may want to talk about portable ways to do finer-grascoping of programmatic enforcement of access control policy. This is doneselecting the right role/privilege to test for. By embedding the name of the prlege to test for in the component state, and possibly even going so far as tothat the caller is a one or more of a set of specific principals whose namescapture in the state of the component.
268 SECURITY
ns-ct to
ging
nefit
ture
ha-
lity
tions
Protecting MessagesIn a distributed computing system, a significant amount of information is tramitted through networks in the form of messages. Message content is subjethree main types of attacks:
• Messages might be intercepted and modified for the purpose of chanthe affects they have on their recipients.
• Messages might be captured and reused one or more times for the beof another party.
• Messages might be monitored by an eavesdropper in an effort to capinformation that would not otherwise be available.
Such attacks can be minimized by using integrity and confidentiality mecnisms.
TBD. Sections will be added that explain how to use integrity and confidentiamechanisms to protect message content.
Application ScenariosTBD.
This section may show an example with sort of a chinese menu of subsecthat could all be used in various combinations.
J2EE Application ClientTBD.
Web Browser ClientTBD.
ty ofts, andll of
nnec-apter
ResourceConnections
by Dale Green
BOTH enterprise beans and web components can access a wide varieresources, including database, mail sessions, Java Message Service objecURLs. The J2EE™ platform provides mechanisms that allow you to access athese resources in a similar manner. This chapter describes how to get cotions to several types of resources. Although the code examples in this chare from enterprise beans, they will also work in web components.
JNDI Names and Resource References 272Definitions 272Specifying a Resource Reference 272Mapping a Resource Reference to a JNDI Name 273
Database Connections for Enterprise Beans 273Coded Connections 273Container-Managed Connections 275Connection Pooling 275
Mail Session Connections 276Tips for Running the ConfirmerEJB Example 277
URL Connections 278Tips for Running the HTMLReaderEJB Example 279
269
270 RESOURCECONNECTIONS
d toEEI, we
heame
fac-tworces.a dif-ilityting
t.eed
JNDI Names and Resource References
DefinitionsA JNDI nameis a people-friendly name for an object. These names are bountheir objects by the naming and directory service that is provided by the J2server. Because J2EE components access this service through the JNDI APusually refer to an object’s people-friendly name as its JNDI name.
A resource referenceis an element in a deployment descriptor that identifies tcomponent’s coded name for the resource. More specifically, the coded nidentifies a connection factory for the resource.
Although both the coded and the JNDI name identify the same connectiontory, they are different. This approach to naming requires that you map thenames before deployment, but it also decouples components from resouBecause of this decoupling, if at a later time the component needs to accessferent resource, you don’t have to change the name in the code. This flexibalso makes it easier for you to assemble J2EE applications from pre-exiscomponents.
Specifying a Resource ReferenceThe instructions that follow mention theAccountEJB example, which isdescribed in the section,A Bean-ManagedPersistenceExample (page 83). TheAccountEJB code is in theexamples/src/ejb/account directory.
1. In thedeploytool, select the component from the tree.
2. Select the Resource Ref’s tab.
3. Click Add.
4. In the Coded Name field, enterjdbc/AccountDB.
TheAccountEJB refers to the database as follows:
private String dbName = “java:comp/env/jdbc/AccountDB”;
The java:comp/env prefix is the JNDI subcontext for the componenBecause this subcontext is implicit in the Coded Name field, you don’t nto include it there.
5. In the Type combo box, select javax.sql.DataSource. ADataSource objectis a factory for database connections.
DATABASE CONNECTIONS FORENTERPRISEBEANS 271
nce.
tab.
tion
to
codethatbeans
s. For
6. In the Authentication combo box, select Container.
Mapping a Resource Reference to a JNDI Name1. Select the J2EE application from the tree.
2. Select the JNDI Names tab.
3. In the References table, select the row containing the resource refereFor theAccountEJB example, the resource reference isjdbc/AccountDB,the name you entered in the Coded Name field of the Resource Ref’s
4. In the row you just selected, enter the JNDI name. For theAccountEJB
example, you would enterjdbc/Cloudscape in the JNDI Name field.
When it starts up, the J2EE server reads information from a configurafile and adds JNDI database names such asjdbc/Cloudscape to the namespace. To edit the configuration file, select Tools->Configuration and gothe Data Sources node.
Database Connections for Enterprise BeansThe persistence type of an enterprise bean determines whether or not youthe connection routine. You must code the connection for enterprise beansaccess a database and do not have container-managed persistence. Suchinclude entity beans with bean-managed persistence and session beanentity beans with container-managed persistence, thedeploytool generates theconnect routines for you.
Coded Connections
How to Connect
The code examples in this section are from theAccountEJB class, which con-nects to the database with the following steps:
1. Specify the database name.
private String dbName = “java:comp/env/jdbc/AccountDB”;
2. Obtain theDataSource associated with the logical name.
InitialContext ic = new InitialContext();DataSource ds = (DataSource) ic.lookup(dbName);
272 RESOURCECONNECTIONS
tainforiceto a
secon-therue the
-
t
passi-n isin thises not
, see
on-rebase
3. Get theConnection from theDataSource.
Connection con = ds.getConnection();
When To Connect
When coding a component, you must decide how long the component will rethe connection. Generally you have two choices: either hold the connectionthe lifetime of the component, or only during each database call. Your chodetermines the method (or methods) in which your component connectsdatabase.
Longterm Connections. You can design a component that holds a databaconnection for its entire lifetime. Because the component connects and disnects just once, its code is slightly easier to write. But there’s a tradeoff—ocomponents may not acquire the connection. Session and entity beans isslifelong connections in different methods.
Session Beans:
The EJB™ container invokes theejbCreate method at the beginning of a session bean’s life cycle, and invokes theejbRemove method at the end. To retain aconnection for the lifetime of a session bean, you connect to the database inejb-
Create and disconnect inejbRemove. If the session bean is stateful, you musalso connect inejbActivate and disconnect inejbPassivate. A stateful ses-sion bean requires these additional calls because the EJB container mayvate the bean during its lifetime. During passivation, a stateful session beasaved in secondary storage, but a database connection may not be savedmanner. Because a stateless session bean cannot be passivated, it dorequire the additional calls inejbActivate andejbPassivate. For more infor-mation on activation and passivation, seeTheLife Cycleof aSessionBean (page74). For an example of a stateful session bean with a longterm connectiontheTellerEJB.java code.
Entity Beans:
After instantiating an entity bean and moving it to the pooled stage, the EJB ctainer invokes thesetEntityContext method. Conversely, the EJB containeinvokes theunsetEntityContext method when the entity bean leaves thpooled stage and becomes eligible for garbage collection. To retain a dataconnection for its entire life span, an entity bean connects in thesetEntityCon-
text method and disconnects in theunsetEntityContext method. To see a dia-gram of the life cycle, refer toTheLife Cycleof anEntity Bean (page 116). For
DATABASE CONNECTIONS FORENTERPRISEBEANS 273
the
sool ofe con-sert a
e trans-
o notarate
con-
bean,ncede bot-
u do-
ol isonnec-auseets a
an example of an entity bean with a longterm connection, seeAccountEJB.java code.
Shortterm Connections. Briefly held connections allow many componentto share the same connection. Because the EJB container manages a pdatabase connections, enterprise beans can quickly obtain and release thnections. For example, a business method might connect to a database, inrow, and then disconnect.
In a session bean, a business method that connects to a database should bactional. The transaction will help maintain data integrity.
Specifying Database Users and Passwords
To connect to the Cloudscape database bundled with this release, you dspecify a database user and password. Authentication is performed by a sepservice. For more information about authentication, see the chapter onSecurity(page 253).
However, some types of databases do require a user and password duringnection. For these databases, if thegetConnection call has no parameters, youmust specify the database user and password with thedeploytool. To specifythese values, click on the Resource Ref’s tabbed pane of the enterpriseselect the appropriate row in the table labelled, “Resource Factories Referein Code,” and enter the database user name and password in the fields at thtom.
If you wish to obtain the database user and password programmatically, yonot need to specify them with thedeploytool. In this case, you include the database user and password in the arguments of thegetConnection method:
con = dataSource.getConnection(dbUser, dbPassword);
Container-Managed ConnectionsTBD
Connection PoolingThe EJB container maintains the pool of database connections. This potransparent to the enterprise beans. When an enterprise bean requests a ction, the container fetches one from the pool and assigns it to the bean. Becthe time-consuming connection has already been made, the bean quickly g
274 RESOURCECONNECTIONS
, sincennec-any
and
on-thef
connection. The bean may release the connection after each database callit can rapidly get another connection. And because such a bean holds the cotion for a short time, the same connection may be shared sequentially by mbeans.
Mail Session ConnectionsIf you’ve ever ordered a product from a web site, you’ve probably receivedemail confirming your order. TheConfirmerEJB class demonstrates how to senemail from an enterprise bean.
The source code for this example is in theexamples/src/ejb/confirmer direc-tory. To compile the code, go to theexamples/src directory and typeant con-
firmer.
In the sendNotice method of theConfirmerEJB class, thelookup methodreturns aSession object, which represents a mail session. Like a database cnection, a mail session is a resource. As with any resource, you must linkcoded name (TheMailSession) with a JNDI name in the Resource Ref’s tab othedeploytool. (See Table 30.) Using theSession object as an argument, thesendNotice method creates an emptyMessage object. After calling severalsetmethods on theMessage object,sendNotice invokes thesend method of theTransport class to send the message on its way. The source code for thesend-
Notice method follows:
public void sendNotice(String recipient) {
try { Context initial = new InitialContext(); Session session = (Session) initial.lookup( “java:comp/env/TheMailSession”);
Message msg = new MimeMessage(session); msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
msg.setSubject(“Test Message from ConfirmerEJB”);
DateFormat dateFormatter = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.SHORT);
MAIL SESSIONCONNECTIONS 275
f
e for
Date timeStamp = new Date();
String messageText = “Thank you for your order.” + `\n’ + “We received your order on “ + dateFormatter.format(timeStamp) + “.”;
msg.setText(messageText); msg.setHeader(“X-Mailer”, mailer); msg.setSentDate(timeStamp);
Transport.send(msg);
} catch(Exception e) { throw new EJBException(e.getMessage()); }}
Tips for Running the ConfirmerEJB Example1. Before compiling theConfirmerClient.java program, change the value o
the recipient variable to an actual email address.
2. In the Resource Ref’s tab of the bean, specify the resource referencthe mail session with the values in the following table.
Table 29 ResourceRef’s for theConfirmerEJB Example
Dialog Field Value
Coded Name TheMailSession
Type javax.mail.Session
Authentication Application
From (your email address)
Host (mail server host)
User Name(your UNIX or Windowsuser name)
276 RESOURCECONNECTIONS
ep-
’ve.
then
3. Use the JNDI names listed in the following table.
If the application cannot connect to the mail server it will generate this exction:
javax.mail.MessagingException: Could not connect to SMTP host
To fix this problem, make sure that the mail server is running and that youentered the correct name for the mail server host in the Resource Ref’s tab
URL ConnectionsA Uniform Resource Locator (URL) specifies the location of a resource onWeb. TheHTMLReaderEJB class shows how to connect to a URL from within aenterprise bean.
The source code for this example is in theexamples/src/ejb/htmlreaderdirectory. To compile the code, go to theexamples/src directory and typeanthtmlreader.
The getContents method of theHTMLReaderEJB class returns aString thatcontains the contents of an HTML file. This method looks up thejava.net.URL
object associated with a coded name (url/MyURL), opens a connection to it, andthen reads its contents from anInputStream. Before deploying the application,you must map the coded name (url/MyURL) to a JNDI name (a URL string).Here is the source code for thegetContents method:
public StringBuffer getContents() throws HTTPResponseException{
Context context; URL url;
Table 30 JNDI Names for theConfirmerEJB Example
Component orReference Name JNDI Name
ConfirmerBean MyConfirmer
TheMailSession MyMailer
URL CONNECTIONS 277
StringBuffer buffer; String line; int responseCode; HttpURLConnection connection; InputStream input; DataInputStream dataInput;
try { context = new InitialContext(); url = (URL)context.lookup(“java:comp/env/url/MyURL”); connection = (HttpURLConnection)url.openConnection(); responseCode = connection.getResponseCode(); } catch (Exception ex) { throw new EJBException(ex.getMessage()); }
if (responseCode != HttpURLConnection.HTTP_OK) {throw new HTTPResponseException(“HTTP response code: “ +
String.valueOf(responseCode)); }
try { buffer = new StringBuffer(); input = connection.getInputStream(); dataInput = new DataInputStream(input); while ((line = dataInput.readLine()) != null) { buffer.append(line); buffer.append(`\n’); } } catch (Exception ex) { throw new EJBException(ex.getMessage()); }
return buffer;}
Tips for Running the HTMLReaderEJB Example1. Include theHTTPResponseException class in the enterprise bean.
278 RESOURCECONNECTIONS
inge
the.
n-
2. In the Resource Ref’s tab of the bean, specify the values in the followtable. Replace the<host> string with the name of the host running thJ2EE server.
3. Use the JNDI names listed in the following table. The JNDI name forurl/MyURL entry should match the URL field of the Resource Ref’s tab
The URL specified in the preceding tables refers to the defaultpublic_html/
index.html file of your J2EE SDK installation.
To connect to a URL outside of your firewall, you must perform these tasks:
1. Exit thedeploytool.
2. Stop the J2EE server.
3. In thebin/j2ee script, add the following options to the PROPS enviroment variable. The<port> is the proxy’s port number and<host> is thename of your proxy host.
-Dhttp.proxyPort=<port> -Dhttp.proxyHost=<host>
Table 31 Resource Ref’s for the HTMLReaderEJB Example
Dialog Field Value
Coded Name url/MyURL
Type java.net.URL
Authentication Container
URL http://<host>:8000/index.html
Table 32 JNDI Names for the HTMLReaderEJB Example
Component Type orReference Name JNDI Name
HTMLReaderBean MyHTMLReader
url/MyURL http://<host>:8000/index.html
URL CONNECTIONS 279
4. In thelib/security/Server.policy file, find the following line:
permission java.net.SocketPermission “*:0-65535”, “connect”;
Edit the line so that it appears as follows:
permission java.net.SocketPermission “*”, “connect”;
5. Start the J2EE server.
6. Start thedeploytool.
280 RESOURCECONNECTIONS
lop-tools
ectornot ae to
rpriseareain-J2EEachgy.
J2EE™ConnectorTechnology
by Dale Green and Beth Stearns
THE other chapters in this book are intended for business application deveers, but this chapter is for advanced users such as system integrators anddevelopers. The examples in this chapter demonstrate the J2EE™ ConnTechnology by accessing relational databases. However, this technology issubstitute for the JDBC API. Business application developers should continuuse the JDBC™ API to access relational databases.
The J2EE Connector Technology enables J2EE components such as entebeans to interact with Enterprise Information Systems (EIS). EIS softwincludes various types of systems: Enterprise Resource Planning (ERP), mframe transaction processing, non-relational database, among others. TheConnector Technology simplifies the integration of diverse EIS systems. EEIS requires just one implementation of the J2EE Connector TechnoloBecause an implementation adheres to theJ2EE Connector Specification, it isportable across all compliant J2EE servers.
About Resource Adapters 284Resource Adapter Contracts 284Administering Resource Adapters 285
The Black Box Resource Adapters 287Transaction Levels 287Properties 288Configuring JDBC™ Drivers 289
281
282 J2EE™CONNECTORTECHNOLOGY
ector2EE
y be. A
APIJ2EEriver,lica-who
pter.uchmpo-trans-
nec-
niqueg is.
Resource Adapter Tutorial 290Setting Up 290Deploying the Resource Adapter 290Testing the Resource Adapter 291
Common Client Interface (CCI) 293Overview of the CCI 293Programming with the CCI 295Writing a CCI Client 304CCI Tutorial 304
About Resource AdaptersA resource adapter is a J2EE component that implements the J2EE ConnTechnology for a specific EIS. It is through the resource adapter that a Japplication communicates with an EIS. (See Figure 20.)
Stored in a RAR (Resource adapter ARchive) file, a resource adapter madeployed on any J2EE server, much like the EAR file of a J2EE applicationRAR file may be contained in a EAR file or it may exist as a separate file.
A resource adapter is analagous to a JDBC driver. Both provide a standardthrough which an application can access a resource that is outside of theserver. For a resource adapter, the outside resource is an EIS; for a JDBC dit is a DBMS. Resource adapters and JDBC drivers are rarely created by apption developers. In most cases, both types of software are built by vendorssell products such as tools, servers, or integration software.
Resource Adapter ContractsFigure 20 shows the two types of contracts implemented by a resource adaThe application contract defines the API through which a J2EE component sas an enterprise bean accesses the EIS. This API is the only view that the conent has of the EIS. The resource adapter itself and its system contracts areparent to the J2EE component.
The system contracts link the resource adapter to important services—contion, transaction, and security—that are managed by the J2EE server.
The connection management contract supports connection pooling, a techthat enhances application performance and scalability. Connection poolintransparent to the application, which simply obtains a connection to the EIS
ABOUT RESOURCEADAPTERS 283
y betainhods., andual
idesation
Because of the transaction management contract, calls to the EIS maenclosed in a XA transactions. XA transactions are global—they may concalls to multiple EISs, databases, and enterprise bean business metAlthough often appropriate, XA transactions are not mandatory. Insteadapplication may use local transactions, which are managed by the indiviEIS, or it may use no transactions at all.
To protect the information in an EIS, the security management contract provthese mechanisms: authentication, authorization, and secure communicbetween the J2EE server and the EIS.
Figure 20 Accessing an EIS Through a Resource Adapter
Administering Resource AdaptersInstalling a resource adapter is a two-step process:
1. Deploy the RAR file containing the resource adapter onto a server.
J2EE Server
Enterprise Bean
EISResource Adapter
Web Component
Transaction Connection Security
Managers:System Contracts
Application Contract
Application Contract
284 J2EE™CONNECTORTECHNOLOGY
rcemit
urce
add
urce
The following command, for example, deploys a sample black box resouadapter onto the local host. (For Windows, in the following commands othe backslash character, change$J2EE_HOME to %J2EE_HOME%, and enter theentire command on a single line.)
deploytool -deployConnector \$J2EE_HOME/lib/connector/cciblackbox-tx.rar \localhost
2. Add a connection factory for the resource adapter.
Suppose that you wanted to add a connection factory for the resoadapter in thecciblackbox-tx.rar file. The JNDI name of the connectionfactory will beeis/MyCciBlackBoxTx. To override the default value of theproperty namedConnnectionURL, you specify the URL of a database. (Aproperty is a name-value pair used to configure a connection factory.) Tothe connection factory, you might enter the followingj2eeadmin command:
j2eeadmin -addConnectorFactory \eis/MyCciBlackBoxTx \cciblackbox-tx.rar \-props \ConnectionURL=jdbc:oracle:thin:@myhost:1521:ACCTDB
For the full syntax of thedeploytool and j2eeadmin commands, seeJ2EE™SDKTools (page 309). These commands also list and remove resoadapters and connection factories.
To list the resource adapters that have been deployed:
deploytool -listConnectors localhost
To list the connection factories that have been added:
j2eeadmin -listConnectorFactory
To uninstall the resource adapter deployed in step 1:
deploytool -undeployConnector \$J2EE_HOME/lib/connector/cciblackbox-tx.rar \localhost
To remove the connection factory added in step 2:
j2eeadmin -removeConnectorFactory eis/MyCciBlackBoxTx
THE BLACK BOX RESOURCEADAPTERS 285
end-ela-
to
ntforng
hat
The Black Box Resource AdaptersThe J2EE SDK includes several black box resource adapters for performingto-end and compatibility testing. The underlying EIS of these adapters is a rtional DBMS. The client API is the JDBC 2.0 API and thejavax.sql.Data-Source interface. Underneath, the black box adapters use JDBC driverscommunicate with relational databases. For more information, seeConfiguringJDBC™ Drivers (page 287).
Note: Although the black box adapters use JDBC, resource adapters are not meato replace JDBC for accessing relational databases. The black box adapters aretesting purposes only. Because they use JDBC, they can be plugged into existitests that also use JDBC.
Transaction LevelsThe black box resource adapters reside in the$J2EE_HOME/lib/connector
(Unix) or %J2EE_HOME%\lib\connector (Windows) subdirectory. The follow-ing table lists the blackbox RAR files and the different transaction levels tthey support:
For theXA_TRANSACTION level, the underlying JDBC driver must support the XArequirements as defined by the JDBC 2.0 API.
Table 33 Black Box Transaction Levels
File Transaction Level
blackbox-notx.rar NO_TRANSACTION
blackbox-tx.rar LOCAL_TRANSACTION
blackbox-xa.rar XA_TRANSACTION
cciblackbox-tx.rar LOCAL_TRANSACTION
cciblackbox-xa.rar XA_TRANSACTION
286 J2EE™CONNECTORTECHNOLOGY
nfor-rtiesthe
nfor-rop-
ction
PropertiesA resource adapter may contain properties, name-value pairs containing imation specific to the resource adapter and its underlying EIS. These propeare defined in the deployment descriptor of each blackbox RAR file. BecauseEIS of a blackbox adapter is a relational database, the properties contain imation required for connecting to a database. The following table lists the perties of the black box adapter files.
The next table shows the default values for the black box properties.
To override a default property value, you set the value when adding a connefactory with thej2eeadmin command. See the section,AdministeringResourceAdapters (page 283).
Table 34 Black Box Properties
File Property Name Description
blackbox-notx.rar ConnectionURL URL of database
blackbox-tx.rar ConnectionURL URL of database
blackbox-xa.rar XADataSourceNameJNDI name ofXADataSource
cciblackbox-tx.rar ConnectionURL URL of database
cciblackbox-xa.rar XADataSourceNameJNDI name ofXADataSource
Table 35 Default Values for Black Box Properties
Property Name Description
ConnectionURL jdbc:cloudscape:rmi:CloudscapeDB;create=true
XADataSourceName jdbc/XACloudscape_xa
THE BLACK BOX RESOURCEADAPTERS 287
, you, you
his
he
heentax
ets
nd
Configuring JDBC™ DriversIf you are running the black box adapters against a Cloudscape databasemay skip this section. If you are using a database other than Cloudscapeshould perform the steps that follow.
The Non-XA Black Box Adapters
1. Set the JDBC driver class. Use thej2eeadmin tool with the -addJdb-
cDriver option and specify the driver class name. The syntax for toption is:
j2eeadmin -addJdbcDriver <class name>
2. Edit the bin/userconfig.sh (UNIX) or bin\userconfig.bat (Win-dows) file, setting the J2EE_CLASSPTH variable to the location of tJDBC driver classes.
3. Restart the J2EE server.
The XA Black Box Adapters
1. Set theXADatasource property. With thej2eeadmin tool and theaddJd-bcXADatasource option, specify the JNDI name and class name for tXADatasource property. Optionally, you may specify the XA user namand password and you may override the default property value. The syfollows:
j2eeadmin -addJdbcXADatasource <jndi name> <class name>[<xa user name> <xa password>][-props (<name>=<value>)+]
The preceding command results in two data sources. One is aDataSource
object with the specified JNDI name from which the J2EE application gaConnection instance. The other is anXADatasource object whose JNDIname is the<jndi-name> parameter appended with two underscores axa (<jndi-name>__xa). Behind the scenes, theDataSource uses theXADataSource to create connections.
2. Restart the J2EE server.
288 J2EE™CONNECTORTECHNOLOGY
d ine
to
the
Resource Adapter TutorialThis tutorial shows you how to deploy the black box resource adapter storethe blackbox-tx.rar file. To test the resource adapter, you will modify thexamples/src/ejb/account/AccountEJB.java file so that it accesses theCloudscape database through the resource adapter. TheAccountEJB.java file isalso used in another example. For more information, seeTips for RunningtheAccountEJB Example (page 94)
Setting Up1. Start the J2EE server.
j2ee -verbose
2. In another terminal window, set the J2EE_HOME environment variablethe directory in which you’ve installed this release.
3. Follow the instructions in the section,SettingUp theDatabase (page 94).
Deploying the Resource Adapter1. Deploy a black box resource adapter that is packaged in theblackbox-
tx.rar file.
UNIX:
deploytool -deployConnector \$J2EE_HOME/lib/connector/blackbox-tx.rar localhost
Windows:
(Enter the following command on a single line.)
deploytool -deployConnector%J2EE_HOME%\lib\connector\blackbox-tx.rar localhost
2. Add a connection factory for the resource adapter. The JNDI name forconnection factory iseis/MyBlackBoxTx.
UNIX:
j2eeadmin -addConnectorFactory \eis/MyBlackBoxTx blackbox-tx.rar
RESOURCEADAPTER TUTORIAL 289
ns
the
es,
Windows:
(Enter the following command on a single line.)
j2eeadmin -addConnectorFactoryeis/MyBlackBoxTx blackbox-tx.rar
3. Verify that the resource adapter has been deployed.
deploytool -listConnectors localhost
Thedeploytool displays these lines:
Installed connector(s):Connector Name: blackbox-tx.rar
Installed connection factories:Connection Factory JNDI Name: eis/MyBlackBoxTx
Testing the Resource Adapter1. If you are new to the J2EE SDK, you may want to review the instructio
in Getting Started (page 43).
2. Locate theAccountEJB.java source code, which resides in theexam-ples/src/ejb/account directory.
3. Edit theAccountEJB.java source code, changing the value assigned todbName variable as follows:
private String dbName = “java:comp/env/MyEIS”;
4. Compile the source code in theaccount directory:
a. Go toexamples/src.
b. Typeant account.
5. Run the New Enterprise Bean Wizard of thedeploytool by selecting File-> New Enterprise Bean. Although the wizard displays many dialog boxfor this example only the following dialog boxes require input.
6. General Dialog Box
c. Select the Entity radio button.
d. In the Enterprise Bean Name field, enterAccountBean.
290 J2EE™CONNECTORTECHNOLOGY
on
re-
log
lect
7. Entity Settings Dialog Box
a. Select the radio button for bean-managed persistence.
8. Resource References Dialog Box:
a. Click Add.
b. Enter the values specified in the following table.
Theeis/MyBlackBoxTx JNDI name matches the name of the connectifactory that you added in step 2 ofDeploying the ResourceAdapter (page 288). The MyEIS value of the Coded Name field corsponds to this line in theAccountEJB.java source code:
private String dbName = “java:comp/env/MyEIS”;
Although it is included in the source code, thejava:comp/env/ subcon-text is implicit in the Coded Name field of the Resource References diabox.
9. Transaction Management Dialog Box:
a. For the business methods, in the Transaction Type column seRequired. The business methods aredebit, credit, getFirstName,getLastName, andgetBalance.
10.Exit the wizard by clicking Finish.
11.Create a J2EE application client.
a. Select New->Application Client
b. Name the clientAccountClient.
c. Add theejb/SimpleAccount enterprise bean reference.
Table 36 Resource References Values
Field Value
Coded Name MyEIS
Type javax.sql.DataSource
Authentication Container
JNDI Name eis/MyBlackBoxTx
COMMON CLIENT INTERFACE (CCI) 291
l-
monIS.
acespera-
12.Select Tools->Deploy Application.
a. In the Introduction dialog box, select Return Client Jar.
b. In the JNDI Names dialog box, verify that the JNDI names in the folowing table have been specified.
13.To run the application, follow the directions inRunning the J2EEApplication (page 96).
Common Client Interface (CCI)This section describes how components use the Connector architecture ComClient Interface (CCI) API and a resource adapter to access data from an E
Overview of the CCIDefined by the J2EE Connector Specification, the CCI defines a set of interfand classes whose methods allow a client to perform typical data access o
Table 37 JNDI Names
Comp. Name orRef. Type JNDI Name
AccountBean MyAccount
MyEIS eis/MyBlackBoxTx
ejb/SimpleAccount MyAccount
292 J2EE™CONNECTORTECHNOLOGY
ow
ss
ute
o-
ord
rly-nnec-
sed
datat
es) or
d readroce-to an
pera-data-
tions. Our exampleCoffeeEJB session bean includes methods that illustrate hto use the CCI, in particular, the following CCI interfaces and classes:
• ConnectionFactory: Provides an application component with aConnec-
tion instance to an EIS.
• Connection- Represents the connection to the underlying EIS.
• ConnectionSpec: Provides a means for an application component to paconnection request-specific properties to theConnectionFactory whenmaking a connection request.
• Interaction: Provides a means for an application component to execEIS functions, such as database stored procedures.
• InteractionSpec: Holds properties pertaining to an application compnent’s Interaction with an EIS.
• Record: The superclass for the different kinds of record instances. Recinstances may beMappedRecord, IndexedRecord, or ResultSet
instances, which all inherit from the Recordinterface.
• RecordFactory: Provides an application component with aRecordinstance.
• IndexedRecord: Represents an ordered collection ofRecord instancesbased on thejava.util.List interface.
A client or application component that uses the CCI to interact with an undeing EIS does so in a prescribed manner. The component must establish a cotion to the EIS’s resource manager, and it does so using theConnectionFactory.TheConnection object represents the actual connection to the EIS and it is ufor subsequent interactions with the EIS.
The component performs its interactions with the EIS, such as accessingfrom a specific table, using anInteraction object. The application componendefines theInteraction object using anInteractionSpec object. When theapplication component reads data from the EIS (such as from database tablwrites to those tables, it does so using a particular type ofRecord instance, eithera MappedRecord, IndexedRecord, or ResultSet instance. Just as theConnec-tionFactory createsConnection instances, aRecordFactory createsRecordinstances.
Our example shows how a session bean uses a resource adapter to add anrecords in a relational database. The example shows how to invoke stored pdures, which are business logic functions stored in a database and specificenterprise’s operation. Stored procedures consist of SQL code to perform otions related to the business needs of an organization. They are kept in the
COMMON CLIENT INTERFACE (CCI) 293
va™res,mapage.
andffer-Ourers:
ome
,
lled
ow
base and can be invoked when needed, just as you might invoke a Jamethod. In addition to showing how to use the CCI to invoke stored proceduwe’ll also explain how to pass parameters to stored procedures and how tothe parameter data types from SQL to those of the Java programming langu
Programming with the CCIThe code for the following example is in theexamples/src/connector/ccidirectory.
To illustrate how to use a CCI resource adapter, we’ve written a session beana client of that bean. These pieces of code illustrate how clients invoke the dient CCI methods that resource adapters built on CCI might make available.example uses the two sample CCI-specific resource adaptcciblackbox_tx.rar and cciblackbox_xa.rar.
The Coffee session bean is much like any other session bean. It has a hinterface (CoffeeHome), a remote interface (Coffee), and an implementationclass (CoffeeEJB). To keep things simple, we’ve called the clientCoffeeCli-
ent.
Let’s start with the session bean interfaces and classes. The home interfaceCof-
feeHome, is like any other session bean home interface. It extendsEJBHome anddefines acreate method to return a reference to theCoffee remote interface.
TheCoffee remote interface defines the bean’s two methods that may be caby a client.
public void insertCoffee(String name, int quantity)throws RemoteException;public int getCoffeeCount() throws RemoteException;
Now let’s examine theCoffeeEJB session bean implementation class to see hit uses the CCI.
To begin with, notice thatCoffeeEJB imports thejavax.resource CCI inter-faces and classes, along with thejavax.resource.ResourceException, andthe samplecciblackbox classes.
import javax.resource.cci.*;import javax.resource.ResourceException;import com.sun.connector.cciblackbox.*;Obtaining a Database Connection
294 J2EE™CONNECTORTECHNOLOGY
p workfi-ndto
orre-
-
beanllow-
Prior to obtaining a database connection, the session bean does some set uin its setSessionContext method. (See the following code example.) Specically, thesetSessionContext method sets the user and password values, ainstantiates aConnectionFactory. These values and objects remain availablethe other session bean methods.
(In this and subsequent code examples, the numbers in the left margin cspond to the explanation that follows the code.)
public void setSessionContext(SessionContext sc) { try { this.sc = sc;1 Context ic = new InitialContext();2 user = (String) ic.lookup(“java:comp/env/user”); password = (String) ic.lookup (“java:comp/env/password”);3 cf = (ConnectionFactory) ic.lookup (“java:comp/env/CCIEIS”); } catch (NamingException ex) { ex.printStackTrace(); } }
1. Establish a JNDIInitialContext.
2. Use the JNDIInitialContext.lookup method to find the user and password values.
3. Use thelookup method to locate theConnectionFactory for the CCIblack box resource adapter and obtain a reference to it.
CoffeeEJB uses its private methodgetCCIConnection method to establish aconnection to the underlying resource manager or database. A client of theCof-
fee session bean cannot invoke this method directly. Rather, the sessionuses this method internally to establish a connection to the database. The foing code uses the CCI to establish a database connection.
private Connection getCCIConnection() { Connection con = null; try {1 ConnectionSpec spec = new CciConnectionSpec(user, password);2 con = cf.getConnection(spec); } catch (ResourceException ex) {
COMMON CLIENT INTERFACE (CCI) 295
por-rite
e CCIdata.
proce-ase.
ata-uresmayuresy are
ex.printStackTrace(); } return con; }
1. Instantiate a newCciConnectionSpec object with the user and passwordvalues obtained by thesetSessionContext method. TheCciConnec-tionSpec class is the implementation of theConnectionSpec interface.
2. Call theConnectionFactory.getConnection method to obtain a connec-tion to the database. (The reference to theConnectionFactory wasobtained in thesetSessionContext method.) Use theCciConnection-Spec object to pass the required properties to theConnectionFactory.ThegetConnection method returns aConnection object.
The CoffeeEJB bean also includes a private method,closeCCIConnection, toclose a connection. The method invokes theConnection object’sclose methodfrom within a try/catch block. Like thegetCCIConnection method, this is aprivate method intended to be called from within the session bean.
private void closeCCIConnection(Connection con) { try { con.close(); } catch (ResourceException ex) { ex.printStackTrace(); }}
Database Stored Procedures
The sample CCI black box adapters call database stored procedures. It is imtant to understand stored procedures before delving into how to read or wdata using the sample CCI black box adapters. The methods of these sampladapters do not actually read data from a database or update databaseInstead, these sample CCI adapters enable you to invoke database storeddures, and it is the stored procedures that actually read or write to the datab
A stored procedure is a business logic method or function that is stored in a dbase and is specific for the enterprise’s business. Typically, stored procedconsist of SQL code, though in certain cases (such as with Cloudscape) theyconsist of code written in the Java™ programming language. Stored procedperform operations related to the business needs of an organization. Thekept in the database and applications can invoke them when needed.
296 J2EE™CONNECTORTECHNOLOGY
ored
ro-
ayvoke
dure
man-backme-ode
onlyd
re
uting
e,fat is,
Stored procedures are typically SQL statements. Our example calls two stprocedures:COUNTCOFFEE and INSERTCOFFEE. The COUNTCOFFEE proceduremerely counts the number of coffee records in theCoffee table, as follows:
SELECT COUNT(*) FROM COFFEE
TheINSERTCOFFFEE procedure adds a record with two values, passed to the pcedure as parameters, to the sameCoffee table, as follows:
INSERT INTO COFFEE VALUES (?,?)
Mapping to Stored Procedure Parameters
When you invoke a stored procedure from your application component you mhave to pass argument values to the procedure. For example, when you intheINSERTCOFFEE procedure, you pass it two values for theCoffee record ele-ments. Likewise, you must be prepared to receive values that a stored procereturns.
The stored procedure, in turn, passes its set of parameters to the databaseagement system (DBMS) to carry out its operation and may receive valuesfrom the DBMS. Database stored procedures specify, for each of their paraters, the SQL type of the parameter value and the mode of the parameter. Mcan be input (IN), output (OUT), or both input and output (INOUT). An inputparameter only passes data in to the DBMS while an output parameterreceives data back from the DBMS. AINOUT parameter accepts both input anoutput data.
When you use the CCIexecute method to invoke a database stored proceduyou also create an instance of anInputRecord, provided that you’re passing aparameter to the stored procedure and the stored procedure you’re execreturns data (possibly anOutputRecord instance). TheInputRecord andOut-putRecord are instances of the supportedRecord types: IndexedRecord,MappedRecord, or ResultSet. In our example, we instantiate anInputRecordand anOutputRecord that are bothIndexedRecord instances.
Note: The CCI black box adapters only supportIndexedRecord types.
The InputRecord maps theIN andINOUT parameters for the stored procedurwhile theOutputRecord maps theOUT andINOUT parameters. Each element oan input or output record corresponds to a stored procedure parameter. Ththere is an entry in theInputRecord for eachIN andINOUT parameter declared
COMMON CLIENT INTERFACE (CCI) 297
same
-
of
e andMSthe
. For
od sig-
-
in the stored procedure. Not only does theInputRecord have the same numberof elements as the procedure’s input parameters, they are declared in theorder as in the procedure’s parameter list. The same holds true for theOutpu-
tRecord, though its list of elements matches only theOUT andINOUT parameters.
For example, suppose you have a stored procedureX that declares three parameters. The first parameter is anIN parameter, the second is anOUT parameter, andthe third is anINOUT parameter. The following figure shows how the elementsanInputRecord and anOutputRecord map to this stored procedure.
Figure 21 Mapping Stored Procedure Parameters to CCI Record Elements
When you use the CCI black box adapter, you designate the parameter typmode in the same way, though the underlying Oracle or Cloudscape DBdeclare the mode differently. Oracle designates the parameter’s mode instored procedure declaration, along with the parameter’s type declarationexample, an OracleINSERTCOFFEE procedure declares its twoIN parameters asfollows:
procedure INSERTCOFFEE (name IN VARCHAR2, qty IN INTEGER)
An OracleCOUNTCOFFEE procedure declares its parameterN as anOUT parameter:
procedure COUNTCOFFEE (N OUT INTEGER)
Cloudscape, which declares stored procedures using standard a Java methnature, indicates anIN parameter using a single value and anINOUT parameter asan array. The method’s return value is theOUT parameter. For example, Cloud
InputRecord iRec
Stored_procedure X ( IN, OUT, INOUT
OutputRecord oRec
e1 e2
e1 e2
298 J2EE™CONNECTORTECHNOLOGY
ype.
ean
data-calledthe
er-e
,
scape declares theIN parameters (name andqty) for insertCoffee and theOUTparameter (the method’s return value) forcountCoffee as follows:
public static void insertCoffee(String name, int qty)public int countCoffee()
If qty were anINOUT parameter, then Cloudscape would declares it as:
public static void insertCoffee(String name, int[] qty)
Oracle would declare it as:
procedure INSERTCOFFEE (name IN VARCHAR2, qty INOUT INTEGER)
You must also map the SQL type of each value to its corresponding Java tThus, if the SQL type is integer, then theInputRecord or OutputRecord ele-ment must be defined as aInteger object. If the SQL type is aVARCHAR, then theJava type must be aString object. Thus, when you add the element to thRecord, you declare it to be an object of the proper type. For example, addinteger and a string element to anInputRecord as follows:
iRec.add (new Integer (intval));iRec.add (new String (“Mocha Java”));
Note: TheJDBC Specification defines the SQL to Java type mapping.
Reading Database Records
The getCoffeeCount method ofCoffeeEJB illustrates how to use the CCI toread records from a database table. This method does not directly read thebase records itself; instead, it invokes a procedure stored in the databaseCOUNTCOFFEE. It is the stored procedure that actually reads the records indatabase table.
The CCI provides interfaces for three types of records:IndexedRecord, Mappe-dRecord, andResultSet. These three record types inherit from the base intface,Record. They differ only in how they map the record elements within threcord. Our example usesIndexedRecord, which is the only record type cur-rently supported.IndexedRecord holds its record elements in an orderedindexed collection based onjava.util.List. As a result, we use anIteratorobject to access the individual elements in the list.
COMMON CLIENT INTERFACE (CCI) 299
argin.
es-s.
r-g
ing a
Let’s begin by looking at how thegetCoffeeCount method uses the CCI toinvoke a database stored procedure. Again, note that the numbers in the mto the left of the code correspond to the explanation after the code example
public int getCoffeeCount() { int count = -1; try {1 Connection con = getCCIConnection();2 Interaction ix = con.createInteraction();3 CciInteractionSpec iSpec = new CciInteractionSpec();4 iSpec.setSchema(user); iSpec.setCatalog(null); iSpec.setFunctionName(“COUNTCOFFEE”);5 RecordFactory rf = cf.getRecordFactory();6 IndexedRecord iRec = rf.createIndexedRecord(“InputRecord”);7 Record oRec = ix.execute(iSpec, iRec);8 Iterator iterator = ((IndexedRecord)oRec).iterator();9 while(iterator.hasNext()) { Object obj = iterator.next(); if(obj instanceof Integer) { count = ((Integer)obj).intValue(); } else if(obj instanceof BigDecimal) { count = ((BigDecimal)obj).intValue(); } }10 closeCCIConnection(con); }catch(ResourceException ex) { ex.printStackTrace(); } return count; }
1. Obtain a connection to the database.
2. Create a newInteraction instance. ThegetCoffeeCount method createsa newInteraction instance because it is this object that enables the ssion bean to execute EIS functions such as invoking stored procedure
3. Instantiate aCciInteractionSpec object. The session bean must pass cetain properties to theInteraction object, such as schema name, cataloname, and the name of the stored procedure. It does this by instantiatCciInteractionSpec object. TheCciInteractionSpec is the implemen-tation class for theInteractionSpec interface, and it holds properties
300 J2EE™CONNECTORTECHNOLOGY
ea cat-
n
ur
d
nd
ts
ord-
required by theInteraction object to interact with an EIS instance. (Notthat our example uses a Cloudscape database, which does not requirealog name.)
4. Set values for theCciInteractionSpec instance’s fields. The session beauses theCciInteractionSpec methodssetSchema, setCatalog, andsetFunctionName to set the required values into the instance’s fields.Oexample passesCOUNTCOFFEE to setFunctionName because this is thename of the stored procedure it intends to invoke.
5. ThegetCoffeeCount method uses theConnectionFactory to obtain areference to aRecordFactory so that it can create anIndexedRecordinstance. We obtain anIndexedRecord (or aMappedRecord or aResult-Set) using aRecordFactory.
6. Invoke thecreateIndexedRecord method of RecordFactory. This methocreates a newIndexedRecord using the nameInputRecord, which ispassed to it as an argument.
7. ThegetCoffeeCount method has completed the required set-up work ait can invoke the stored procedureCOUNTCOFFEE. It does this using theInteraction instance’sexecute method. Notice that it passes two objecto theexecute method: theInteractionSpec object, whose propertiesreference theCOUNTCOFFEE stored procedure, and theIndexedRecordobject, which the method expects to be an inputRecord. The execute
method returns an outputRecord object.
8. ThegetCoffeeCount method uses anIterator to retrieve the individualelements from the returnedIndexedRecord. It casts the outputRecordobject to anIndexedRecord. IndexedRecord contains an iterator methodthat it inherits fromjava.util.List.
9. Retrieve each element in the returned record object using theitera-
tor.hasNext method. Each extracted element is anObject, and the beanevaluates whether it is an integer or decimal value and processes it accingly.
10.Close the connection to the database.
Inserting Database Records
TheCoffeeEJB session bean implements theinsertCoffee method to add newrecords into theCoffee database table. This method invokes theINSERTCOFFEE
stored procedure, which inserts a record with the values (name andqty) passedto it as arguments.
COMMON CLIENT INTERFACE (CCI) 301
e ashows
an
eedure
ece.
ts-
TheinsertCoffee method shown here illustrates how to use the CCI to invokstored procedure that expects to be passed argument values. This examplethe code for theinsertCoffee method and is followed by an explanation.
public void insertCoffee(String name, int qty) { try {1 Connection con = getCCIConnection();2 Interaction ix = con.createInteraction();3 CciInteractionSpec iSpec = new CciInteractionSpec();4 iSpec.setFunctionName(“INSERTCOFFEE”); iSpec.setSchema(user); iSpec.setCatalog(null);5 RecordFactory rf = cf.getRecordFactory();6 IndexedRecord iRec = rf.createIndexedRecord(“InputRecord”);7 boolean flag = iRec.add(name); flag = iRec.add(new Integer(qty));8 ix.execute(iSpec, iRec);9 closeCCIConnection(con); }catch(ResourceException ex) { ex.printStackTrace(); } }
1. Establish a connection to the database.
2. Create a newInteraction instance for the connection so that the bean cexecute the database’s stored procedures.
3. Instantiate aCciInteractionSpec object so that the bean can pass thnecessary properties—schema name, catalog name, stored procname—to theInteraction object. The CciInteractionSpec classimplements theInteractionSpec interface and it holds properties that thInteraction object requires to communicate with the database instan
4. Set the required values into the newCciInteractionSpec instance’sfields, using the instance’ssetSchema, setCatalog, andsetFunction-Name methods. Our example passesINSERTCOFFEE to setFunctionName
and theuser to setSchema.
5. Obtain a reference to aRecordFactory using theConnectionFactoryobjects’sgetRecordFactory method.
6. Invoke theRecordFactory object’screateIndexedRecordmethod to cre-ate a newIndexedRecord with the nameInputRecord.
7. Use theIndexedRecord add method to set the values for the two elemenin the new record. Call theadd method once for each element. Our exam
302 J2EE™CONNECTORTECHNOLOGY
t
e
o-
any
pter
r.
st be
ple sets the first record element to thename value and the second elemento theqty value. Notice thatqty is set to anInteger object when passedto theadd method. TheCoffeeEJB session bean is now ready to add thnew record to the database.
8. Call theInteraction instance’s execute method to invoke the stored prcedureINSERTCOFFEE. Just as we did when invoking theCOUNTCOFFEEprocedure, we pass two objects to the execute method: theInteraction-
Spec object with the correctly set properties for theINSERTCOFFEE storedprocedure and theIndexedRecord object representing an inputRecord.Theexecute method is not expected to return anything in this case.
9. Close the connection to the database.
Writing a CCI ClientA client application that relies on a CCI resource adapter is very much likeother J2EE client that uses enterprise bean methods. OurCoffeeClient applica-tion uses the methods of theCoffeeEJB session bean to access theCoffee tablein the underlying database.CoffeeClient invokes theCoffee.getCoffeeCountmethod to read theCoffee table records and theCoffee.insertCoffee methodto add records to the table.
CCI TutorialThis tutorial shows you how to deploy and test the sample CCI black box adawith the code described in the preceding sections. The source code is inexam-
ples/src/connector/cci.
Deploy the Resource Adapter
1. Use thedeploytool utility to deploy the CCI black box resource adapteSpecify the name of the resource adapter’s RAR file (cciblackbox-
tx.rar), plus the name of the server (localhost).
UNIX:
deploytool -deployConnector \$J2EE_HOME/lib/connector/cciblackbox-tx.rar localhost
Windows:
(Note that this command and all subsequent Windows commands muentered on a single line.)
COMMON CLIENT INTERFACE (CCI) 303
nec-UseDICCI
ee
deploytool -deployConnector%J2EE_HOME%\lib\connector\cciblackbox-tx.rar localhost
2. Next, add a connection factory for the deployed CCI adapter. The contion factory supplies a data source connection for the adapter.j2eeadmin to create the connection factory, specifying the adapter’s JNname plus the server name. Here, we add a connection factory for ouradapter whose JNDI name iseis/CciBlackBoxTx on the serverlocal-host.
UNIX:
j2eeadmin -addConnectorFactory \eis/CciBlackBoxTx cciblackbox-tx.rar
Windows:
j2eeadmin -addConnectorFactoryeis/CciBlackBoxTx cciblackbox-tx.rar
3. Verify that the resource adapter has been deployed.
deploytool -listConnectors localhost
Thedeploytool utility displays these lines:
Installed connector(s):Connector Name: cciblackbox-tx.rar
Installed connection factories:Connection Factory JNDI name: eis/CciBlackBoxTx
Set Up the Database
Cloudscape:
1. Create the stored procedure.
a. To compile the stored procedure, go to theexamples/src directory andtype ant procs. This command will put theProcs.class file in theexamples/build/connector/procs directory.
b. Locate thebin/userconfig.sh (UNIX) or bin\userconfig.bat
(Windows) file in your J2EE SDK installation. Edit the file so that thJ2EE_CLASSPATH variable points to the directory that contains thProcs.class file.
c. Restart the Cloudscape server.
304 J2EE™CONNECTORTECHNOLOGY
ures.
ion
g
derter
d. Go to theexamples/src directory and typeant create-procs-alias.This command creates aliases for the methods inProcs.class. Methodaliases are the means by which Cloudscape simulates stored proced
2. To create the Coffee table, go to theexamples/src directory and typeantcreate-coffee-table.
Oracle:
1. Start the database server.
2. Run theexamples/src/connector/sql/oracle.sql script, which cre-ates both the stored procedures and the Coffee table.
Create the J2EE Application
1. To compile the application source code, go to theexamples/src directoryand typeant cci.
2. In the deploytool, select File->New Application and create an applicatnamedCoffeeApp.
3. Select File->New Enterprise Bean Wizard and fill in the following dialoboxes.
4. General Dialog Box
a. Select the Stateful Session Bean radio button.
b. In the Enterprise Bean Name field, enterCoffeeBean.
5. Environment Entiries Dialog Box
Add the entries shown in the following table. For Cloudscape, placeholstrings such asxxx are required, but for other databases you should enthe actual values .
6. Resource References Dialog Box:
a. Click Add.
Table 38 Environment Entries
Coded Entry Type Value
user String xxx
password String xxx
COMMON CLIENT INTERFACE (CCI) 305
on
ion
b. Enter the values specified in the following table.
Theeis/CciBlackBoxTx JNDI name matches the name of the connectifactory you added in step 2 ofDeploy the ResourceAdapter (page 302).The CCIEIS value corresponds to the following line in theCof-feeEJB.java source code:
cf = (ConnectionFactory) ic.lookup(“java:comp/env/CCIEIS”);
7. Transaction Management Dialog Box
a. Select Container-Managed Transactions.
b. For theCoffeeEJB business methods, select Required in the TransactType column.
8. Click Finish to exit the wizard.
9. Create a J2EE application client.
a. Select New->Application Client
b. Name the clientCoffeeClient.
c. Add theejb/SimpleCoffee enterprise bean reference.
10.Select Tools->Deploy.
a. In the Introduction dialog box, select Return Client Jar.
Table 39 Resource Reference Values
Field Value
Coded Name CCIEIS
Type javax.resource.cci.ConnectionFactory
Authentication Application
JNDI Name eis/CciBlackBoxTx
User Name xxx
Password xxx
306 J2EE™CONNECTORTECHNOLOGY
l-
b. In the JNDI Names dialog box, verify that the JNDI names in the folowing table have been specified.Test the Resource Adapter
1. In a terminal window, set theAPPCPATH environment variable to the nameof the stub client JAR file (CoffeeAppClient.jar).
2. Go to the directory containing the application EAR file.
3. Run the application with therunclient script. In the following example,the application EAR file isCoffeeApp.ear and the name of the J2EEapplication client isCoffeeClient:
runclient -client CoffeeApp.ear -name CoffeeClient
4. In the login dialog, enterguest as the user name andguest123 as the pass-word.
5. The application displays the following lines:
Coffee count = 0Coffee count = 3
Table 40 JNDI Names
Comp. Name orRef. Type JNDI Name
CoffeeBean MyCoffee
CCIEIS eis/CciBlackBoxTx
ejb/SimpleCoffee MyCoffee
th ar andwhichML
eliv-nentonse
ForFC
elds,
HTTP Overviewby Stephanie Bodoff
Most web-based J2EE clients use the HTTP protocol to communicate wiJ2EE server. HTTP defines the requests that a client can send to a serveresponses that the server can send in reply. Each request contains a URL,is a string that identifies a web component or a static object such as an HTpage or image file.
The J2EE server converts an HTTP request to an HTTP request object and ders it to the web component identified by the request URL. The web compofills in an HTTP response object, which the server converts to an HTTP respand sends to the client.
This appendix provides some introductory material on the HTTP protocol.further information on this protocol, see the Internet RFCs: HTTP/1.0 - R1945, HTTP/1.1 - RFC 2616, which can be downloaded from
http://www.rfc-editor.org/rfc.html
HTTP RequestsAn HTTP request consists of a request method, a request URL, header fiand a body. HTTP 1.1 defines the following request methods:
• GET - retrieves the resource identified by the request URL.
• HEAD - returns the headers identified by the request URL.
• POST - sends data of unlimited length to the web server.
• PUT - stores a resource under the request URL.
• DELETE - removes the resource identified by the request URL.
307
308 HTTP OVERVIEW
EElud-
rned
om
able
• OPTIONS - returns the HTTP methods the server supports.
• TRACE - returns the header fields sent with the TRACE request.
HTTP 1.0 includes only the GET, HEAD, and POST methods. Although J2servers are only required to support HTTP 1.0, in practice many servers, incing the J2EE SDK, support HTTP 1.1.
HTTP ResponsesAn HTTP response contains a result code, header fields, and a body.
The HTTP protocol expects the result code and all header fields to be retubefore any body content.
Some commonly used status codes include:
• 404 - indicates that the requested resource is not available.
• 401 - indicates that the request requires HTTP authentication.
• 500 - indicates an error inside the HTTP server which prevented it frfulfilling the request.
• 503 - indicates that the HTTP server is temporarily overloaded, and unto handle the request.
J2EE™SDK Toolsby Dale Green
THE J2EE™ SDK includes the following tools:
J2EE Administration Tool 312Cleanup Tool 313Cloudscape Server 313
Starting and Stopping Cloudscape 313Cloudscape Server Configuration 314Cloudscapeij Tool 314
Deployment Tool 315J2EE Server 316Key Tool 316Packager 317
EJB JAR File 317Web Application WAR File 318Application Client JAR File 319J2EE Application EAR File 319Resource Adapter RAR File 321
Realm Tool 321Runclient Script 322Verifier 322
Command-Line Verifier 322Stand-Alone GUI Verifier 323
309
310 J2EE™SDK TOOLS
nds and
-
J2EE Administration ToolThe j2eeadmin tool is a command-line script that enables you to add aremove these resources: JDBC™ drivers and data sources, JMS destinationconnection factories, and resource adapter connection factories.
Table 41 j2eeadmintool Options
Option Description
-addConnectorFactory<jndi-name>[<app-name>:]<rar-filename>[<xa-user-name><xa-password>][-props (<name>=<value>)+]
Adds a connection factory with the specified<jndi-name>. The connection factory is contained inthe RAR file specified by<rar-filename>. The<rar-filename> must be the base name of the file; it cannot include any prefix ending in / (Unix) or \ (Windows).If the RAR file is contained in a EAR file, then the nameof the J2EE application name must be specified by<app-name>, followed by a colon. Optionally, a username and password for the factory may be specified.Also optional is the-props flag, followed by one ormore name-value pairs that specify properties for thisfactory. To prevent the shell from interpreting charactersin the values, enclose the values in single or doublequotes.
-addJdbcDriver<class-name>
Adds the JDBC driver specified by its fully-qualified<class-name>. You must also update theJ2EE_CLASSPATH environment variable in the filebin\userconfig.bat. Then you must restart the J2EEserver.
-addJdbcDatasource<jndi-name> <url>
Adds the JDBCDataSource with the specified<jndi-name> and<url>.
-addJdbcXADatasource<jndi-name><class-name>[<xa-user-name><xa-password>][-props (<name>=<value>)+]
Adds the JDBCXADataSource with the specified<jndi-name> and fully-qualified <class-name>.Optionally, a user name and password for theData-Source may be specified. Also optional is the-propsflag, followed by one or more name-value pairs thatspecify properties for thisDataSource.
-addJmsDestination<jndi-name>(queue|topic)
Adds a JMS destination with the specified<jndi-name> and declares the destination as either aqueue or topic.
CLEANUP TOOL 311
a-R,
loud-
st run
Cleanup ToolThe cleanup tool is a command-line script that removes all deployed applictions from your J2EE server. It will not delete the component files (JAR, WAEAR).
Note: Use this utility with care!
Cloudscape ServerThe enterprise code examples in this manual have been tested with the Cscape DBMS, which is included in the J2EE SDK.
Starting and Stopping CloudscapeBefore your enterprise beans can access a Cloudscape database, you muthe Cloudscape server from the command line:
-addJmsFactory<jndi-name>(queue|topic)[-props (<name>=<value>)+]
Adds a JMS connection factory with the specified<jndi-name> and destination type, either queue ortopic. Optionally, one or more properties may be speci-fied with name-value pairs.
-list<resource-type> Lists resources of the specified<resource-type>,either:ConnectorFactory, JdbcDriver, JdbcData-source, JdbcXADatasource, JmsDestination, orJmsFactory. There is no space between-list and<resource-type>.
-remove<resource-type><jndi-name>
Removes the resource of the specified<resource-type> and<jndi-name>. (See thedescription of-list for the allowed<resource-type> elements.)
-removeAll<resource-type> Removes all resources of the specified<resource-type>. (See the description of-list forthe allowed<resource-type> elements.)
Table 41 j2eeadmintool Options (Continued)
Option Description
312 J2EE™SDK TOOLS
itthe
cloudscape -start
You should see output similar to the following:
Mon Aug 09 11:50:30 PDT 1999: [RmiJdbc]COM.cloudscape.core.JDBCDriver registered in DriverManagerMon Aug 09 11:50:30 PDT 1999: [RmiJdbc] Binding . . ..Mon Aug 09 11:50:30 PDT 1999: [RmiJdbc] No installation ofRMI Security Manager...Mon Aug 09 11:50:31 PDT 1999: [RmiJdbc] RmiJdbcServerbound in rmi registry
To stop the server type the following command:
cloudscape -stop
You should see output similar to the following:
Attempting to shutdown RmiJdbc serverRmiJdbc Server RmiAddr is: //buzz/RmiJdbcServerWARNING: Shutdown was successful!
Note: If you stop the server with Control-c, files will not be closed properly. Whenthe server is started the next time, it must perform recovery by rolling backnon-committed transactions and possibly applying the forward log.
Cloudscape Server ConfigurationThe default database used by the Cloudscape server is namedCloudscapeDB.This database will reside in thecloudscape directory of your J2EE SDK instal-lation. TheCloudscapeDB database will be created automatically the first timeis accessed. The driver for the Cloudscape server is already configured inconfig/default.properties file. No further changes by you are necessary.
Cloudscape ij ToolThe Cloudscape product includes an interactive SQL tool calledij. (This tool isnot supported by Sun Microsystems, Inc.) You can run theij tool by executingthecloudIJ.sh (UNIX) or cloudIJ.bat (Windows) script, which resides in theexamples/src/ejb/sql directory.
DEPLOYMENT TOOL 313
ions..
Toor a
pli-
Deployment ToolThedeploytool has two versions: GUI and command-line.
The GUI version enables you to package components and to deploy applicatIf you run thedeploytool script with no options, the GUI version is launched
The GUI version includes online help information that is context sensitive.access a help topic for a particular dialog box or tabbed pane, press f1. Fquick introduction to the tool, see the chapterGetting Started (page 43).
The command-line version of the tool enables you to deploy and undeploy apcations. To package components from the command line, use thepackager tool.
Table 42 deploytool Options
Option Description
-deploy<myApplear><myServerName>[<myAppClientCode.jar>]
Deploys the J2EE application contained in the EARfile specified by<myApplear> onto the J2EE serverrunning on the machine specified by<myServer-Name>. Optionally, a JAR file for a stand-alone Javaapplication client may be created by specifying<myAppClientCode.jar>.
-deployConnector<rar-filename> <server-name>
Deploys the resource adapter contained in the RARfile specified by<rar-filename> onto the J2EEserver running on the machine specified by<server-name>.
-listApps<server-name>
Lists the J2EE applications that are deployed on theJ2EE server running on the machine specified by<server-name>.
-listConnectors<server-name>
Lists the resource adapters that are deployed on theJ2EE server running on the machine specified by<server-name>.
-undeployConnector<rar-filename><server-name>
Undeploys the resource adapter contained in the filespecified by<rar-filename> from the J2EE serverrunning on the machine specified by<server-name>.
-uninstall<app-name><server-name>
Undeploys the J2EE application whose name is<app-name> from the J2EE server running on themachine specified by<server-name>.
314 J2EE™SDK TOOLS
rtifi-
09
2EEhas
ffi-
s..
J2EE ServerTo launch the J2EE server, run thej2ee script from the command-line prompt.
To run the HTTPS service of the J2EE server, you must install a server cecate. For instructions, see the sectionSetting Up a Server Certificate (page 262).
Key ToolThe keytool utility creates public and private keys and generates X5self-signed certificates. The J2EE SDK version of thekeytool utility has thesame options as the version distributed with the J2SE SDK. However, the Jversion programatically adds a Java Cryptographic Extension provider that
-help Displays options.
-ui Runs GUI version (default).
Table 43 j2ee Options
Option Description
-verbose Redirects all logging output to the current shell.
-version Displays the version number.
-stop Stops the J2EE server.
-singleVM Runs services and deployed enterprise beans in a single process. Thismode is the default. You’ll probably want to use this mode when debug-ging your applications because debugging multiple processes can be dicult.
-multiVM Launches an additional VM (virtual machine) for each application thatyou deploy. Also launches separate VMs for the EJB and HTTP serviceThis option may improve performance but it will increase memory usage
Table 42 deploytool Options (Continued)
Option Description
PACKAGER 315
or
EE
ss.
implementations of RSA algorithms (licensed from RSA Data Security). Fmore information, see the sectionSetting Up a Server Certificate (page 262).
PackagerThe packager tool is a command-line script that enables you to package J2components. This tool is for advanced users who do not want to use thedeploy-
tool to package J2EE components. With thepackager, you can create the fol-lowing component packages:
• EJB JAR file
• Web Application WAR file
• Application Client JAR file
• J2EE Application EAR file
• Resource Adapter RAR file
Note: To make them easier to read, the examples that follow contain line breakwithin the commands. When typing these commands, do not include the line break
EJB JAR File
Syntaxpackager -ejbJar root-directorypackage/Class1.class:package/Class2.class:pics/me.gifejb-jar.xml ejb.jar
Example
The following command packages the EJB classes and thehello-jar.xml
deployment descriptor into theHelloEJB.jar file:
packager -ejbJar /home/duke/classes/HelloHome.class:HelloEJB.class:HelloRemote.class:Util.classhello-jar.xml HelloEJB.jar
316 J2EE™SDK TOOLS
ng
od-
le
Web Application WAR File
Syntax
packager -webArchive[-classpath servletorjspbean/classes[-classFiles package/MyClass1.class: package/MyClass2.class]] <content-root>[-contentFiles login.jsp:index.html:images/me.gif] web.xmlmyWebApp.war
Example: Creating a Simple WAR File
The following command packages themyWebPage.xml deployment descriptorand the page inWebPageDir/Hello.html into themyWebPage.war file:
packager -webArchive myWebPageDir myWebPage.xml myWebPage.war
Example: Specifying Individual Content Files
Suppose that you add aHello.jsp file to the directorymyWebPageDir, laterdecide that you don’t want theHello.html file any more, and modify your.xmlfile accordingly. You can individually specify the content files to add by usithe-contentFiles flag:
packager -webArchive myWebPageDir-contentFiles Hello.jsp myWebPage.xml myWebPage.war
Without the-contentFiles option, the following command will produce thesame WAR file because it includes everything under the directorymyWebPage-
Dir:
packager -webArchive myWebPageDir-contentFiles Hello.jsp:Hello.html myWebPage.xml myWebPage.war
Example: Specifying Servlets and JSP Files
Suppose that you write a servlet and compile it into your classes directory, mifying the .xml file for its deployment attributes. Its class file isclasses/pack-age/Servlet1.class. The following command includes the servlet class fibecause it is under theclasses directory:
packager -webArchive -classpath classes myWebPageDir-contentFiles Hello.jsp myWebPage.xml myWebPage.war.
PACKAGER 317
The following command specifies that only thepackage/Servlet1.class andpackageB/Servlet.class files are to be included:
packager -webArchive -classpath classes-classFiles package/Servlet1.class:packageB/Servlet.classmyWebPageDir-contentFiles Hello.jsp myWebPage.xml myWebPage.war
The next command adds theHello.html file back into the WAR file:
packager -webArchive -classpath classes-classFiles package/Servlet1.class:packageB/Servlet.classmyWebPageDir-contentFiles Hello.jsp:Hello.html myWebPage.xml myWebPage.war
Application Client JAR File
Syntax
packager -applicationClient <root-directory>package/Class1.class:package/Main.class:pics/me.gifpackage.Main client.xml appClient.jar
Example
The following command creates theappClient.jar file:
packager classeshello/HelloClient.class:hello/HelloUtil.classpackage.Main client.xml appClient.jar
J2EE Application EAR File
Syntax
packager -enterpriseArchivemyWeb.war:myEJB.jar:myOtherApp.ear[-alternativeDescriptorEntries myWeb/web.xml:myEjb/myEjb.xml:][-libraryJars ejblib.jar:ejblib1.jar]myAppName myApp.ear
318 J2EE™SDK TOOLS
t as
bees
rt it
entof
t
a
Example: Creating an EAR File
In the following command, the optional-alternativeDescriptorEntries flagallows you to specify the external descriptor entry name of each componenyou wish it to appear in the EAR file:
packager -enterpriseArchivemyWeb.war:myEJB.jar:appClient.ear-alternativeDescriptorEntriesmyWeb/web.xml:myEjb/myEjb.xml:client/client.xmlmyAppName myApp.ear
After packaging, any manipulation of the deployment information will notwritten back into the component files inside the EAR file, but to the entry namin the EAR file that you specified.
Example: Specifying the Runtime Deployment Descriptor
The preceding example specified the-enterpriseArchive flag to create a por-table J2EE application EAR file. This file is portable because you can impointo any J2EE environment that conforms to theJ2EE Specification. Althoughyou can import the file into thedeploytool, you cannot deploy it on the J2EEserver until it contains a runtime deployment descriptor. This deploymdescriptor is an XML file that contains information such as the JNDI namesthe application’s enterprise beans.
In the following command, the-setRuntime flag instructs the packager to inserthe runtime deployment descriptor (sun-j2ee-ri.xml) into themyApp.ear file:
packager -setRuntime MyApp.ear sun-j2ee-ri.xml
To obtain an example of the runtime deployment descriptor, extract it fromEAR file that you’ve already deployed:
jar -xvf SomeApp.ear
The DTD of the runtime deployment descriptor is in thelib/dtds/sun-j2ee-ri-dtd file of your J2EE SDK installation.
Note: The runtime deployment descriptor (sun-j2ee-ri.xml) is not required bytheJ2EE Specification. This descriptor is unique to the J2EE SDK and may changein future releases.
REALM TOOL 319
nd
Resource Adapter RAR File
Syntax
packager -connector <root-directory> file1:file2ra.xml myConnector.rar
For examples, see TBD.
Realm ToolThe realmtool utility is a command-line script that enables you to add aremove J2EE users and to import certificate files.
Examples in the sectionManagingJ2EEUsersandGroups (page 256) show howto run therealmtool utility.
Table 44 realmtool Options
Option Description
-show Lists the realm names.
-list <realm-name> Lists the users in the specified realm. This releasehas two realms:default andcertificate.
-add <username passwordgroup[,group]>
Adds the specified user to thedefault realm.
-addGroup <group> Adds a group to thedefault realm.
-import <certificate-file>-alias <alias>
Adds a user to thecertificate realm by import-ing a file containing an X509 certificate.
-remove <realm-name username> Removes a user from the specified realm.
-removeGroup<group>
Removes a group.
320 J2EE™SDK TOOLS
wo
Runclient ScriptTo run a J2EE application client, you execute therunclient script from thecommand-line prompt.
Examples: SeeRunning the J2EE™ Application Client (page 58).
VerifierTheverifier validates J2EE component files (EAR, WAR, JAR).
You can run theverifier three ways:
• From within thedeploytool GUI
• As a command-line utility
• As a stand-alone GUI utility
To run theverifier from within thedeploytool GUI, choose Verifier from theTools menu. The following sections explain how to run the verifier the other tways.
Command-Line VerifierThe command-line verifier has the following syntax:
verifier [options] <filename>
Table 45 runclient Options
Option Description
-client <appjar> The J2EE application EAR file.
<name> The display name of the J2EE application client component.
<app-args> Any arguments required by the J2EE application.
VERIFIER 321
ng
The filename argument is the name of a J2EE component file. The followitable lists the options.Stand-Alone GUI VerifierTo run the stand-alone GUIverifier, follow these steps:
1. From the command-line prompt, type:
verifier -u
2. To select a file for verification, click Add.
3. Select the radio button to indicate the report level:
• All Results
• Failures Only
• Failures and Warnings Only
4. Click OK.
5. Theverifier lists the details in the lower portion of the screen.
Table 46 verifier Options
Syntax Description
-v Displays a verbose version of output.
-o <output-file> Writes the results to the specified<output-file>, overriding thedefaultResults.txt file
-u Runs the stand-alone GUI version.
-<report-level> Determines whether warnings or failures are reported. The<report-level> may be eithera, w, orf:a (all results)w (warnings only)f (failures only)By default, only warnings and failures are reported.
322 J2EE™SDK TOOLS
323
onsity,
city,
e to
in aing
eth-
Glossary
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
access controlThe methods by which interactions with resources are limited to collectiof users or programs for the purpose of enforcing integrity, confidentialor availability constraints.
ACIDThe acronym for the four properties guaranteed by transactions: atomiconsistency, isolation, and durability.
activationThe process of transferring an enterprise bean from secondary storagmemory. (Seepassivation.)
appletA component that typically executes in a web browser, but can executevariety of other applications or devices that support the applet programmmodel.
applet containerA container that includes support for the applet programming model.
Application Component ProviderA vendor that provides the Java classes that implement components’ mods, JSP page definitions, and any required deployment descriptors.
Application AssemblerA person that combinescomponents andmodules into deployable applica-tion units.
324
ne.S)
lient
onof
utho-the
ecu-a-to
the
eb
ntitylt-in
ager
application clientA first-tier client component that executes in its own Java virtual machiApplication clients have access to some (JNDI, JDBC, RMI-IIOP, JMJ2EE platform APIs.
application client containerA container that supports application client components.
application client moduleA software unit that consists of one or more classes and an application cdeployment descriptor.
authenticationThe process by which an entity proves to another entity that it is actingbehalf of a specific identity. The J2EE platform requires three typesauthentication:basic,form-based, andmutual, and supportsdigest authenti-cation.
authorizationThe process by which access to a method or resource is determined. Arization in the J2EE platform depends upon the determination of whetherprincipal associated with a request through authentication is in a given srity role. A security role is a logical grouping of users defined by an Appliction Component Provider or Assembler. A Deployer maps security rolessecurity identities. Security identities may be principals or groups inoperational environment.
authorization constraintAn authorization rule that determines who is permitted to access a wresource collection.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
basic authenticationAn authentication mechanism in which a web server authenticates an ewith a user name and password obtained using the web client’s buiauthentication mechanism.
bean-managed persistenceData transfer between an entity bean’s variables and a resource manmanaged by the entity bean.
bean-managed transactionA transaction whose boundaries are defined by an enterprise bean.
325
er-f an
ules
t of
to
the
of
des:the
iner,ts.
business logicThe code that implements the functionality of an application. In the Entprise JavaBeans model, this logic is implemented by the methods oenterprise bean.
business methodA method of an enterprise bean that implements the business logic or rof an application.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
callback methodsComponent methods called by the container to notify the componenimportant events in its life cycle.
callerSame as caller principal.
caller principalThe principal that identifies the invoker of the enterprise bean method.
client certificate authenticationAn authentication mechanism in which a client uses a X.509 certificateestablish its identity.
commitThe point in a transaction when all updates to any resources involved intransaction are made permanent.
componentAn application-level software unit supported by acontainer. Components areconfigurable at deployment time. The J2EE platform defines four typescomponents:enterprisebeans,webcomponents,applets, andapplicationcli-ents.
component contractThe contract between a component and its container. The contract inclulife cycle management of the component, a context interface thatinstance uses to obtain various information and services from its contaand a list of services that every container must provide for its componen
connectionSeeresource manager connection.
connection factorySeeresource manager connection factory.
326
y torise-rceon-
videdlowsractsxam-
nd
r-
ager
jectsnedge,
dis-
n
connectorA standard extension mechanism for containers to provide connectivitenterprise information systems. A connector is specific to an enterpinformation system and consists of aresourceadapter and application development tools for enterprise information system connectivity. The resouadapter is plugged in to a container through its support for system-level ctracts defined in the connector architecture.
Connector architectureAn architecture for integration of J2EE products withenterpriseinformationsystems. There are two parts to this architecture: a resource adapter proby an enterprise information system vendor and the J2EE product that althis resource adapter to plug in. This architecture defines a set of contthat a resource adapter has to support to plug in to a J2EE product, for eple, transactions, security, and resource management.
containerAn entity that provides life cycle management, security, deployment, aruntime services tocomponents. Each type of container (EJB, web, JSP,servlet,applet, andapplicationclient) also provides component-specific sevices.
container-managed persistenceData transfer between an entity bean’s variables and a resource manmanaged by the entity bean’s container.
container-managed transactionA transaction whose boundaries are defined by an EJB container. Anentitybean must use container-managed transactions.
context attributeAn object bound into the context associated with a servlet.
conversational stateThe field values of a session bean plus the transitive closure of the obreachable from the bean’s fields. The transitive closure of a bean is defiin terms of the serialization protocol for the Java programming languathat is, the fields that would be stored by serializing the bean instance.
CORBACommon Object Request Broker Architecture. A language independent,tributed object model specified by the Object Management Group.
create methodA method defined in thehomeinterface and invoked by a client to create aenterprise bean.
327
ntsion
a
ty
nal
ent.
owent
ndlve.
e or
ebmes-to a. Thetain
imepi-
credentialsThe information describing the security attributes of aprincipal.
CSSCascading Style Sheet. A stylesheet used with HTML and XML documeto add a style to all elements marked with a particular tag, for the directof browsers or other presentation mechanisms.
CTSCompatibility Test Suite. A suite of compatibility tests for verifying thatJ2EE product complies with the J2EE platform specification.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
delegationAn act whereby oneprincipal authorizes another principal to use its identior privileges with some restrictions.
DeployerA person who installs modules and J2EE applications into an operatioenvironment.
deploymentThe process whereby software is installed into an operational environm
deployment descriptorAn XML file provided with each module and application that describes hthey should be deployed. The deployment descriptor directs a deploymtool to deploy a module or application with specific container options adescribes specific configuration requirements that a Deployer must reso
destinationA JMS administered object that encapsulates the identity of a JMS queutopic. Seepoint-to-point messagingsystem,publish/subscribemessagingsystem.
digest authenticationAn authentication mechanism in which a web client authenticates to a wserver by sending the server a message digest along its HTTP requestsage. The digest is computed by employing a one-way hash algorithmconcatenation of the HTTP request message and the client’s passworddigest is typically much smaller than the HTTP request, and doesn’t conthe password.
distributed applicationAn application made up of distinct components running in separate runtenvironments, usually on different platforms connected via a network. Ty
328
nt-le
the.
f a
se is
chi-ansion,y an
theed
ancon-riseform
cal distributed applications are two-tier (client-server), three-tier (cliemiddleware-server), and multitier (client-multiple middleware-multipservers).
DOMDocument Object Model. A tree of objects with interfaces for traversingtree and writing anXML version of it, as defined by the W3C specification
DTDDocument Type Definition. A description of the structure and properties oclass ofXML files.
durable subscriptionIn a JMSpublish/subscribemessagingsystem, a subscription that continueto exist whether or not there is a current active subscriber object. If therno active subscriber, JMS retains the subscription’smessages until they arereceived by the subscription or until they expire.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
EAR fileA JAR archive that contains a J2EE application.
EJB™See Enterprise JavaBeans.
EJB containerA container that implements the EJB component contract of the J2EE artecture. This contract specifies a runtime environment for enterprise bethat includes security, concurrency, life cycle management, transactdeployment, naming, and other services. An EJB container is provided bEJB orJ2EE server.
EJB Container ProviderA vendor that supplies an EJB container.
EJB contextAn object that allows an enterprise bean to invoke services provided bycontainer and to obtain the information about the caller of a client-invokmethod.
EJB home objectAn object that provides the life cycle operations (create, remove, find) forenterprise bean. The class for the EJB home object is generated by thetainer’s deployment tools. The EJB home object implements the enterpbean’s home interface. The client references an EJB home object to per
329
EJB
EJB
e. Aayscon-
-rveran-by aneen
.
sides
lingions acli-
tionnsac-
lityem, action
life cycle operations on an EJB object. The client uses JNDI to locate anhome object.
EJB JAR fileA JAR archive that contains an EJB module.
EJB moduleA software unit that consists of one or more enterprise beans and andeployment descriptor.
EJB objectAn object whose class implements the enterprise bean’s remote interfacclient never references an enterprise bean instance directly; a client alwreferences an EJB object. The class of an EJB object is generated by atainer’s deployment tools.
EJB serverSoftware provides services to anEJB container. For example, an EJB container typically relies on a transaction manager that is part of the EJB seto perform the two-phase commit across all the participating resource magers. The J2EE architecture assumes that an EJB container is hostedEJB server from the same vendor, so does not specify the contract betwthese two entities. An EJB server may host one or more EJB containers
EJB Server ProviderA vendor that supplies an EJB server.
enterprise beanA component that implements a business task or business entity and rein an EJB container; either anentity bean,sessionbean, ormessage-drivenbean.
enterprise information systemThe applications that comprise an enterprise’s existing system for handcompany-wide information. These applications provide an informatinfrastructure for an enterprise. An enterprise information system offerwell defined set of services to its clients. These services are exposed toents as local and/or remote interfaces. Examples of enterprise informasystems include: enterprise resource planning systems, mainframe tration processing systems, and legacy database systems.
enterprise information system resourceAn entity that provides enterprise information system-specific functionato its clients. Examples are: a record or set of records in a database systbusiness object in an enterprise resource planning system, and a transaprogram in a transaction processing system.
330
motem in
ect-enl, and
base.unc-n-ary
t ortts forouldfilter
n
ica-
Enterprise Bean ProviderAn application programmer who produces enterprise bean classes, reand home interfaces, and deployment descriptor files, and packages thean EJB JAR file.
Enterprise JavaBeans™ (EJB™)A component architecture for the development and deployment of objoriented, distributed, enterprise-level applications. Applications writtusing the Enterprise JavaBeans architecture are scalable, transactionasecure.
entity beanAn enterprise bean that represents persistent data maintained in a dataAn entity bean can manage its own persistence or it can delegate this ftion to its container. An entity bean is identified by a primary key. If the cotainer in which an entity bean is hosted crashes, the entity bean, its primkey, and any remote references survive the crash.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
filterAn object that can transform the header and/or content of a requesresponse. Filters differ fromweb components in that they usually do nothemselves create responses but rather they modify or adapt the requesa resource, and modify or adapt responses from a resource. A filter shnot have any dependencies on a web resource for which it is acting as aso that it can be composable with more than one type of web resource.
finder methodA method defined in thehomeinterface and invoked by a client to locate aentity bean.
form-based authenticationAn authentication mechanism in which a web container provides an appltion-specific form for logging in.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
groupA collection of principals within a given security policy domain.
331
an-ean.
srfaceinter-
e. Alized
ntsdeotext
textnt to
therts
on is
tosys-
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
handleAn object that identifies an enterprise bean. A client may serialize the hdle, and then later deserialize it to obtain a reference to the enterprise b
home interfaceOne of two interfaces for anenterprisebean. The home interface definezero or more methods for managing an enterprise bean. The home inteof a session bean defines create and remove methods, while the homeface of an entity bean defines create, finder, and remove methods.
home handleAn object that can be used to obtain a reference of the home interfachome handle can be serialized and written to stable storage and deseriato obtain the reference.
HTMLHypertext Markup Language. A markup language for hypertext documeon the Internet. HTML enables the embedding of images, sounds, vistreams, form fields, references to other objects with URLs and basicformatting.
HTTPHypertext Transfer Protocol. The Internet protocol used to fetch hyperobjects from remote hosts. HTTP messages consist of requests from clieserver and responses from server to client.
HTTPSHTTP layered over the SSL protocol.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
impersonationAn act whereby one entity assumes the identity and privileges of anoentity without restrictions and without any indication visible to the recipienof the impersonator’s calls that delegation has taken place. Impersonatia case of simpledelegation.
IDLInterface Definition Language. A language used to define interfacesremote CORBA objects. The interfaces are independent of operatingtems and programming languages.
332
en
r aloy-uted
ted
heter-ng
IIOPInternet Inter-ORB Protocol. A protocol used for communication betweCORBA object request brokers.
initialization parameterA parameter that initializes the context associated with a servlet.
ISVIndependent Software Vendor.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
J2EE™SeeJava 2 Platform, Enterprise Edition.
J2ME™SeeJava 2 Platform, Micro Edition.
J2SE™SeeJava 2 Platform, Standard Edition.
J2EE applicationAny deployable unit of J2EE functionality. This can be a single module ogroup of modules packaged into an .ear file with a J2EE application depment descriptor. J2EE applications are typically engineered to be distribacross multiple computing tiers.
J2EE productAn implementation that conforms to the J2EE platform specification.
J2EE Product ProviderA vendor that supplies a J2EE product.
J2EE serverThe runtime portion of a J2EE product. A J2EE server providesEJB and/orweb containers.
JAR Java ARchiveA platform-independent file format that permits many files to be aggregainto one file.
Java™ 2 Platform, Enterprise Edition (J2EE)An environment for developing and deploying enterprise applications. TJ2EE platform consists of a set of services, application programming infaces (APIs), and protocols that provide the functionality for developimultitiered, web-based applications.
333
on-l set-
es
ies,
s.
JTAvice
sederty
a-s toP.
ents,ntentin
orm
Java™ 2 Platform, Micro Edition (J2SE)A highly optimized Java runtime environment targeting a wide range of csumer products, including pagers, cellular phones, screenphones, digitatop boxes and car navigation systems.
Java™ 2 Platform, Standard Edition (J2SE)The core Java technology platform.
Java™ 2 SDK, Enterprise Edition (J2EE SDK)Sun’s implementation of the J2EE platform. This implementation providan operational definition of the J2EE platform.
Java™ Message Service (JMS)An API for using enterprise messaging systems such as IBM MQ SerTIBCO Rendezvous, and so on.
Java Naming and Directory Interface™ (JNDI)An API that provides naming and directory functionality.
Java™ Transaction API (JTA)An API that allows applications and J2EE servers to access transaction
Java™ Transaction Service (JTS)Specifies the implementation of a transaction manager which supportsand implements the Java mapping of the OMG Object Transaction Ser(OTS) 1.1 specification at the level below the API.
JavaBeans™ componentA Java class that can be manipulated in a visual builder tool and compointo applications. A JavaBeans component must adhere to certain propand event interface conventions.
Java IDLA technology that provides CORBA interoperability and connectivity capbilities for the J2EE platform. These capabilities enable J2EE applicationinvoke operations on remote network services using the OMG IDL and IIO
JavaMail™An API for sending and receiving email.
JavaServer Pages™ (JSP™)An extensible web technology that uses template data, custom elemscripting languages, and server-side Java objects to return dynamic coto a client. Typically the template data is HTML or XML elements, andmany cases the client is a web browser.
JDBC™An API for database-independent connectivity between the J2EE platfand a wide range of data sources.
334
es-
dis-
jectsorcan
d a
to a
nol-, and
JMSSeeJava Message Service.
JMS administered objectA preconfigured JMS object (aresourcemanagerconnectionfactory or adestination) created by an administrator for the use ofJMS clients andplaced in aJNDI namespace.
JMS applicationOne or moreJMS clients that exchangemessages.
JMS clientA Java language program that sends and/or receivesmessages.
JMS providerA messaging system that implements theJava MessageService as well asother administrative and control functionality needed in a full-featured msaging product.
JMS sessionA single-threaded context for sending and receiving JMSmessages. A JMSsession can be non-transacted, locally transacted, or participating in atributed transaction.
JNDISeeJava Naming and Directory Interface.
JSPSeeJavaServer Pages.
JSP actionA JSP element that can act on implicit objects and other server-side obor can define new scripting variables. Actions follow the XML syntax felements with a start tag, a body and an end tag; if the body is empty italso use the empty tag syntax. The tag must use a prefix.
JSP action, customAn action described in a portable manner by a tag library descriptor ancollection of Java classes and imported into a JSP page by ataglib direc-tive. A custom action is invoked when a JSP page uses a custom tag.
JSP action, standardAn action that is defined in the JSP specification and is always availableJSP file without being imported.
JSP applicationA stand-alone web application, written using the JavaServer Pages techogy, that can contain JSP pages, servlets, HTML files, images, appletsJavaBeans components.
335
ableg on
JSP
ter-
ent
that
file
that
ytingyntax
theribese is
JSP containerA container that provides the same services as aservletcontainer and anengine that interprets and processes JSP pages into a servlet.
JSP container, distributedA JSP container that can run a web application that is tagged as distributand is spread across multiple Java virtual machines that might be runnindifferent hosts.
JSP declarationA JSP scripting element that declares methods, variables, or both in afile.
JSP directiveA JSP element that gives an instruction to the JSP container and is inpreted at translation time.
JSP elementA portion of a JSP page that is recognized by a JSP translator. An elemcan be adirective, anaction, or ascripting element.
JSP expressionA scripting element that contains a valid scripting language expressionis evaluated, converted to aString, and placed into the implicitout object.
JSP fileA file that contains a JSP page. In the Servlet 2.2 specification, a JSPmust have a .jsp extension.
JSP pageA text-based document using fixed template data and JSP elementsdescribes how to process a request to create a response.
JSP scripting elementA JSPdeclaration,scriptlet, orexpression, whose tag syntax is defined bthe JSP specification, and whose content is written according to the scriplanguage used in the JSP page. The JSP specification describes the sand semantics for the case where the language page attribute is "java".
JSP scriptletA JSP scripting element containing any code fragment that is valid inscripting language used in the JSP page. The JSP specification descwhat is a valid scriptlet for the case where the language page attribut"java".
336
at isle ass.
tag
nenting
or
thaty be
riseplica-
hatman., inons.
JSP tagA piece of text between a left angle bracket and a right angle bracket thused in a JSP file as part of a JSP element. The tag is distinguishabmarkup, as opposed to data, because it is surrounded by angle bracket
JSP tag libraryA collection of custom tags identifying custom actions described via alibrary descriptor and Java classes.
JTASeeJava Transaction API.
JTSSeeJava Transaction Service.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
life cycleThe framework events of a component’s existence. Each type of compohas defining events which mark its transition into states where it has varyavailability for use. For example, a servlet is created and has itsinit methodcalled by its container prior to invocation of its service method by clientsother servlets who require its functionality. After the call of itsinit methodit has the data and readiness for its intended use. The servlet’sdestroy
method is called by its container prior to the ending of its existence soprocessing associated with winding up may be done, and resources mareleased. Theinit anddestroy methods in this example arecallbackmeth-ods. Similar considerations apply to all J2EE component types: enterpbeans (EJBs), web components (servlets or JSP pages), applets, and aption clients.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
messageIn theJava MessageService, an asynchronous request, report, or event tis created, sent, and consumed by an enterprise application, not by a huIt contains vital information needed to coordinate enterprise applicationsthe form of precisely formatted data that describes specific business acti
337
sage-maydata-
h the
or
amehree
of
and
d tots thes aent
e
MessageConsumerAn object created by aJMSsession that is used for receivingmessages sentto adestination.
MessageProducerAn object created by aJMS session that is used for sendingmessages to adestination.
message-driven beanAn enterprise bean that is an asynchronous message consumer. A mesdriven bean has no state for a specific client, but its instance variablescontain state across the handling of client messages, including an openbase connection and an object reference to anEJBobject. A client accesses amessage-driven bean by sending messages to the destination for whicmessage-driven bean is a message listener.
method permissionAn authorization rule that determines who is permitted to execute onemore enterprise bean methods.
moduleA software unit that consists of one or more J2EE components of the scontainer type and one deployment descriptor of that type. There are ttypes of modules:EJB, web, and application client. Modules can bedeployed as stand-alone units or assembled into an application.
mutual authenticationAn authentication mechanism employed by two parties for the purposeproving each other’s identity to one another.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
naming contextA set of associations between unique, atomic, people-friendly identifiersobjects.
naming environmentA mechanism that allows a component to be customized without the neeaccess or change the component’s source code. A container implemencomponent’s naming environment, and provides it to the component aJNDI namingcontext. Each component names and accesses its environmentries using thejava:comp/env JNDI context. The environment entries ardeclaratively specified in the component’s deployment descriptor.
338
t API
and
is
it
dary
nce
pli-
the
that
non-JMS clientA messaging client program that uses a message system’s native clieninstead of theJava Message Service.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
ORBObject Request Broker. A library than enables CORBA objects to locatecommunicate with one another.
OS principalA principal native to the operating system on which the J2EE platformexecuting.
OTSObject Transaction Service. A definition of the interfaces that permCORBA objects to participate in transactions.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
passivationThe process of transferring an enterprise bean from memory to seconstorage. (Seeactivation.)
persistenceThe protocol for transferring the state of an entity bean between its instavariables and an underlying database.
POAPortable Object Adapter. A CORBA standard for building server-side apcations that are portable across heterogeneous ORBs.
point-to-point message systemA messaging system built around the concept of message queues. Eachmes-sage is addressed to a specific queue; clients extract messages fromqueue(s) established to hold their messages.
principalThe identity assigned to an user as a result of authentication.
privilegeA security attribute that does not have the property of uniqueness andmay be shared by many principals.
primary keyAn object that uniquely identifies an entity bean within a home.
339
ns andtemub-
Pro-aces,
sted
s
n
pli-rceail-lientpo-pter)prisete to
publish/subscribe message systemA messaging system in which clients addressmessages to a specific node ia content hierarchy. Publishers and subscribers are generally anonymoumay dynamically publish or subscribe to the content hierarchy. The systakes care of distributing the messages arriving from a node’s multiple plishers to its multiple subscribers.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
queueSeepoint-to-point messaging system.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
realmSee security policy domain. Also, a string, passed as part of an HTTrequest duringbasicauthentication, that defines a protection space. The ptected resources on a server can be partitioned into a set of protection speach with its own authentication scheme and/or authorization database.
re-entrant entity beanAn entity bean that can handle multiple simultaneous, interleaved, or neinvocations which will not interfere with each other.
Reference ImplementationSeeJava 2 SDK, Enterprise Edition.
remote interfaceOne of two interfaces for anenterprisebean. The remote interface definethe business methods callable by a client.
remove methodMethod defined in thehomeinterface and invoked by a client to destroy aenterprise bean.
resource adapterA system-level software driver that is used by an EJB container or an apcation client to connect to an enterprise information system. A resouadapter is typically specific to an enterprise information system. It is avable as a library and is used within the address space of the server or cusing it. A resource adapter plugs in to a container. The application comnents deployed on the container then use the client API (exposed by adaor tool generated high-level abstractions to access the underlying enterinformation system. The resource adapter and EJB container collabora
340
tion
ipatessac-e or
ned
infer-
ry
es.
entare:
onecu-
the
lled
provide the underlying mechanisms—transactions, security, and connecpooling—for connectivity to the enterprise information system.
resource managerProvides access to a set of shared resources. A resource manager particin transactions that are externally controlled and coordinated by a trantion manager. A resource manager is typically in different address spacon a different machine from the clients that access it. Note: Anenterpriseinformationsystem is referred to as resource manager when it is mentioin the context of resource and transaction management.
resource manager connectionAn object that represents a session with a resource manager.
resource manager connection factoryAn object used for creating a resource manager connection.
RMIRemote Method Invocation. A technology that allows an object runningone Java virtual machine to invoke methods on an object running in a difent Java virtual machine.
RMI-IIOPA version of RMI implemented to use the CORBA IIOP protocol. RMI oveIIOP provides interoperability with CORBA objects implemented in anlanguage if all the remote interfaces are originally defined as RMI interfac
role (development)The function performed by a party in the development and deploymphases of an application developed using J2EE technology. The rolesApplication ComponentProvider, Application Assembler,Deployer, J2EEProductProvider, EJB ContainerProvider, EJB Server Provider, Web Con-tainerProvider, Web Server Provider, Tool Provider, andSystemAdminis-trator.
role (security)An abstract logical grouping of users that is defined by the ApplicatiAssembler. When an application is deployed, the roles are mapped to srity identities, such asprincipals orgroups, in the operational environment.
role mappingThe process of associating the groups and/or principals recognized bycontainer to security roles specified in thedeploymentdescriptor. Securityroles have to be mapped by the Deployer before the component is instain the server.
341
the
ss-
beEE
. A
urity
the.
ust
rityci-serss.
ecu--
rollbackThe point in a transaction when all updates to any resources involved intransaction are reversed.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
SAXSimple API forXML. An event-driven, serial-access mechanism for acceing XML documents.
security attributesA set of properties associated with a principal. Security attributes canassociated with a principal by an authentication protocol and/or by a J2Product Provider.
security constraintA declarative way to annotate the intended protection of web contentsecurity constraint consists of aweb resourcecollection, anauthorizationconstraint, and auser data constraint.
security contextAn object that encapsulates the shared state information regarding secbetween two entities.
security permissionA mechanism, defined by J2SE, used by the J2EE platform to expressprogramming restrictions imposed on Application Component Providers
security permission setThe minimum set of security permissions that a J2EE Product Provider mprovide for the execution of each component type.
security policy domainA scope over which security policies are defined and enforced by a secuadministrator. A security policy domain has a collection of users (or prinpals), uses a well defined authentication protocol(s) for authenticating u(or principals), and may have groups to simplify setting of security policie
security roleSeerole (security).
security technology domainA scope over which the same security mechanism is used to enforce a srity policy. Multiple security policy domains can exist within a single technology domain.
security viewThe set of security roles defined by the Application Assembler.
342
tingnse
andet con-t may
but-n the
chtainrvlets
ng is
ica-
forpera-ile astemintainmain-st beage
thein a
server principalThe OS principal that the server is executing as.
servletA Java program that extends the functionality of a web server, generadynamic content and interacting with web clients using a request-respoparadigm.
servlet containerA container that provides the network services over which requestsresponses are sent, decodes requests, and formats responses. All servltainers must support HTTP as a protocol for requests and responses, bualso support additional request-response protocols such as HTTPS.
servlet container, distributedA servlet container that can run a web application that is tagged as distriable and that executes across multiple Java virtual machines running osame host or on different hosts.
servlet contextAn object that contains a servlet’s view of the web application within whithe servlet is running. Using the context, a servlet can log events, obURL references to resources, and set and store attributes that other sein the context can use.
servlet mappingDefines an association between a URL pattern and a servlet. The mappiused to map requests to servlets.
sessionAn object used by a servlet to track a user’s interaction with a web appltion across multiple HTTP requests.
session beanAn enterprise bean that is created by a client and that usually exists onlythe duration of a single client-server session. A session bean performs otions, such as calculations or accessing a database, for the client. Whsession bean may be transactional, it is not recoverable should a sycrash occur. Session bean objects can be either stateless or they can maconversational state across methods and transactions. If a session beantains state, then the EJB container manages this state if the object muremoved from memory. However, the session bean object itself must manits own persistent data.
SSLSecure Socket Layer. A security protocol that provides privacy overInternet. The protocol allows client-server applications to communicate
343
ways
uage
ate-s forfunc-pro-ver.
ses-
se’s
orac-
sedriseing
by aodi-
way that cannot be eavesdropped or tampered with. Servers are alauthenticated and clients are optionally authenticated.
SQLStructured Query Language. The standardized relational database langfor defining database objects and manipulating data.
SQL/JA set of standards that includes specifications for embedding SQL stments in methods in the Java programming language and specificationcalling Java static methods as SQL stored procedures and user-definedtions. An SQL checker can detects errors in static SQL statements atgram development time, rather than at execution time as with a JDBC dri
stateful session beanA session bean with a conversational state.
stateless session beanA session bean with no conversational state. All instances of a statelesssion bean are identical.
System AdministratorThe person responsible for configuring and administering the enterpricomputers, networks, and software systems.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
topicSeepublish-subscribe messaging system.
transactionAn atomic unit of work that modifies data. A transaction encloses onemore program statements, all of which either complete or roll back. Transtions enable multiple users to access the same data concurrently.
transaction attributeA value specified in an enterprise bean’s deployment descriptor that is uby the EJB container to control the transaction scope when the enterpbean’s methods are invoked. A transaction attribute can have the followvalues: Required, RequiresNew, Supports, NotSupported, Mandatory,Never.
transaction isolation levelThe degree to which the intermediate state of the data being modifiedtransaction is visible to other concurrent transactions and data being mfied by other transactions is visible to it.
344
nsac-, and
lop-
ng
er-
an
o-
ists
thisaseptyend
ping
ath
uttityto
transaction managerProvides the services and management functions required to support tration demarcation, transactional resource management, synchronizationtransaction context propagation.
Tool ProviderAn organization or software vendor that provides tools used for the devement, packaging, and deployment of J2EE applications.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
URIUniform Resource Identifier. A compact string of characters for identifyian abstract or physical resource. A URI is either aURL or aURN. URLs andURNs are concrete entities that actually exist; A URI is an abstract supclass.
URLUniform Resource Locator. A standard for writing a textual reference toarbitrary piece of data in the World Wide Web. A URL looks likeproto-col://host/localinfo whereprotocol specifies a protocol for fetchingthe object (such as HTTP or FTP),host specifies the Internet name of thetargeted host, andlocalinfo is a string (often a file name) passed to the prtocol handler on the remote host.
URL pathThe URL passed by a HTTP request to invoke a servlet. The URL consof the Context Path + Servlet Path + Path Info, where
• Context Path is the path prefix associated with a servlet context thatservlet is a part of. If this context is the default context rooted at the bof the web server’s URL namespace, the path prefix will be an emstring. Otherwise, the path prefix starts with a / character but does notwith a / character.
• Servlet Path is the path section that directly corresponds to the mapwhich activated this request. This path starts with a / character.
• Path Info is the part of the request path that is not part of the Context Por the Servlet Path.
URNUniform Resource Name. A unique identifier that identifies an entity, bdoesn’t tell where it is located. A system can use a URN to look up an enlocally before trying to find it on the web. It also allows the web locationchange, while still allowing the entity to be found.
345
cted.en-
h-t with
beualent
chi-entsion,viceseb
ableame
user data constraintIndicates how data between a client and a web container should be proteThe protection can be the prevention of tampering with the data or prevtion of eavesdropping on the data.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
WAR fileA JAR archive that contains a web module.
web applicationAn application written for the Internet, including those built with Java tecnologies such as JavaServer Pages and servlets, as well as those builnon-Java technologies such as CGI and Perl.
web application, distributableA web application that uses J2EE technology written so that it candeployed in a web container distributed across multiple Java virtmachines running on the same host or different hosts. The deploymdescriptor for such an application uses the distributable element.
web componentA component that provides services in response to requests; either aservletor aJSP page.
web containerA container that implements the web component contract of the J2EE artecture. This contract specifies a runtime environment for web componthat includes security, concurrency, life cycle management, transactdeployment, and other services. A web container provides the same seras aJSPcontainer and a federated view of the J2EE platform APIs. A wcontainer is provided by aweb orJ2EE server.
web container, distributedA web container that can run a web application that is tagged as distributand that executes across multiple Java virtual machines running on the shost or on different hosts.
Web Container ProviderA vendor that supplies a web container.
346
ent
s to
r antherserv-rverlyrchi-
thees. A
fineoc-onlya-
re ittypes
asionof
ter-EEed
web moduleA unit that consists of one or more web components and a web deploymdescriptor.
web resource collectionA list of URL patterns and HTTP methods that describe a set of resourcebe protected.
web serverSoftware that provides services to access the Internet, an intranet, oextranet. A web server hosts web sites, provides support for HTTP and oprotocols, and executes server-side programs (such as CGI scripts orlets) that perform certain functions. In the J2EE architecture, a web seprovides services to awebcontainer. For example, a web container typicalrelies on a web server to provide HTTP message handling. The J2EE atecture assumes that a web container is hosted by a web server fromsame vendor, so does not specify the contract between these two entitiweb server may host one or more web containers.
Web Server ProviderA vendor that supplies a web server.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
XMLExtensible Markup Language. A markup language that allows you to dethe tags (markup) needed to identify the content, data, and text, in XML duments. It differs fromHTML the markup language most often used tpresent information on the internet. HTML has fixed tags that deal maiwith style or presentation. An XML document must undergo a transformtion into a language with style tags under the control of a stylesheet befocan be presented by a browser or other presentation mechanism. Twoof style sheets used with XML areCSS andXSL. Typically, XML is trans-formed into HTML for presentation. Although tags may be definedneeded in the generation of an XML document, a Document Type Definit( DTD) may be used to define the elements allowed in a particular typedocument. A document may be compared with the rules in the DTD to demine its validity and to locate particular elements in the document. J2deployment descriptors are expressed in XML with DTDs defining allowelements. Programs for processing XML documents useSAX or DOMAPIs. J2EEdeployment descriptors are expressed in XML.
347
e-actedowforich
.
n-n-erly
XSLExtensible Stylesheet Language. AnXML transformation language used fortransforming XML documents into documents with flow object tags for prsentation purposes. The transformation aspect of XSL has been abstrinto XSLT with the XSL name now used to designate the presentation fllanguage. XSL is a direct descendent of the DSSSL style languageSGML (Standard Generalized Markup Language), the language from whXML was subsetted. It was designed to have all the capabilities ofCSS, thestylesheet often used withHTML. XSL flow objects can be presented byspecialized browsers, and themselves transformed into PDF documents
XSLTXSL Transformation. An XML file that controls the transformation of aXML document into another XML document or HTML. The target document often will have presentation related tags dictating how it will be redered by a browser or other presentation mechanism. XSLT was formpart of XSL, which also included a tag language of style flow objects.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
348
dnt
op-
i-
K.
-
Bios For ContribuingAuthors
Topic Bio
Web Components
Stephanie Bodoff is a staff writer at Sun Microsystems. She has beeninvolved with object-oriented enterprise software since graduating fromColumbia University with an M.S. in electrical engineering. For severalyears she worked as a software engineer on distributed computing antelecommunications systems and object-oriented software developmemethods. As a technical writer Stephanie has documented object-ori-ented databases, application servers, and enterprise application develment methods. She is a co-author ofDesigning Enterprise Applicationswith the Java™ 2 Platform, Enterprise Edition andObject-OrientedSoftware Development: The Fusion Method.
EnterpriseJavaBeans
Dale Green is a staff writer with Sun Microsystems, where he docu-ments the J2EE™ platform. In previous positions he programmed busness applications, designed databases, taught technical classes, anddocumented RDBMS products. He wrote the internationalization andreflection trails for the Java Tutorial Continued. In his current positionhe writes about Enterprise JavaBeans™ technology and the J2EE SD
Security
Eric Jendrock is a staff writer with Sun Microsystems, where he docu-ments the J2EE platform. Previously, he documented middleware products and standards. Currently, he writes about the J2EE CompatibilityTest Suite and J2EE security.
349
350
si-
r-r-
e
Overview
Monica Pawlan is a staff writer for the Java Developer Connection(JDC), and was a contributing author for the Java Tutorial. She is theauthor ofEssentials of the Java Programming Language: A Hands-OnGuideand co-author ofAdvanced Programming for the Java 2 Platform.She has a background in 2D and 3D graphics, security, and databaseproducts, and loves to study and write about emerging technologies.When not writing, she spends her spare time gardening, studying clascal piano, and dreaming of far away places—some of which she occa-sionally visits.
J2EE ConnectorTechnology
Beth Stearnsis the president of Computer Ease Publishing, a computeconsulting firm she founded in 1982. Her client list includes Sun Microsystems Inc., Silicon Graphics Inc., Oracle Corporation, and Xerox Coporation, among others. HerUnderstanding EDT, a guide to DigitalEquipment Corporation’s text editor, has sold throughout the world. Shereceived her B.S. degree from Cornell University and a master’s degrefrom Adelphi University. Beth wrote the JNI trail for the Java Tutorial.She is a co-author ofApplying Enterprise JavaBeans: Component-BasedDevelopment for the J2EE Platform.
Topic Bio