The Java EE 5 Tutorial - Lia

glueblacksmithInternet and Web Development

Nov 13, 2013 (3 years and 6 months ago)

968 views

TheJavaEE5Tutorial
For SunJava SystemApplicationServer 9.1
SunMicrosystems,Inc.
4150 Network Circle
Santa Clara,CA95054
U.S.A.
Part No:819–3669–10
September 2007
Copyright 2007 SunMicrosystems,Inc.4150 Network Circle,Santa Clara,CA95054 U.S.A.All rights reserved.
SunMicrosystems,Inc.has intellectual property rights relating to technology embodied inthe product that is described inthis document.Inparticular,and without
limitation,these intellectual property rights may include one or more U.S.patents or pending patent applications inthe U.S.and inother countries.
U.S.Government Rights – Commercial software.Government users are subject to the SunMicrosystems,Inc.standard license agreement and applicable provisions
of the FARand its supplements.
This distributionmay include materials developed by third parties.
Parts of the product may be derived fromBerkeley BSDsystems,licensed fromthe University of California.UNIXis a registered trademark inthe U.S.and other
countries,exclusively licensed through X/OpenCompany,Ltd.
Sun,SunMicrosystems,the Sunlogo,the Solaris logo,the Java Coffee Cup logo,docs.sun.com,Java,and Solaris are trademarks or registered trademarks of Sun
Microsystems,Inc.inthe U.S.and other countries.All SPARCtrademarks are used under license and are trademarks or registered trademarks of SPARC
International,Inc.inthe U.S.and other countries.Products bearing SPARCtrademarks are based uponanarchitecture developed by SunMicrosystems,Inc.
The OPENLOOKand Sun
TM
Graphical User Interface was developed by SunMicrosystems,Inc.for its users and licensees.Sunacknowledges the pioneering efforts
of Xerox inresearching and developing the concept of visual or graphical user interfaces for the computer industry.Sunholds a non-exclusive license fromXerox to
the Xerox Graphical User Interface,which license also covers Sun's licensees who implement OPENLOOKGUIs and otherwise comply with Sun's writtenlicense
agreements.
Products covered by and informationcontained inthis publicationare controlled by U.S.Export Control laws and may be subject to the export or import laws in
other countries.Nuclear,missile,chemical or biological weapons or nuclear maritime end uses or end users,whether direct or indirect,are strictly prohibited.Export
or reexport to countries subject to U.S.embargo or to entities identified onU.S.export exclusionlists,including,but not limited to,the denied persons and specially
designated nationals lists is strictly prohibited.
DOCUMENTATIONIS PROVIDED“AS IS” ANDALL EXPRESS ORIMPLIEDCONDITIONS,REPRESENTATIONS ANDWARRANTIES,INCLUDINGANY
IMPLIEDWARRANTYOF MERCHANTABILITY,FITNESS FORAPARTICULARPURPOSEORNON-INFRINGEMENT,AREDISCLAIMED,EXCEPTTO
THEEXTENTTHATSUCHDISCLAIMERS AREHELDTOBELEGALLYINVALID.
Copyright 2007 SunMicrosystems,Inc.4150 Network Circle,Santa Clara,CA95054 U.S.A.Tous droits réservés.
SunMicrosystems,Inc.détient les droits de propriété intellectuelle relatifs à la technologie incorporée dans le produit qui est décrit dans ce document.Enparticulier,
et ce sans limitation,ces droits de propriété intellectuelle peuvent inclure unou plusieurs brevets américains ou des applications de brevet enattente aux Etats-Unis
et dans d'autres pays.
Cette distributionpeut comprendre des composants développés par des tierces personnes.
Certaines composants de ce produit peuvent être dérivées du logiciel Berkeley BSD,licenciés par l'Université de Californie.UNIXest une marque déposée aux
Etats-Unis et dans d'autres pays;elle est licenciée exclusivement par X/OpenCompany,Ltd.
Sun,SunMicrosystems,le logo Sun,le logo Solaris,le logo Java Coffee Cup,docs.sun.com,Java et Solaris sont des marques de fabrique ou des marques déposées de
SunMicrosystems,Inc.aux Etats-Unis et dans d'autres pays.Toutes les marques SPARCsont utilisées sous licence et sont des marques de fabrique ou des marques
déposées de SPARCInternational,Inc.aux Etats-Unis et dans d'autres pays.Les produits portant les marques SPARCsont basés sur une architecture développée par
SunMicrosystems,Inc.
L'interface d'utilisationgraphique OPENLOOKet Suna été développée par SunMicrosystems,Inc.pour ses utilisateurs et licenciés.Sunreconnaît les efforts de
pionniers de Xerox pour la recherche et le développement du concept des interfaces d'utilisationvisuelle ou graphique pour l'industrie de l'informatique.Sundétient
une licence nonexclusive de Xerox sur l'interface d'utilisationgraphique Xerox,cette licence couvrant également les licenciés de Sunqui mettent enplace l'interface
d'utilisationgraphique OPENLOOKet qui,enoutre,se conforment aux licences écrites de Sun.
Les produits qui font l'objet de cette publicationet les informations qu'il contient sont régis par la legislationaméricaine enmatière de contrôle des exportations et
peuvent être soumis au droit d'autres pays dans le domaine des exportations et importations.Les utilisations finales,ou utilisateurs finaux,pour des armes nucléaires,
des missiles,des armes chimiques ou biologiques ou pour le nucléaire maritime,directement ou indirectement,sont strictement interdites.Les exportations ou
réexportations vers des pays sous embargo des Etats-Unis,ou vers des entités figurant sur les listes d'exclusiond'exportationaméricaines,y compris,mais de manière
nonexclusive,la liste de personnes qui font objet d'unordre de ne pas participer,d'une façondirecte ou indirecte,aux exportations des produits ou des services qui
sont régis par la legislationaméricaine enmatière de contrôle des exportations et la liste de ressortissants spécifiquement designés,sont rigoureusement interdites.
LADOCUMENTATIONESTFOURNIE"ENL'ETAT"ETTOUTES AUTRES CONDITIONS,DECLARATIONS ETGARANTIES EXPRESSES OUTACITES
SONTFORMELLEMENTEXCLUES,DANS LAMESUREAUTORISEEPARLALOI APPLICABLE,YCOMPRIS NOTAMMENTTOUTEGARANTIE
IMPLICITERELATIVEALAQUALITEMARCHANDE,AL'APTITUDEAUNEUTILISATIONPARTICULIEREOUAL'ABSENCEDECONTREFACON.
070918@18741
Contents
Preface...................................................................................................................................................29
Part I Introduction.........................................................................................................................................39
1 Overview...............................................................................................................................................41
Java EEApplicationModel.................................................................................................................42
Distributed Multitiered Applications...............................................................................................42
Security..........................................................................................................................................43
Java EEComponents...................................................................................................................44
Java EEClients..............................................................................................................................44
Web Components........................................................................................................................46
Business Components.................................................................................................................47
Enterprise InformationSystemTier..........................................................................................48
Java EEContainers..............................................................................................................................48
Container Services.......................................................................................................................49
Container Types...........................................................................................................................49
Web Services Support.........................................................................................................................51
XML...............................................................................................................................................51
SOAPTransport Protocol...........................................................................................................52
WSDL Standard Format..............................................................................................................52
UDDI and ebXML Standard Formats.......................................................................................52
Java EEApplicationAssembly and Deployment.............................................................................52
Packaging Applications......................................................................................................................53
Development Roles.............................................................................................................................54
Java EEProduct Provider............................................................................................................55
Tool Provider................................................................................................................................55
ApplicationComponent Provider.............................................................................................55
3
ApplicationAssembler................................................................................................................56
ApplicationDeployer and Administrator.................................................................................56
Java EE5 APIs......................................................................................................................................57
Enterprise JavaBeans Technology..............................................................................................57
Java Servlet Technology..............................................................................................................58
JavaServer Pages Technology.....................................................................................................58
JavaServer Pages Standard Tag Library.....................................................................................58
JavaServer Faces...........................................................................................................................58
Java Message Service API............................................................................................................59
Java TransactionAPI...................................................................................................................59
JavaMail API.................................................................................................................................59
JavaBeans ActivationFramework..............................................................................................59
Java API for XML Processing.....................................................................................................60
Java API for XML Web Services (JAX-WS)..............................................................................60
Java Architecture for XML Binding (JAXB).............................................................................60
SOAPwith Attachments API for Java........................................................................................60
Java API for XML Registries.......................................................................................................61
J2EEConnector Architecture.....................................................................................................61
Java Database Connectivity API.................................................................................................61
Java Persistence API.....................................................................................................................62
Java Naming and Directory Interface........................................................................................62
Java Authenticationand AuthorizationService.......................................................................62
Simplified Systems Integration...................................................................................................63
SunJava SystemApplicationServer PlatformEdition9.................................................................63
Tools..............................................................................................................................................63
2 UsingtheTutorial Examples..............................................................................................................65
Required Software...............................................................................................................................65
Tutorial Bundle............................................................................................................................65
Java Platform,Standard Edition.................................................................................................66
SunJava SystemApplicationServer 9.1.....................................................................................66
NetBeans IDE...............................................................................................................................67
Apache Ant...................................................................................................................................68
Starting and Stopping the ApplicationServer..................................................................................68
Starting the AdminConsole...............................................................................................................69
Contents
The Java EE 5Tutorial • September 20074
Starting and Stopping the Java DBDatabase Server........................................................................69
Building the Examples........................................................................................................................70
Building the Examples Using NetBeans IDE............................................................................70
Building the Examples onthe Command-Line Using Ant.....................................................70
Tutorial Example Directory Structure..............................................................................................71
Debugging Java EEApplications.......................................................................................................72
Using the Server Log....................................................................................................................72
Using a Debugger.........................................................................................................................73
Part II TheWebTier.........................................................................................................................................75
3 GettingStartedwithWebApplications...........................................................................................77
Web Applications................................................................................................................................77
Web ApplicationLife Cycle................................................................................................................80
Web Modules.......................................................................................................................................81
Packaging Web Modules.............................................................................................................83
Deploying a WARFile.................................................................................................................84
Testing Deployed Web Modules................................................................................................85
Listing Deployed Web Modules.................................................................................................86
Updating Web Modules..............................................................................................................86
Undeploying Web Modules........................................................................................................88
Configuring Web Applications..........................................................................................................89
Mapping URLs to Web Components........................................................................................89
Declaring Welcome Files............................................................................................................91
Setting InitializationParameters................................................................................................92
Mapping Errors to Error Screens...............................................................................................93
Declaring Resource References..................................................................................................94
Duke’s Bookstore Examples...............................................................................................................96
Accessing Databases fromWeb Applications..................................................................................97
Populating the Example Database.............................................................................................97
Creating a Data Source inthe ApplicationServer....................................................................98
Further Informationabout Web Applications.................................................................................98
Contents
5
4 JavaServlet Technology.....................................................................................................................99
What Is a Servlet?.................................................................................................................................99
The Example Servlets........................................................................................................................100
Troubleshooting Duke's Bookstore Database Problems.......................................................102
Servlet Life Cycle................................................................................................................................102
Handling Servlet Life-Cycle Events.........................................................................................103
Handling Servlet Errors.............................................................................................................105
Sharing Information.........................................................................................................................105
Using Scope Objects..................................................................................................................105
Controlling Concurrent Access to Shared Resources...........................................................106
Accessing Databases..................................................................................................................107
Initializing a Servlet...........................................................................................................................109
Writing Service Methods..................................................................................................................110
Getting InformationfromRequests........................................................................................110
Constructing Responses............................................................................................................112
Filtering Requests and Responses....................................................................................................114
Programming Filters..................................................................................................................115
Programming Customized Requests and Responses............................................................117
Specifying Filter Mappings.......................................................................................................119
Invoking Other Web Resources.......................................................................................................122
Including Other Resources inthe Response...........................................................................122
Transferring Control to Another Web Component..............................................................124
Accessing the Web Context..............................................................................................................124
Maintaining Client State...................................................................................................................125
Accessing a Session....................................................................................................................125
Associating Objects with a Session..........................................................................................126
SessionManagement.................................................................................................................126
SessionTracking........................................................................................................................127
Finalizing a Servlet.............................................................................................................................128
Tracking Service Requests........................................................................................................129
Notifying Methods to Shut Down............................................................................................129
Creating Polite Long-Running Methods.................................................................................130
Further Informationabout Java Servlet Technology....................................................................131
Contents
The Java EE 5Tutorial • September 20076
5 JavaServer PagesTechnology.........................................................................................................133
What Is a JSPPage?............................................................................................................................133
ASimple JSPPage Example......................................................................................................134
The Example JSPPages.....................................................................................................................136
The Life Cycle of a JSPPage..............................................................................................................142
Translationand Compilation...................................................................................................142
Execution....................................................................................................................................143
Creating Static Content....................................................................................................................144
Response and Page Encoding...................................................................................................145
Creating Dynamic Content..............................................................................................................145
Using Objects withinJSPPages................................................................................................145
Unified ExpressionLanguage..........................................................................................................146
Immediate and Deferred EvaluationSyntax...........................................................................148
Value and Method Expressions................................................................................................150
Defining a Tag Attribute Type..................................................................................................156
Deactivating ExpressionEvaluation........................................................................................157
Literal Expressions.....................................................................................................................158
Resolving Expressions...............................................................................................................160
Implicit Objects..........................................................................................................................162
Operators....................................................................................................................................163
Reserved Words.........................................................................................................................163
Examples of EL Expressions.....................................................................................................164
Functions....................................................................................................................................165
JavaBeans Components....................................................................................................................167
JavaBeans Component DesignConventions..........................................................................167
Creating and Using a JavaBeans Component.........................................................................168
Setting JavaBeans Component Properties..............................................................................169
Retrieving JavaBeans Component Properties........................................................................171
Using CustomTags...........................................................................................................................172
Declaring Tag Libraries.............................................................................................................172
Including the Tag Library Implementation............................................................................174
Reusing Content inJSPPages..........................................................................................................175
Transferring Control to Another Web Component.....................................................................176
jsp:param Element....................................................................................................................176
Including anApplet...........................................................................................................................176
Setting Properties for Groups of JSPPages.....................................................................................179
Contents
7
Deactivating EL ExpressionEvaluation..................................................................................180
Further Informationabout JavaServer Pages Technology...........................................................183
6 JavaServer Pages Documents.........................................................................................................185
The Example JSPDocument............................................................................................................185
Creating a JSPDocument.................................................................................................................188
Declaring Tag Libraries.............................................................................................................190
Including Directives ina JSPDocument.................................................................................191
Creating Static and Dynamic Content....................................................................................193
Using the jsp:root Element....................................................................................................196
Using the jsp:output Element................................................................................................196
Identifying the JSPDocument to the Container............................................................................200
7 JavaServer Pages StandardTagLibrary........................................................................................201
The Example JSPPages.....................................................................................................................201
Using JSTL..........................................................................................................................................203
Tag Collaboration......................................................................................................................204
Core Tag Library...............................................................................................................................205
Variable Support Tags...............................................................................................................205
FlowControl Tags......................................................................................................................206
URL Tags.....................................................................................................................................210
Miscellaneous Tags....................................................................................................................211
XML Tag Library...............................................................................................................................211
Core Tags....................................................................................................................................213
FlowControl Tags......................................................................................................................214
TransformationTags.................................................................................................................215
InternationalizationTag Library.....................................................................................................215
Setting the Locale.......................................................................................................................216
Messaging Tags..........................................................................................................................216
Formatting Tags.........................................................................................................................217
SQL Tag Library.................................................................................................................................218
query Tag Result Interface........................................................................................................220
JSTL Functions..................................................................................................................................222
Further Informationabout JSTL.....................................................................................................223
Contents
The Java EE 5Tutorial • September 20078
8 CustomTags inJSPPages.................................................................................................................225
What Is a CustomTag?.....................................................................................................................226
The Example JSPPages.....................................................................................................................226
Types of Tags......................................................................................................................................229
Tags with Attributes...................................................................................................................229
Tags with Bodies........................................................................................................................232
Tags That Define Variables.......................................................................................................232
CommunicationbetweenTags................................................................................................233
Encapsulating Reusable Content Using Tag Files.........................................................................233
Tag File Location........................................................................................................................235
Tag File Directives......................................................................................................................235
Evaluating Fragments Passed to Tag Files...............................................................................242
CustomTag Examples...............................................................................................................243
Tag Library Descriptors....................................................................................................................247
Top-Level Tag Library Descriptor Elements..........................................................................248
Declaring Tag Files....................................................................................................................249
Declaring Tag Handlers............................................................................................................251
Declaring Tag Attributes for Tag Handlers............................................................................252
Declaring Tag Variables for Tag Handlers..............................................................................254
Programming Simple Tag Handlers...............................................................................................256
Including Tag Handlers inWeb Applications........................................................................256
HowIs a Simple Tag Handler Invoked?..................................................................................256
Tag Handlers for Basic Tags.....................................................................................................257
Tag Handlers for Tags with Attributes....................................................................................257
Tag Handlers for Tags with Bodies..........................................................................................260
Tag Handlers for Tags That Define Variables........................................................................261
Cooperating Tags.......................................................................................................................263
Tag Handler Examples..............................................................................................................265
9 ScriptinginJSPPages.......................................................................................................................273
The Example JSPPages.....................................................................................................................273
Using Scripting..................................................................................................................................275
Disabling Scripting............................................................................................................................275
JSPDeclarations................................................................................................................................276
Initializing and Finalizing a JSPPage.......................................................................................276
Contents
9
JSPScriptlets......................................................................................................................................277
JSPExpressions..................................................................................................................................277
Programming Tags That Accept Scripting Elements....................................................................278
TLDElements.............................................................................................................................278
Tag Handlers..............................................................................................................................278
Tags with Bodies........................................................................................................................280
Cooperating Tags.......................................................................................................................282
Tags That Define Variables.......................................................................................................284
10 JavaServer FacesTechnology..........................................................................................................285
JavaServer Faces Technology User Interface..................................................................................285
JavaServer Faces Technology Benefits............................................................................................286
What Is a JavaServer Faces Application?.........................................................................................287
ASimple JavaServer Faces Application...........................................................................................287
Steps inthe Development Process...........................................................................................288
Mapping the FacesServlet Instance......................................................................................289
Creating the Pages......................................................................................................................290
Defining Page Navigation.........................................................................................................296
Configuring Error Messages.....................................................................................................297
Developing the Beans................................................................................................................298
Adding Managed BeanDeclarations.......................................................................................298
User Interface Component Model..................................................................................................299
User Interface Component Classes..........................................................................................300
Component Rendering Model.................................................................................................301
ConversionModel.....................................................................................................................304
Event and Listener Model.........................................................................................................305
ValidationModel.......................................................................................................................307
NavigationModel..............................................................................................................................307
Backing Beans....................................................................................................................................309
Creating a Backing BeanClass.................................................................................................309
The Life Cycle of a JavaServer Faces Page.......................................................................................313
Restore ViewPhase....................................................................................................................315
Further Informationabout JavaServer Faces Technology............................................................318
Contents
The Java EE 5Tutorial • September 200710
11 UsingJavaServer FacesTechnologyinJSPPages........................................................................319
The Example JavaServer Faces Application....................................................................................319
Setting Up a Page...............................................................................................................................322
Using the Core Tags..........................................................................................................................325
Adding UI Components to a Page Using the HTML Component Tags.....................................327
UI Component Tag Attributes.................................................................................................327
Adding a FormComponent.....................................................................................................329
Using Text Components...........................................................................................................330
Using Command Components for Performing Actions and Navigation...........................335
Using Data-Bound Table Components..................................................................................337
Adding Graphics and Images with the graphicImage Tag...................................................340
Laying Out Components with the UIPanel Component......................................................341
Rendering Components for Selecting One Value..................................................................343
Rendering Components for Selecting Multiple Values.........................................................345
The UISelectItem,UISelectItems,and UISelectItemGroup Components...................346
Displaying Error Messages with the message and messages Tags.......................................349
Using Localized Data........................................................................................................................350
Loading a Resource Bundle......................................................................................................351
Referencing Localized Static Data............................................................................................352
Referencing Error Messages.....................................................................................................352
Using the Standard Converters........................................................................................................354
Converting a Component’s Value............................................................................................355
Using DateTimeConverter.......................................................................................................356
Using NumberConverter...........................................................................................................357
Registering Listeners onComponents............................................................................................359
Registering a Value-Change Listener ona Component........................................................359
Registering anActionListener ona Component...................................................................360
Using the Standard Validators.........................................................................................................361
Validating a Component’s Value.............................................................................................362
Using the LongRangeValidator..............................................................................................363
Binding Component Values and Instances to External Data Sources........................................364
Binding a Component Value to a Property.............................................................................365
Binding a Component Value to anImplicit Object...............................................................366
Binding a Component Instance to a BeanProperty..............................................................368
Binding Converters,Listeners,and Validators to Backing BeanProperties..............................369
Referencing a Backing BeanMethod..............................................................................................370
Contents
11
Referencing a Method That Performs Navigation.................................................................371
Referencing a Method That Handles anActionEvent..........................................................371
Referencing a Method That Performs Validation..................................................................372
Referencing a Method That Handles a Value-change Event................................................372
Using CustomObjects......................................................................................................................373
Using a CustomConverter.......................................................................................................374
Using a CustomValidator.........................................................................................................375
Using a CustomComponent....................................................................................................376
12 DevelopingwithJavaServer FacesTechnology...........................................................................379
Writing BeanProperties...................................................................................................................379
Writing Properties Bound to Component Values.................................................................380
Writing Properties Bound to Component Instances.............................................................388
Writing Properties Bound to Converters,Listeners,or Validators.....................................389
Performing Localization...................................................................................................................390
Creating a Resource Bundle......................................................................................................390
Localizing Dynamic Data..........................................................................................................390
Localizing Messages...................................................................................................................391
Creating a CustomConverter..........................................................................................................393
Implementing anEvent Listener.....................................................................................................395
Implementing Value-Change Listeners..................................................................................396
Implementing ActionListeners...............................................................................................397
Creating a CustomValidator...........................................................................................................398
Implementing the Validator Interface.....................................................................................399
Creating a CustomTag..............................................................................................................402
Writing Backing BeanMethods......................................................................................................404
Writing a Method to Handle Navigation................................................................................404
Writing a Method to Handle anActionEvent........................................................................406
Writing a Method to PerformValidation...............................................................................406
Writing a Method to Handle a Value-Change Event.............................................................407
13 CreatingCustomUI Components...................................................................................................409
Determining Whether You Need a CustomComponent or Renderer.......................................410
Whento Use a CustomComponent........................................................................................410
Whento Use a CustomRenderer.............................................................................................411
Contents
The Java EE 5Tutorial • September 200712
Component,Renderer,and Tag Combinations.....................................................................412
Understanding the Image Map Example........................................................................................413
Why Use JavaServer Faces Technology to Implement anImage Map?...............................413
Understanding the Rendered HTML......................................................................................413
Understanding the JSPPage.....................................................................................................414
Configuring Model Data...........................................................................................................416
Summary of the ApplicationClasses.......................................................................................417
Steps for Creating a CustomComponent.......................................................................................418
Creating CustomComponent Classes............................................................................................419
Specifying the Component Family..........................................................................................421
Performing Encoding................................................................................................................422
Performing Decoding................................................................................................................424
Enabling Component Properties to Accept Expressions......................................................424
Saving and Restoring State........................................................................................................426
Delegating Rendering to a Renderer...............................................................................................427
Creating the Renderer Class.....................................................................................................427
Identifying the Renderer Type.................................................................................................429
Handling Events for CustomComponents....................................................................................429
Creating the Component Tag Handler...........................................................................................430
Retrieving the Component Type..............................................................................................431
Setting Component Property Values.......................................................................................431
Providing the Renderer Type...................................................................................................433
Releasing Resources...................................................................................................................434
Defining the CustomComponent Tag ina Tag Library Descriptor...........................................434
14 ConfiguringJavaServer Faces Applications..................................................................................437
ApplicationConfigurationResource File.......................................................................................437
Configuring Beans.............................................................................................................................439
Using the managed-bean Element............................................................................................439
Initializing Properties Using the managed-property Element............................................441
Initializing Maps and Lists........................................................................................................447
Registering CustomError Messages...............................................................................................448
Registering CustomLocalized Static Text......................................................................................449
Registering a CustomValidator.......................................................................................................450
Registering a CustomConverter.....................................................................................................451
Contents
13
Configuring NavigationRules.........................................................................................................451
Registering a CustomRenderer with a Render Kit........................................................................455
Registering a CustomComponent..................................................................................................457
Basic Requirements of a JavaServer Faces Application.................................................................458
Configuring anApplicationwith a Deployment Descriptor................................................459
Including the Required JARFiles.............................................................................................466
Including the Classes,Pages,and Other Resources...............................................................466
15 InternationalizingandLocalizingWebApplications..................................................................467
Java PlatformLocalizationClasses..................................................................................................467
Providing Localized Messages and Labels......................................................................................468
Establishing the Locale..............................................................................................................468
Setting the Resource Bundle.....................................................................................................469
Retrieving Localized Messages.................................................................................................470
Date and Number Formatting.........................................................................................................471
Character Sets and Encodings..........................................................................................................472
Character Sets.............................................................................................................................472
Character Encoding...................................................................................................................473
Further Informationabout Internationalizing Web Applications..............................................475
Part III WebServices......................................................................................................................................477
16 BuildingWebServices withJAX-WS...............................................................................................479
Setting the Port...................................................................................................................................480
Creating a Simple Web Service and Client with JAX-WS............................................................480
Requirements of a JAX-WS Endpoint.....................................................................................481
Coding the Service Endpoint ImplementationClass............................................................482
Building,Packaging,and Deploying the Service....................................................................482
Testing the Service without a Client........................................................................................484
ASimple JAX-WS Client...........................................................................................................484
Types Supported by JAX-WS...........................................................................................................486
Web Services Interoperability and JAX-WS..................................................................................487
Further Informationabout JAX-WS...............................................................................................487
Contents
The Java EE 5Tutorial • September 200714
17 BindingbetweenXMLSchemaandJavaClasses.........................................................................489
JAXBArchitecture.............................................................................................................................489
Architectural Overview.............................................................................................................489
The JAXBBinding Process........................................................................................................490
More about Unmarshalling......................................................................................................492
More about Marshalling............................................................................................................492
More about Validation..............................................................................................................492
Representing XML Content.............................................................................................................492
Java Representationof XML Schema.......................................................................................492
Binding XML Schemas.....................................................................................................................493
Simple Type Definitions............................................................................................................493
Default Data Type Bindings.....................................................................................................493
Customizing Generated Classes and Java ProgramElements.....................................................495
Schema-to-Java..........................................................................................................................495
Java-to-Schema..........................................................................................................................496
JAXBExamples..................................................................................................................................501
JAXBCompiler Options...........................................................................................................503
JAXBSchema Generator Option.............................................................................................505
About the Schema-to-Java Bindings........................................................................................505
Schema-Derived JAXBClasses.................................................................................................508
Basic JAXBExamples........................................................................................................................511
Modify Marshal Example..........................................................................................................511
Unmarshal Validate Example...................................................................................................512
Customizing JAXBBindings............................................................................................................514
Why Customize?........................................................................................................................515
CustomizationOverview..........................................................................................................515
Customize Inline Example........................................................................................................526
Datatype Converter Example...................................................................................................531
Binding DeclarationFiles..........................................................................................................533
External Customize Example...................................................................................................536
Java-to-Schema Examples................................................................................................................536
Create Marshal Example...........................................................................................................537
XmlAccessorOrder Example....................................................................................................538
XmlAdapter Field Example......................................................................................................540
XmlAttribute Field Example.....................................................................................................543
XmlRootElement Example.......................................................................................................544
Contents
15
XmlSchemaType Class Example..............................................................................................545
XmlType Example.....................................................................................................................546
Further Informationabout JAXB....................................................................................................548
18 StreamingAPI for XML......................................................................................................................549
Why StAX?.........................................................................................................................................549
Streaming versus DOM.............................................................................................................549
Pull Parsing versus Push Parsing..............................................................................................550
StAXUse Cases..........................................................................................................................551
Comparing StAXto Other JAXPAPIs....................................................................................551
StAXAPI............................................................................................................................................552
Cursor API..................................................................................................................................553
Iterator API.................................................................................................................................553
Choosing betweenCursor and Iterator APIs..........................................................................557
Using StAX.........................................................................................................................................559
StAXFactory Classes.................................................................................................................559
Resources,Namespaces,and Errors........................................................................................561
Reading XML Streams...............................................................................................................561
Writing XML Streams...............................................................................................................564
Sun’s Streaming XML Parser Implementation..............................................................................566
Reporting CDATAEvents.........................................................................................................566
Streaming XML Parser Factories Implementation................................................................566
Example Code....................................................................................................................................567
Example Code Organization....................................................................................................567
Example XML Document.........................................................................................................568
Cursor Example..........................................................................................................................568
Cursor-to-Event Example.........................................................................................................571
Event Example............................................................................................................................573
Filter Example............................................................................................................................575
Read-and-Write Example.........................................................................................................578
Writer Example..........................................................................................................................580
Further Informationabout StAX.....................................................................................................583
19 SOAPwithAttachments API for Java.............................................................................................585
Overviewof SAAJ..............................................................................................................................586
Contents
The Java EE 5Tutorial • September 200716
SAAJ Messages...........................................................................................................................586
SAAJ Connections.....................................................................................................................589
SAAJ Tutorial.....................................................................................................................................590
Creating and Sending a Simple Message.................................................................................591
Adding Content to the Header.................................................................................................598
Adding Content to the SOAPPart Object.................................................................................599
Adding a Document to the SOAPBody..................................................................................600
Manipulating Message Content Using SAAJ or DOMAPIs................................................601
Adding Attachments..................................................................................................................601
Adding Attributes......................................................................................................................603
Using SOAPFaults.....................................................................................................................608
Code Examples..................................................................................................................................613
Request Example........................................................................................................................613
Header Example.........................................................................................................................614
DOMand DOMSource Examples...........................................................................................617
Attachments Example...............................................................................................................622
SOAPFault Example.................................................................................................................624
Further Informationabout SAAJ....................................................................................................627
Part IV EnterpriseBeans................................................................................................................................629
20 EnterpriseBeans................................................................................................................................631
What Is anEnterprise Bean?............................................................................................................631
Benefits of Enterprise Beans.....................................................................................................631
Whento Use Enterprise Beans.................................................................................................632
Types of Enterprise Beans.........................................................................................................632
What Is a SessionBean?....................................................................................................................633
State Management Modes.........................................................................................................633
Whento Use SessionBeans......................................................................................................634
What Is a Message-DrivenBean?....................................................................................................634
What Makes Message-DrivenBeans Different fromSessionBeans?..................................635
Whento Use Message-DrivenBeans.......................................................................................636
Defining Client Access with Interfaces...........................................................................................636
Remote Clients...........................................................................................................................636
Local Clients...............................................................................................................................637
Contents
17
Deciding onRemote or Local Access.......................................................................................638
Web Service Clients...................................................................................................................639
Method Parameters and Access................................................................................................639
The Contents of anEnterprise Bean...............................................................................................640
Naming Conventions for Enterprise Beans...................................................................................641
The Life Cycles of Enterprise Beans................................................................................................641
The Life Cycle of a Stateful SessionBean................................................................................642
The Life Cycle of a Stateless SessionBean...............................................................................642
The Life Cycle of a Message-DrivenBean...............................................................................643
Further Informationabout Enterprise Beans................................................................................644
21 GettingStartedwithEnterpriseBeans..........................................................................................645
Creating the Enterprise Bean...........................................................................................................645
Coding the Enterprise Bean......................................................................................................646
Compiling and Packaging the converter Example..............................................................647
Creating the converter ApplicationClient...................................................................................648
Coding the converter ApplicationClient..............................................................................648
Compiling the converter ApplicationClient........................................................................650
Creating the converter Web Client...............................................................................................650
Coding the converter Web Client..........................................................................................650
Compiling the converter Web Client....................................................................................652
Deploying the converter Java EEApplication..............................................................................652
Deploying the converter Example Using NetBeans IDE....................................................652
Deploying the converter Example Using Ant......................................................................652
Running the converter ApplicationClient...................................................................................653
Running the converter ApplicationClient Using NetBeans IDE......................................653
Running the converter ApplicationClient Using Ant........................................................653
Running the converter Web Client...............................................................................................654
Modifying the Java EEApplication.................................................................................................654
Modifying a Class File................................................................................................................654
22 SessionBeanExamples....................................................................................................................657
The cart Example.............................................................................................................................657
The Business Interface...............................................................................................................658
SessionBeanClass.....................................................................................................................658
Contents
The Java EE 5Tutorial • September 200718
The Remove Method.................................................................................................................662
Helper Classes.............................................................................................................................662
Building,Packaging,Deploying,and Running the cart Example......................................662
Undeploying the cart Example...............................................................................................665
AWeb Service Example:helloservice.........................................................................................665
The Web Service Endpoint ImplementationClass................................................................666
Stateless SessionBeanImplementationClass........................................................................666
Building,Packaging,Deploying,and Testing the helloservice Example........................667
Using the Timer Service....................................................................................................................669
The Timeout Method.................................................................................................................669
Creating Timers.........................................................................................................................669
Canceling and Saving Timers...................................................................................................670
Getting Timer Information......................................................................................................670
Transactions and Timers..........................................................................................................670
The timersession Example.....................................................................................................671
Building,Packaging,Deploying,and Running the timersession Example......................672
Handling Exceptions.........................................................................................................................674
23 AMessage-DrivenBeanExample...................................................................................................675
simplemessage Example ApplicationOverview...........................................................................675
The simplemessage ApplicationClient.........................................................................................676
The Message-DrivenBeanClass.....................................................................................................677
The onMessage Method.............................................................................................................677
Packaging,Deploying,and Running the simplemessage Example............................................678
Creating the Administered Objects for the simplemessage Example.................................679
Building,Deploying,and Running the simplemessage ApplicationUsing NetBeans
IDE...............................................................................................................................................679
Building,Deploying,and Running the simplemessage ApplicationUsing Ant...............680
Removing the Administered Objects for the simplemessage Example..............................681
Creating Deployment Descriptors for Message-DrivenBeans...................................................682
Part V Persistence..........................................................................................................................................683
24 IntroductiontotheJavaPersistenceAPI......................................................................................685
Entities................................................................................................................................................685
Contents
19
Requirements for Entity Classes..............................................................................................685
Persistent Fields and Properties inEntity Classes..................................................................686
Primary Keys inEntities............................................................................................................688
Multiplicity inEntity Relationships.........................................................................................689
DirectioninEntity Relationships.............................................................................................690
Entity Inheritance......................................................................................................................691
Managing Entities..............................................................................................................................696
The Persistence Context............................................................................................................696
The EntityManager Interface..................................................................................................696
Persistence Units........................................................................................................................701
25 PersistenceintheWebTier..............................................................................................................703
Accessing Databases fromWeb Applications................................................................................703
Defining the Persistence Unit...................................................................................................704
Creating anEntity Class............................................................................................................705
Obtaining Access to anEntity Manager..................................................................................706
Accessing Data fromthe Database...........................................................................................708
Updating Data inthe Database................................................................................................708
26 PersistenceintheEJBTier................................................................................................................711
The order Application......................................................................................................................711
Entity Relationships inthe order Application.......................................................................711
Primary Keys inthe order Application...................................................................................714
Entity Mapped to More ThanOne Database Table...............................................................717
Cascade Operations inthe order Application.......................................................................718
BLOBand CLOBDatabase Types inthe order Application................................................718
Temporal Types inthe order Application..............................................................................719
Managing the order Application’s Entities.............................................................................719
Building and Running the order Application........................................................................721
The roster Application....................................................................................................................726
Relationships inthe roster Application.................................................................................726
Entity Inheritance inthe roster Application.........................................................................727
Automatic Table Generationinthe roster Application......................................................729
Building and Running the roster Application......................................................................729
Contents
The Java EE 5Tutorial • September 200720
27 TheJavaPersistenceQueryLanguage..........................................................................................733
Query Language Terminology.........................................................................................................733
Simplified Query Language Syntax.................................................................................................734
Select Statements........................................................................................................................734
Update and Delete Statements.................................................................................................734
Example Queries................................................................................................................................735
Simple Queries...........................................................................................................................735
Queries That Navigate to Related Entities..............................................................................736
Queries with Other Conditional Expressions........................................................................738
Bulk Updates and Deletes.........................................................................................................740
Full Query Language Syntax............................................................................................................740
BNF Symbols..............................................................................................................................740
BNF Grammar of the Java Persistence Query Language.......................................................741
FROM Clause.................................................................................................................................745
Path Expressions........................................................................................................................749
WHERE Clause...............................................................................................................................751
SELECT Clause.............................................................................................................................759
ORDER BY Clause.........................................................................................................................761
The GROUP BY Clause.................................................................................................................762
Part VI Services...............................................................................................................................................763
28 IntroductiontoSecurityintheJavaEEPlatform.........................................................................765
Overviewof Java EESecurity...........................................................................................................766
ASimple Security Example.......................................................................................................766
Security Functions.....................................................................................................................769
Characteristics of ApplicationSecurity...................................................................................770
Security ImplementationMechanisms...........................................................................................771
Java SESecurity ImplementationMechanisms......................................................................771
Java EESecurity ImplementationMechanisms......................................................................772
Securing Containers..........................................................................................................................774
Using Deployment Descriptors for Declarative Security......................................................774
Using Annotations.....................................................................................................................775
Using Programmatic Security..................................................................................................776
Securing the ApplicationServer......................................................................................................777
Contents
21
Working with Realms,Users,Groups,and Roles..........................................................................777
What Are Realms,Users,Groups,and Roles?........................................................................778
Managing Users and Groups onthe ApplicationServer.......................................................781
Setting Up Security Roles..........................................................................................................782
Mapping Roles to Users and Groups.......................................................................................784
Establishing a Secure ConnectionUsing SSL.................................................................................785
Installing and Configuring SSL Support.................................................................................785
Specifying a Secure ConnectioninYour ApplicationDeployment Descriptor.................786
Verifying SSL Support...............................................................................................................787
Working with Digital Certificates............................................................................................788
Enabling Mutual Authenticationover SSL.............................................................................793
Further Informationabout Security................................................................................................795
29 SecuringJavaEEApplications.........................................................................................................797
Securing Enterprise Beans................................................................................................................798
Accessing anEnterprise BeanCaller’s Security Context.......................................................799
Declaring Security Role Names Referenced fromEnterprise BeanCode...........................801
Defining a Security Viewof Enterprise Beans........................................................................804
Using Enterprise BeanSecurity Annotations.........................................................................815
Using Enterprise BeanSecurity Deployment Descriptor Elements....................................816
Configuring IORSecurity.........................................................................................................817
Deploying Secure Enterprise Beans.........................................................................................819
Enterprise BeanExample Applications..........................................................................................820
Example:Securing anEnterprise Bean....................................................................................820
Example:Using the isCallerInRole and getCallerPrincipal Methods.......................826
Discussion:Securing the Duke’s Bank Example.....................................................................831
Securing ApplicationClients...........................................................................................................832
Using LoginModules................................................................................................................832
Using Programmatic Login......................................................................................................833
Securing EIS Applications................................................................................................................834
Container-Managed Sign-On..................................................................................................834
Component-Managed Sign-On...............................................................................................834
Configuring Resource Adapter Security.................................................................................835
Mapping anApplicationPrincipal to EIS Principals.............................................................837
Contents
The Java EE 5Tutorial • September 200722
30 SecuringWebApplications..............................................................................................................839
Overviewof Web ApplicationSecurity..........................................................................................840
Working with Security Roles...........................................................................................................841