The Java EE 5Tutorial

Alex EvangSoftware and s/w Development

Aug 30, 2011 (6 years and 25 days ago)

2,537 views

This tutorial is a guide to developing enterprise applications for the JavaTM Platform, Enterprise Edition 5 (Java EE 5). This preface contains information about and conventions for the entire Sun Java System Application Server documentation set.

TheJavaEE5Tutorial
For SunJava SystemApplicationServer 9.1
SunMicrosystems,Inc.
4150 Network Circle
Santa Clara,CA95054
U.S.A.
Part No:819–3669–11
October 2008
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.
081104@21288
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...........................................................................................................................59
Java Message Service API............................................................................................................59
Java TransactionAPI...................................................................................................................59
JavaMail API.................................................................................................................................59
JavaBeans ActivationFramework..............................................................................................60
Java API for XML Processing.....................................................................................................60
Java API for XML Web Services (JAX-WS)..............................................................................60
Java Architecture for XML Binding (JAXB).............................................................................61
SOAPwith Attachments API for Java........................................................................................61
Java API for XML Registries.......................................................................................................61
J2EEConnector Architecture.....................................................................................................61
Java Database Connectivity API.................................................................................................62
Java Persistence API.....................................................................................................................62
Java Naming and Directory Interface........................................................................................62
Java Authenticationand AuthorizationService.......................................................................63
Simplified Systems Integration...................................................................................................63
SunJava SystemApplicationServer PlatformEdition9.................................................................64
Tools..............................................................................................................................................64
2 UsingtheTutorial Examples..............................................................................................................67
Required Software...............................................................................................................................67
Tutorial Bundle............................................................................................................................67
Java Platform,Standard Edition.................................................................................................68
SunJava SystemApplicationServer 9.1.....................................................................................68
NetBeans IDE...............................................................................................................................69
Apache Ant...................................................................................................................................69
Starting and Stopping the ApplicationServer..................................................................................69
Starting the AdminConsole...............................................................................................................70
Contents
The Java EE 5Tutorial • October 20084
Starting and Stopping the Java DBDatabase Server........................................................................71
Building the Examples........................................................................................................................71
Building the Examples Using NetBeans IDE............................................................................71
Building the Examples onthe Command-Line Using Ant.....................................................72
Tutorial Example Directory Structure..............................................................................................73
Debugging Java EEApplications.......................................................................................................73
Using the Server Log....................................................................................................................73
Using a Debugger.........................................................................................................................74
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 • October 20086
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 • October 20088
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.................................................................................................302
ConversionModel.....................................................................................................................305
Event and Listener Model.........................................................................................................306
ValidationModel.......................................................................................................................307
NavigationModel..............................................................................................................................308
Backing Beans....................................................................................................................................310
Creating a Backing BeanClass.................................................................................................310
The Life Cycle of a JavaServer Faces Page.......................................................................................314
Restore ViewPhase....................................................................................................................315
Further Informationabout JavaServer Faces Technology............................................................319
Contents
The Java EE 5Tutorial • October 200810
11 UsingJavaServer FacesTechnologyinJSPPages........................................................................321
The Example JavaServer Faces Application....................................................................................321
Setting Up a Page...............................................................................................................................324
Using the Core Tags..........................................................................................................................327
Adding UI Components to a Page Using the HTML Component Tags.....................................329
UI Component Tag Attributes.................................................................................................329
Adding a FormComponent.....................................................................................................331
Using Text Components...........................................................................................................332
Using Command Components for Performing Actions and Navigation...........................337
Using Data-Bound Table Components..................................................................................339
Adding Graphics and Images with the graphicImage Tag...................................................343
Laying Out Components with the UIPanel Component......................................................343
Rendering Components for Selecting One Value..................................................................346
Rendering Components for Selecting Multiple Values.........................................................348
The UISelectItem,UISelectItems,and UISelectItemGroup Components...................349
Displaying Error Messages with the message and messages Tags.......................................352
Using Localized Data........................................................................................................................353
Loading a Resource Bundle......................................................................................................354
Referencing Localized Static Data............................................................................................355
Referencing Error Messages.....................................................................................................355
Using the Standard Converters........................................................................................................357
Converting a Component’s Value............................................................................................358
Using DateTimeConverter.......................................................................................................359
Using NumberConverter...........................................................................................................360
Registering Listeners onComponents............................................................................................362
Registering a Value-Change Listener ona Component........................................................362
Registering anActionListener ona Component...................................................................363
Using the Standard Validators.........................................................................................................364
Validating a Component’s Value.............................................................................................365
Using the LongRangeValidator..............................................................................................366
Binding Component Values and Instances to External Data Sources........................................367
Binding a Component Value to a Property.............................................................................368
Binding a Component Value to anImplicit Object...............................................................369
Binding a Component Instance to a BeanProperty..............................................................371
Binding Converters,Listeners,and Validators to Backing BeanProperties..............................372
Referencing a Backing BeanMethod..............................................................................................373
Contents
11
Referencing a Method That Performs Navigation.................................................................374
Referencing a Method That Handles anActionEvent..........................................................374
Referencing a Method That Performs Validation..................................................................375
Referencing a Method That Handles a Value-change Event................................................375
Using CustomObjects......................................................................................................................376
Using a CustomConverter.......................................................................................................377
Using a CustomValidator.........................................................................................................378
Using a CustomComponent....................................................................................................379
12 DevelopingwithJavaServer FacesTechnology...........................................................................381
Writing BeanProperties...................................................................................................................381
Writing Properties Bound to Component Values.................................................................382
Writing Properties Bound to Component Instances.............................................................390
Writing Properties Bound to Converters,Listeners,or Validators.....................................391
Performing Localization...................................................................................................................392
Creating a Resource Bundle......................................................................................................392
Localizing Dynamic Data..........................................................................................................392
Localizing Messages...................................................................................................................393
Creating a CustomConverter..........................................................................................................395
Implementing anEvent Listener.....................................................................................................397
Implementing Value-Change Listeners..................................................................................398
Implementing ActionListeners...............................................................................................399
Creating a CustomValidator...........................................................................................................400
Implementing the Validator Interface.....................................................................................401
Creating a CustomTag..............................................................................................................404
Writing Backing BeanMethods......................................................................................................406
Writing a Method to Handle Navigation................................................................................406
Writing a Method to Handle anActionEvent........................................................................408
Writing a Method to PerformValidation...............................................................................408
Writing a Method to Handle a Value-Change Event.............................................................409
13 CreatingCustomUI Components...................................................................................................411
Determining Whether You Need a CustomComponent or Renderer.......................................412
Whento Use a CustomComponent........................................................................................412
Whento Use a CustomRenderer.............................................................................................413
Contents
The Java EE 5Tutorial • October 200812
Component,Renderer,and Tag Combinations.....................................................................414
Understanding the Image Map Example........................................................................................415
Why Use JavaServer Faces Technology to Implement anImage Map?...............................415
Understanding the Rendered HTML......................................................................................415
Understanding the JSPPage.....................................................................................................416
Configuring Model Data...........................................................................................................418
Summary of the ApplicationClasses.......................................................................................419
Steps for Creating a CustomComponent.......................................................................................420
Creating CustomComponent Classes............................................................................................421
Specifying the Component Family..........................................................................................423
Performing Encoding................................................................................................................424
Performing Decoding................................................................................................................426
Enabling Component Properties to Accept Expressions......................................................426
Saving and Restoring State........................................................................................................428
Delegating Rendering to a Renderer...............................................................................................429
Creating the Renderer Class.....................................................................................................429
Identifying the Renderer Type.................................................................................................431
Handling Events for CustomComponents....................................................................................431
Creating the Component Tag Handler...........................................................................................432
Retrieving the Component Type..............................................................................................433
Setting Component Property Values.......................................................................................433
Providing the Renderer Type...................................................................................................435
Releasing Resources...................................................................................................................436
Defining the CustomComponent Tag ina Tag Library Descriptor...........................................436
14 ConfiguringJavaServer Faces Applications..................................................................................439
ApplicationConfigurationResource File.......................................................................................439
Configuring Beans.............................................................................................................................441
Using the managed-bean Element............................................................................................441
Initializing Properties Using the managed-property Element............................................443
Initializing Maps and Lists........................................................................................................449
Registering CustomError Messages...............................................................................................450
Registering CustomLocalized Static Text......................................................................................451
Registering a CustomValidator.......................................................................................................452
Registering a CustomConverter.....................................................................................................453
Contents
13
Configuring NavigationRules.........................................................................................................453
Registering a CustomRenderer with a Render Kit........................................................................457
Registering a CustomComponent..................................................................................................459
Basic Requirements of a JavaServer Faces Application.................................................................460
Configuring anApplicationwith a Deployment Descriptor................................................461
Including the Required JARFiles.............................................................................................468
Including the Classes,Pages,and Other Resources...............................................................468
15 InternationalizingandLocalizingWebApplications..................................................................469
Java PlatformLocalizationClasses..................................................................................................469
Providing Localized Messages and Labels......................................................................................470
Establishing the Locale..............................................................................................................470
Setting the Resource Bundle.....................................................................................................471
Retrieving Localized Messages.................................................................................................472
Date and Number Formatting.........................................................................................................473
Character Sets and Encodings..........................................................................................................474
Character Sets.............................................................................................................................474
Character Encoding...................................................................................................................475
Further Informationabout Internationalizing Web Applications..............................................477
Part III WebServices......................................................................................................................................479
16 BuildingWebServices withJAX-WS...............................................................................................481
Setting the Port...................................................................................................................................482
Creating a Simple Web Service and Client with JAX-WS............................................................482
Requirements of a JAX-WS Endpoint.....................................................................................483
Coding the Service Endpoint ImplementationClass............................................................484
Building,Packaging,and Deploying the Service....................................................................484
Testing the Service without a Client........................................................................................486
ASimple JAX-WS Client...........................................................................................................486
Types Supported by JAX-WS...........................................................................................................489
Web Services Interoperability and JAX-WS..................................................................................489
Further Informationabout JAX-WS...............................................................................................489
Contents
The Java EE 5Tutorial • October 200814
17 BindingbetweenXMLSchemaandJavaClasses.........................................................................491
JAXBArchitecture.............................................................................................................................491
Architectural Overview.............................................................................................................492
The JAXBBinding Process........................................................................................................492
More about Unmarshalling......................................................................................................494
More about Marshalling............................................................................................................494
More about Validation..............................................................................................................494
Representing XML Content.............................................................................................................494
Java Representationof XML Schema.......................................................................................494
Binding XML Schemas.....................................................................................................................495
Simple Type Definitions............................................................................................................495
Default Data Type Bindings.....................................................................................................495
Customizing Generated Classes and Java ProgramElements.....................................................497
Schema-to-Java..........................................................................................................................497
Java-to-Schema..........................................................................................................................498
JAXBExamples..................................................................................................................................503
JAXBCompiler Options...........................................................................................................505
JAXBSchema Generator Option.............................................................................................507
About the Schema-to-Java Bindings........................................................................................507
Schema-Derived JAXBClasses.................................................................................................510
Basic JAXBExamples........................................................................................................................513
Modify Marshal Example..........................................................................................................513
Unmarshal Validate Example...................................................................................................514
Customizing JAXBBindings............................................................................................................516
Why Customize?........................................................................................................................517
CustomizationOverview..........................................................................................................517
Customize Inline Example........................................................................................................528
Datatype Converter Example...................................................................................................533
Binding DeclarationFiles..........................................................................................................535
External Customize Example...................................................................................................538
Java-to-Schema Examples................................................................................................................538
Create Marshal Example...........................................................................................................539
XmlAccessorOrder Example....................................................................................................540
XmlAdapter Field Example......................................................................................................542
XmlAttribute Field Example.....................................................................................................545
XmlRootElement Example.......................................................................................................546
Contents
15
XmlSchemaType Class Example..............................................................................................547
XmlType Example.....................................................................................................................548
Further Informationabout JAXB....................................................................................................550
18 StreamingAPI for XML......................................................................................................................551
Why StAX?.........................................................................................................................................551
Streaming versus DOM.............................................................................................................551
Pull Parsing versus Push Parsing..............................................................................................552
StAXUse Cases..........................................................................................................................553
Comparing StAXto Other JAXPAPIs....................................................................................553
StAXAPI............................................................................................................................................554
Cursor API..................................................................................................................................555
Iterator API.................................................................................................................................555
Choosing betweenCursor and Iterator APIs..........................................................................559
Using StAX.........................................................................................................................................561
StAXFactory Classes.................................................................................................................561
Resources,Namespaces,and Errors........................................................................................563
Reading XML Streams...............................................................................................................563
Writing XML Streams...............................................................................................................566
Sun’s Streaming XML Parser Implementation..............................................................................568
Reporting CDATAEvents.........................................................................................................568
Streaming XML Parser Factories Implementation................................................................568
Example Code....................................................................................................................................569
Example Code Organization....................................................................................................569
Example XML Document.........................................................................................................570
Cursor Example..........................................................................................................................570
Cursor-to-Event Example.........................................................................................................573
Event Example............................................................................................................................575
Filter Example............................................................................................................................577
Read-and-Write Example.........................................................................................................580
Writer Example..........................................................................................................................582
Further Informationabout StAX.....................................................................................................585
19 SOAPwithAttachments API for Java.............................................................................................587
Overviewof SAAJ..............................................................................................................................588
Contents
The Java EE 5Tutorial • October 200816
SAAJ Messages...........................................................................................................................588
SAAJ Connections.....................................................................................................................591
SAAJ Tutorial.....................................................................................................................................592
Creating and Sending a Simple Message.................................................................................593
Adding Content to the Header.................................................................................................601
Adding Content to the SOAPPart Object.................................................................................602
Adding a Document to the SOAPBody..................................................................................603
Manipulating Message Content Using SAAJ or DOMAPIs................................................603
Adding Attachments..................................................................................................................603
Adding Attributes......................................................................................................................606
Using SOAPFaults.....................................................................................................................611
Code Examples..................................................................................................................................615
Request Example........................................................................................................................615
Header Example.........................................................................................................................617
DOMand DOMSource Examples...........................................................................................620
Attachments Example...............................................................................................................624
SOAPFault Example.................................................................................................................626
Further Informationabout SAAJ....................................................................................................629
Part IV EnterpriseBeans................................................................................................................................631
20 EnterpriseBeans................................................................................................................................633
What Is anEnterprise Bean?............................................................................................................633
Benefits of Enterprise Beans.....................................................................................................633
Whento Use Enterprise Beans.................................................................................................634
Types of Enterprise Beans.........................................................................................................634
What Is a SessionBean?....................................................................................................................635
State Management Modes.........................................................................................................635
Whento Use SessionBeans......................................................................................................636
What Is a Message-DrivenBean?....................................................................................................636
What Makes Message-DrivenBeans Different fromSessionBeans?..................................637
Whento Use Message-DrivenBeans.......................................................................................638
Defining Client Access with Interfaces...........................................................................................638
Remote Clients...........................................................................................................................638
Local Clients...............................................................................................................................639
Contents
17
Deciding onRemote or Local Access.......................................................................................640
Web Service Clients...................................................................................................................641
Method Parameters and Access................................................................................................641
The Contents of anEnterprise Bean...............................................................................................642
Naming Conventions for Enterprise Beans...................................................................................643
The Life Cycles of Enterprise Beans................................................................................................643
The Life Cycle of a Stateful SessionBean................................................................................644
The Life Cycle of a Stateless SessionBean...............................................................................644
The Life Cycle of a Message-DrivenBean...............................................................................645
Further Informationabout Enterprise Beans................................................................................646
21 GettingStartedwithEnterpriseBeans..........................................................................................647
Creating the Enterprise Bean...........................................................................................................647
Coding the Enterprise Bean......................................................................................................648
Compiling and Packaging the converter Example..............................................................649
Creating the converter ApplicationClient...................................................................................650
Coding the converter ApplicationClient..............................................................................650
Compiling the converter ApplicationClient........................................................................652
Creating the converter Web Client...............................................................................................652
Coding the converter Web Client..........................................................................................652
Compiling the converter Web Client....................................................................................654
Deploying the converter Java EEApplication..............................................................................654
Deploying the converter Example Using NetBeans IDE....................................................654
Deploying the converter Example Using Ant......................................................................654
Running the converter ApplicationClient...................................................................................655
Running the converter ApplicationClient Using NetBeans IDE......................................655
Running the converter ApplicationClient Using Ant........................................................655
Running the converter Web Client...............................................................................................656
Modifying the Java EEApplication.................................................................................................656
Modifying a Class File................................................................................................................656
22 SessionBeanExamples....................................................................................................................659
The cart Example.............................................................................................................................659
The Business Interface...............................................................................................................660
SessionBeanClass.....................................................................................................................660
Contents
The Java EE 5Tutorial • October 200818
The Remove Method.................................................................................................................664
Helper Classes.............................................................................................................................664
Building,Packaging,Deploying,and Running the cart Example......................................664
Undeploying the cart Example...............................................................................................667
AWeb Service Example:helloservice.........................................................................................667
The Web Service Endpoint ImplementationClass................................................................668
Stateless SessionBeanImplementationClass........................................................................668
Building,Packaging,Deploying,and Testing the helloservice Example........................669
Using the Timer Service....................................................................................................................671
The Timeout Method.................................................................................................................671
Creating Timers.........................................................................................................................671
Canceling and Saving Timers...................................................................................................672
Getting Timer Information......................................................................................................672
Transactions and Timers..........................................................................................................672
The timersession Example.....................................................................................................673
Building,Packaging,Deploying,and Running the timersession Example......................674
Handling Exceptions.........................................................................................................................676
23 AMessage-DrivenBeanExample...................................................................................................677
simplemessage Example ApplicationOverview...........................................................................677
The simplemessage ApplicationClient.........................................................................................678
The Message-DrivenBeanClass.....................................................................................................679
The onMessage Method.............................................................................................................679
Packaging,Deploying,and Running the simplemessage Example............................................680
Creating the Administered Objects for the simplemessage Example.................................681
Building,Deploying,and Running the simplemessage ApplicationUsing NetBeans
IDE...............................................................................................................................................681
Building,Deploying,and Running the simplemessage ApplicationUsing Ant...............682
Removing the Administered Objects for the simplemessage Example..............................683
Creating Deployment Descriptors for Message-DrivenBeans...................................................684
Part V Persistence..........................................................................................................................................685
24 IntroductiontotheJavaPersistenceAPI......................................................................................687
Entities................................................................................................................................................687
Contents
19
Requirements for Entity Classes..............................................................................................687
Persistent Fields and Properties inEntity Classes..................................................................688
Primary Keys inEntities............................................................................................................690
Multiplicity inEntity Relationships.........................................................................................691
DirectioninEntity Relationships.............................................................................................692
Entity Inheritance......................................................................................................................693
Managing Entities..............................................................................................................................698
The Persistence Context............................................................................................................698
The EntityManager Interface..................................................................................................698
Persistence Units........................................................................................................................703
25 PersistenceintheWebTier..............................................................................................................705
Accessing Databases fromWeb Applications................................................................................705
Defining the Persistence Unit...................................................................................................706
Creating anEntity Class............................................................................................................707
Obtaining Access to anEntity Manager..................................................................................708
Accessing Data fromthe Database...........................................................................................710
Updating Data inthe Database................................................................................................710
26 PersistenceintheEJBTier................................................................................................................713
The order Application......................................................................................................................713
Entity Relationships inthe order Application.......................................................................713
Primary Keys inthe order Application...................................................................................716
Entity Mapped to More ThanOne Database Table...............................................................719
Cascade Operations inthe order Application.......................................................................720
BLOBand CLOBDatabase Types inthe order Application................................................720
Temporal Types inthe order Application..............................................................................721
Managing the order Application’s Entities.............................................................................721
Building and Running the order Application........................................................................723
The roster Application....................................................................................................................728
Relationships inthe roster Application.................................................................................728
Entity Inheritance inthe roster Application.........................................................................729
Automatic Table Generationinthe roster Application......................................................731
Building and Running the roster Application......................................................................731
Contents
The Java EE 5Tutorial • October 200820
27 TheJavaPersistenceQueryLanguage..........................................................................................735
Query Language Terminology.........................................................................................................735
Simplified Query Language Syntax.................................................................................................736
Select Statements........................................................................................................................736
Update and Delete Statements.................................................................................................736
Example Queries................................................................................................................................737
Simple Queries...........................................................................................................................737
Queries That Navigate to Related Entities..............................................................................738
Queries with Other Conditional Expressions........................................................................740
Bulk Updates and Deletes.........................................................................................................742
Full Query Language Syntax............................................................................................................742
BNF Symbols..............................................................................................................................742
BNF Grammar of the Java Persistence Query Language.......................................................743
FROM Clause.................................................................................................................................747
Path Expressions........................................................................................................................751
WHERE Clause...............................................................................................................................753
SELECT Clause.............................................................................................................................761
ORDER BY Clause.........................................................................................................................763
The GROUP BY Clause.................................................................................................................764
Part VI Services...............................................................................................................................................765
28 IntroductiontoSecurityintheJavaEEPlatform.........................................................................767
Overviewof Java EESecurity...........................................................................................................768
ASimple Security Example.......................................................................................................768
Security Functions.....................................................................................................................771
Characteristics of ApplicationSecurity...................................................................................772
Security ImplementationMechanisms...........................................................................................773
Java SESecurity ImplementationMechanisms......................................................................773
Java EESecurity ImplementationMechanisms......................................................................774
Securing Containers..........................................................................................................................776
Using Deployment Descriptors for Declarative Security......................................................776
Using Annotations.....................................................................................................................777
Using Programmatic Security..................................................................................................778
Securing the ApplicationServer......................................................................................................779
Contents
21
Working with Realms,Users,Groups,and Roles..........................................................................779
What Are Realms,Users,Groups,and Roles?........................................................................780
Managing Users and Groups onthe ApplicationServer.......................................................783
Setting Up Security Roles..........................................................................................................784
Mapping Roles to Users and Groups.......................................................................................786
Establishing a Secure ConnectionUsing SSL.................................................................................787
Installing and Configuring SSL Support.................................................................................787
Specifying a Secure ConnectioninYour ApplicationDeployment Descriptor.................788
Verifying SSL Support...............................................................................................................789
Working with Digital Certificates............................................................................................790
Enabling Mutual Authenticationover SSL.............................................................................795
Further Informationabout Security................................................................................................797
29 SecuringJavaEEApplications.........................................................................................................799
Securing Enterprise Beans................................................................................................................800
Accessing anEnterprise BeanCaller’s Security Context.......................................................801
Declaring Security Role Names Referenced fromEnterprise BeanCode...........................803
Defining a Security Viewof Enterprise Beans........................................................................806
Using Enterprise BeanSecurity Annotations.........................................................................817
Using Enterprise BeanSecurity Deployment Descriptor Elements....................................818
Configuring IORSecurity.........................................................................................................819
Deploying Secure Enterprise Beans.........................................................................................821
Enterprise BeanExample Applications..........................................................................................822
Example:Securing anEnterprise Bean....................................................................................822
Example:Using the isCallerInRole and getCallerPrincipal Methods.......................828
Discussion:Securing the Duke’s Bank Example.....................................................................833
Securing ApplicationClients...........................................................................................................834
Using LoginModules................................................................................................................834
Using Programmatic Login......................................................................................................835
Securing EIS Applications................................................................................................................836
Container-Managed Sign-On..................................................................................................836
Component-Managed Sign-On...............................................................................................836
Configuring Resource Adapter Security.................................................................................837
Mapping anApplicationPrincipal to EIS Principals.............................................................839
Contents
The Java EE 5Tutorial • October 200822
30 SecuringWebApplications..............................................................................................................841
Overviewof Web ApplicationSecurity..........................................................................................842
Working with Security Roles...........................................................................................................843