the java ee 6 tutorial -...
Post on 02-Apr-2018
223 Views
Preview:
TRANSCRIPT
The Java EE 6 TutorialAdvanced Topics
Fourth Edition
This page intentionally left blank
The Java EE 6 Tutorial
Eric JendrockRicardo Cervera-Navarro
Ian EvansDevika Gollapudi
Kim HaaseWilliam Markito
Chinmayee Srivathsa
Advanced Topics
Fourth Edition
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • MadridCapetown • Sydney • Tokyo • Singapore • Mexico City
Many of the designations used bymanufacturers and sellers to distinguish their products are claimed as trademarks.Where thosedesignations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initialcapital letters or in all capitals.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other namesmay be trademarks of their respective owners.
The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kindand assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connectionwith or arising out of the use of the information or programs contained herein.
This document is provided for information purposes only and the contents hereof are subject to change without notice. Thisdocument is not warranted to be error-free, nor subject to any other warranties or conditions, whether expressed orally or implied inlaw, including implied warranties and conditions of merchantability or fitness for a particular purpose.We specifically disclaim anyliability with respect to this document and no contractual obligations are formed either directly or indirectly by this document. Thisdocumentmay not be reproduced or transmitted in any form or by anymeans, electronic ormechanical, for any purpose, withoutour prior written permission.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which mayinclude electronic versions and/or custom covers and content particular to your business, training goals, marketing focus,and branding interests. For more information, please contact
U.S. Corporate andGovernment Sales(800) 382-3419corpsales@pearsontechgroup.com
For sales outside the United States, please contact
International Sales interna-tional@pearsoned.com
Visit us on theWeb: informit.com/aw
Library of Congress Control Number: 2012952541
Copyright © 2011, 2013, Oracle and/or its affiliates. All rights reserved.500 Oracle Parkway, Redwood Shores, CA 94065
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permissionmust be ob-tained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by anymeans, electronic, mechanical, photocopying, recording, or likewise. To obtain permission to usematerial from this work, pleasesubmit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey07458, or youmay fax your request to (201) 236-3290.
ISBN-13: 978-0-13-708186-8ISBN-10: 0-13-708186-3Text printed in the United States on recycled paper at RRDonnelley in Crawfordsville, Indiana.First printing, January, 2013
Contents
Preface ..................................................................................................................................xxi
Part I Introduction . ..........................................................................................................................1
1 Overview .................................................................................................................................3Java EE 6 PlatformHighlights ................................................................................................4Java EEApplicationModel ....................................................................................................5DistributedMultitiered Applications ...................................................................................6
Security..............................................................................................................................7Java EE Components .......................................................................................................8Java EE Clients ..................................................................................................................8Web Components .........................................................................................................10Business Components ...................................................................................................11Enterprise Information SystemTier ...........................................................................12
Java EE Containers ...............................................................................................................13Container Services ........................................................................................................13Container Types ............................................................................................................14
Web Services Support ..........................................................................................................15XML ................................................................................................................................15SOAPTransport Protocol .............................................................................................16WSDL Standard Format ...............................................................................................16
Java EEApplication Assembly andDeployment ..............................................................17Packaging Applications .......................................................................................................17Development Roles ..............................................................................................................19
Java EE Product Provider .............................................................................................19Tool Provider .................................................................................................................19Application Component Provider ..............................................................................20
v
Application Assembler ..................................................................................................20ApplicationDeployer and Administrator...................................................................21
Java EE 6 APIs........................................................................................................................21Enterprise JavaBeans Technology ...............................................................................25Java Servlet Technology.................................................................................................26JavaServer Faces Technology .......................................................................................26JavaServer Pages Technology........................................................................................27JavaServer Pages Standard Tag Library .......................................................................28Java Persistence API ......................................................................................................28Java Transaction API ....................................................................................................28Java API for RESTfulWeb Services ............................................................................29Managed Beans .............................................................................................................29Contexts andDependency Injection for the Java EE Platform (JSR 299) ..............29Dependency Injection for Java (JSR 330) ...................................................................29Bean Validation .............................................................................................................30JavaMessage Service API .............................................................................................30Java EE Connector Architecture .................................................................................30JavaMail API ..................................................................................................................31Java Authorization Contract for Containers ..............................................................31Java Authentication Service Provider Interface for Containers ..............................31
Java EE 6 APIs in the Java Platform, Standard Edition 6 and 7........................................32Java Database Connectivity API ..................................................................................32Java Naming andDirectory Interface API .................................................................32JavaBeans Activation Framework ...............................................................................33Java API for XML Processing ......................................................................................33Java Architecture for XML Binding ............................................................................33SOAPwith Attachments API for Java .........................................................................34Java API for XMLWeb Services ..................................................................................34Java Authentication and Authorization Service .........................................................34
GlassFish Server Tools..........................................................................................................35
2 Using theTutorial Examples . .............................................................................................37Required Software ................................................................................................................37
Java Platform, Standard Edition ..................................................................................37Java EE 6 Software Development Kit ..........................................................................38
Contents
The Java EE 6Tutorialvi
Java EE 6 Tutorial Component ....................................................................................38NetBeans IDE ................................................................................................................39Apache Ant ....................................................................................................................40
Starting and Stopping the GlassFish Server .......................................................................41▼ To Start the GlassFish Server Using NetBeans IDE ..................................................42
Starting the Administration Console .................................................................................42▼ To Start the Administration Console Using NetBeans IDE ....................................42
Starting and Stopping the Java DB Server ..........................................................................43▼ To Start the Database Server Using NetBeans IDE ...................................................43
Building the Examples .........................................................................................................43Tutorial Example Directory Structure ...............................................................................44Getting the Latest Updates to the Tutorial ........................................................................45
▼ ToUpdate the Tutorial through the Update Center .................................................45Debugging Java EEApplications ........................................................................................45
Using the Server Log .....................................................................................................45Using a Debugger ..........................................................................................................46
Part II TheWebTier . ........................................................................................................................47
3 JavaServer FacesTechnology: AdvancedConcepts . ......................................................49The Lifecycle of a JavaServer Faces Application.................................................................50
Overview of the JavaServer Faces Lifecycle ................................................................50Restore View Phase .......................................................................................................53Apply Request Values Phase ........................................................................................53Process Validations Phase ............................................................................................54UpdateModel Values Phase ........................................................................................55Invoke Application Phase ............................................................................................55Render Response Phase ................................................................................................55
Partial Processing and Partial Rendering ..........................................................................56The Lifecycle of a Facelets Application ..............................................................................56User Interface ComponentModel .....................................................................................57
User Interface Component Classes .............................................................................58Component RenderingModel ....................................................................................60ConversionModel ........................................................................................................61Event and ListenerModel ............................................................................................61
Contents
vii
ValidationModel ..........................................................................................................63NavigationModel .........................................................................................................64
4 UsingAjaxwith JavaServer FacesTechnology . ..............................................................69Overview of Ajax ..................................................................................................................70Using Ajax Functionality with JavaServer Faces Technology .........................................70Using Ajax with Facelets ......................................................................................................71
Using the f:ajax Tag....................................................................................................71Sending an Ajax Request ......................................................................................................73
Using the eventAttribute.............................................................................................74Using the executeAttribute ........................................................................................74Using the immediateAttribute ....................................................................................75Using the listenerAttribute ......................................................................................75
Monitoring Events on the Client.........................................................................................75Handling Errors ....................................................................................................................76Receiving an Ajax Response.................................................................................................77Ajax Request Lifecycle ..........................................................................................................78Grouping of Components....................................................................................................78Loading JavaScript as a Resource ........................................................................................79
Using JavaScript API in a Facelets Application ..........................................................80Using the @ResourceDependencyAnnotation in a Bean Class ................................81
The ajaxguessnumber Example Application ....................................................................81The ajaxguessnumber Source Files ............................................................................81Running the ajaxguessnumber Example .. ................................................................83
Further Information about Ajax in JavaServer Faces Technology ..................................85
5 Composite Components: AdvancedTopics and Example . ............................................87Attributes of a Composite Component .............................................................................87Invoking aManaged Bean ...................................................................................................88Validating Composite Component Values .......................................................................89The compositecomponentlogin Example Application ...................................................89
The Composite Component File .................................................................................89The Using Page ..............................................................................................................90TheManaged Bean .......................................................................................................91Running the compositecomponentlogin Example ..................................................92
Contents
The Java EE 6Tutorialviii
6 CreatingCustomUI Components andOther CustomObjects ......................................95DeterminingWhether YouNeed a CustomComponent or Renderer ..........................97
When to Use a CustomComponent ...........................................................................97When to Use a CustomRenderer ................................................................................98Component, Renderer, and Tag Combinations ........................................................99
Understanding the ImageMap Example..........................................................................100WhyUse JavaServer Faces Technology to Implement an ImageMap? ................100Understanding the RenderedHTML .......................................................................101Understanding the Facelets Page ..............................................................................102ConfiguringModel Data ............................................................................................103Summary of the ImageMapApplication Classes ....................................................104
Steps for Creating a CustomComponent ........................................................................105Creating CustomComponent Classes .............................................................................106
Specifying the Component Family ...........................................................................109Performing Encoding .................................................................................................109PerformingDecoding .................................................................................................111Enabling Component Properties to Accept Expressions ........................................112Saving and Restoring State .........................................................................................113
Delegating Rendering to a Renderer.................................................................................114Creating the Renderer Class ......................................................................................115Identifying the Renderer Type ...................................................................................117
Implementing an Event Listener .......................................................................................117Implementing Value-Change Listeners ...................................................................117Implementing Action Listeners ................................................................................118
Handling Events for CustomComponents......................................................................119Defining the CustomComponent Tag in a Tag Library Descriptor ............................120Using a CustomComponent ............................................................................................121Creating andUsing a CustomConverter ........................................................................123
Creating a CustomConverter ...................................................................................123Using a CustomConverter .........................................................................................126
Creating andUsing a CustomValidator ..........................................................................128Implementing the Validator Interface ......................................................................129Specifying a CustomTag ............................................................................................131Using a CustomValidator ..........................................................................................132
Binding Component Values and Instances toManaged Bean Properties....................133Binding a Component Value to a Property ..............................................................134
Contents
ix
Binding a Component Value to an Implicit Object ................................................136Binding a Component Instance to a Bean Property ...............................................137
Binding Converters, Listeners, and Validators toManaged Bean Properties .............138
7 Configuring JavaServer FacesApplications ... ...............................................................141Using Annotations to ConfigureManaged Beans ..........................................................142
UsingManaged Bean Scopes......................................................................................143Application Configuration Resource File ........................................................................144
Ordering of Application Configuration Resource Files ..........................................145ConfiguringManaged Beans.............................................................................................146
Using the managed-bean Element .............................................................................147Initializing Properties Using the managed-property Element .............................150InitializingMaps and Lists .........................................................................................155
Registering ApplicationMessages.....................................................................................155Using FacesMessage to Create aMessage ...............................................................157Referencing ErrorMessages ......................................................................................157
Using Default Validators....................................................................................................159Registering a CustomValidator ........................................................................................159Registering a CustomConverter .......................................................................................160Configuring Navigation Rules ...........................................................................................161▼ ToConfigure a Navigation Rule .................................................................................163
Implicit Navigation Rules ...........................................................................................164Registering a CustomRenderer with a Render Kit .........................................................165Registering a CustomComponent ...................................................................................167Basic Requirements of a JavaServer Faces Application ..................................................168
Configuring an Application with aWebDeployment Descriptor.........................169Configuring Project Stage...........................................................................................172Including the Classes, Pages, andOther Resources ................................................173
8 Uploading Fileswith Java ServletTechnology . ............................................................175The @MultipartConfigAnnotation.................................................................................175The getParts and getPartMethods ...............................................................................176The fileupload Example Application ............................................................................177
Architecture of the fileupload Example Application ...........................................177Running the fileupload Example............................................................................180
Contents
The Java EE 6Tutorialx
9 Internationalizing and LocalizingWebApplications . .................................................183Java Platform Localization Classes ...................................................................................183Providing LocalizedMessages and Labels .......................................................................184
Establishing the Locale ...............................................................................................185Setting the Resource Bundle.......................................................................................185Retrieving LocalizedMessages...................................................................................186
Date andNumber Formatting ..........................................................................................187Character Sets and Encodings ...........................................................................................188
Character Sets ..............................................................................................................188Character Encoding ....................................................................................................188
Part III WebServices . .....................................................................................................................191
10 JAX-RS: AdvancedTopics andExample . .........................................................................193Annotations for Field and Bean Properties of Resource Classes ..................................193
Extracting Path Parameters ........................................................................................194Extracting Query Parameters .....................................................................................195Extracting FormData ................................................................................................195Extracting the Java Type of a Request or Response ................................................196
Subresources and Runtime Resource Resolution ...........................................................197SubresourceMethods .................................................................................................197Subresource Locators . ................................................................................................197
Integrating JAX-RS with EJB Technology and CDI .......................................................198Conditional HTTP Requests .............................................................................................199Runtime Content Negotiation ..........................................................................................200Using JAX-RSWith JAXB .................................................................................................202
Using Java Objects toModel Your Data ...................................................................204Starting from an Existing XML SchemaDefinition ................................................206Using JSONwith JAX-RS and JAXB .........................................................................208
The customer Example Application ................................................................................209Overview of the customer Example Application.....................................................209The Customer and Address Entity Classes ...............................................................209The CustomerServiceClass ......................................................................................212The CustomerClientXML and CustomerClientJSONClasses ................................214Modifying the Example to Generate Entity Classes from an Existing Schema ...216
Contents
xi
Running the customer Example ................................................................................219
Part IV Enterprise Beans . ...............................................................................................................225
11 AMessage-DrivenBeanExample . ..................................................................................227Overview of the simplemessage Example .......................................................................227The simplemessageApplication Client ...........................................................................228TheMessage-Driven Bean Class ......................................................................................229
The onMessageMethod ..............................................................................................230Running the simplemessage Example ............................................................................231
Administered Objects for the simplemessage Example.........................................231▼ To Run the simplemessageApplicationUsingNetBeans IDE..............................232▼ To Run the simplemessageApplicationUsing Ant................................................232
Removing the AdministeredObjects for the simplemessage Example................233
12 Using the EmbeddedEnterprise BeanContainer .........................................................235Overview of the Embedded Enterprise Bean Container ................................................235Developing Embeddable Enterprise Bean Applications ................................................236
Running Embedded Applications .............................................................................236Creating the Enterprise Bean Container ..................................................................237Looking Up Session Bean References .......................................................................238Shutting Down the Enterprise Bean Container .......................................................238
The standalone Example Application.............................................................................239▼ To Run the standalone Example Application ........................................................240
13 UsingAsynchronousMethod Invocation in SessionBeans . ......................................241AsynchronousMethod Invocation ...................................................................................241
Creating an Asynchronous BusinessMethod ..........................................................242Calling AsynchronousMethods from Enterprise Bean Clients ............................243
The async Example Application .......................................................................................244Architecture of the async Example Application......................................................244Running the async Example ......................................................................................245
Contents
The Java EE 6Tutorialxii
PartV Contexts andDependency Injection for the Java EEPlatform .. .................................249
14 Contexts andDependency Injection for the Java EEPlatform:AdvancedTopics ... 251Using Alternatives in CDI Applications ..........................................................................251
Using Specialization .. ................................................................................................253Using ProducerMethods, Producer Fields, andDisposerMethods in CDIApplications ........................................................................................................................254
Using ProducerMethods ...........................................................................................254Using Producer Fields to Generate Resources .........................................................255Using a DisposerMethod ...........................................................................................256
Using Predefined Beans in CDI Applications .................................................................256Using Events in CDI Applications ....................................................................................257
Defining Events ...........................................................................................................257Using ObserverMethods to Handle Events..............................................................258Firing Events.................................................................................................................259
Using Interceptors in CDI Applications ..........................................................................260Using Decorators in CDI Applications ............................................................................262Using Stereotypes in CDI Applications ...........................................................................263
15 Running theAdvancedContexts andDependency Injection Examples ..................265The encoder Example: Using Alternatives .....................................................................265
The Coder Interface and Implementations ..............................................................266The encoder Facelets Page andManaged Bean .......................................................266Running the encoder Example .................................................................................268
The producermethods Example: Using a ProducerMethod To Choose a Bean Imple-mentation .. ..........................................................................................................................271
Components of the producermethods Example .....................................................271Running the producermethods Example .................................................................272
The producerfields Example: Using Producer Fields to Generate Resources .........273The Producer Field for the producerfields Example ...........................................274The producerfields Entity and Session Bean .......................................................275The producerfields Facelets Pages andManaged Bean ......................................276Running the producerfields Example . .................................................................278
The billpayment Example: Using Events and Interceptors .........................................280The PaymentEvent Event Class . ...............................................................................280
Contents
xiii
The PaymentHandler Event Listener ........................................................................281The billpayment Facelets Pages andManaged Bean .............................................281The LoggedInterceptor Interceptor Class .............................................................284Running the billpayment Example .........................................................................285
The decorators Example: Decorating a Bean ................................................................286Components of the decorators Example . ..............................................................286Running the decorators Example ...........................................................................287
PartVI Persistence . .........................................................................................................................291
16 Creating andUsing String-BasedCriteriaQueries .......................................................293Overview of String-Based Criteria API Queries .............................................................293Creating String-BasedQueries .........................................................................................294Executing String-BasedQueries .......................................................................................295
17 ControllingConcurrentAccess to EntityDatawith Locking .......................................297Overview of Entity Locking and Concurrency ...............................................................297
Using Optimistic Locking...........................................................................................298LockModes..........................................................................................................................299
Setting the LockMode.................................................................................................300Using Pessimistic Locking .........................................................................................301
18 Using a Second-Level Cachewith JavaPersistenceAPI Applications .......................303Overview of the Second-Level Cache ...............................................................................303
ControllingWhether EntitiesMay Be Cached . ......................................................304Specifying the CacheMode Settings to Improve Performance .....................................305
Setting the Cache Retrieval and StoreModes . ........................................................306Controlling the Second-Level Cache Programmatically ........................................307
PartVII Security . ..............................................................................................................................309
19 Java EE Security: AdvancedTopics ... ...............................................................................311Working with Digital Certificates ....................................................................................311
Contents
The Java EE 6Tutorialxiv
Creating a Server Certificate ......................................................................................312Adding Users to the Certificate Realm .....................................................................314Using a Different Server Certificate with the GlassFish Server ..............................315
AuthenticationMechanisms..............................................................................................316Client Authentication .................................................................................................316Mutual Authentication ...............................................................................................317
Using Form-Based Login in JavaServer FacesWebApplications .................................321Using j_security_check in JavaServer Faces Forms ............................................321Using aManaged Bean for Authentication in JavaServer Faces Applications ....322
Using the JDBCRealm for User Authentication ............................................................324▼ ToConfigure a JDBCAuthentication Realm .. .......................................................324
SecuringHTTPResources .................................................................................................328Securing Application Clients ............................................................................................331
Using LoginModules .................................................................................................331Using Programmatic Login .......................................................................................332
Securing Enterprise Information Systems Applications ... ............................................332Container-Managed Sign-On ...................................................................................333Component-Managed Sign-On ................................................................................333Configuring Resource Adapter Security ..................................................................334
▼ ToMap an Application Principal to EIS Principals .. .............................................335Configuring Security Using Deployment Descriptors ...................................................336
Specifying Security for Basic Authentication in the Deployment Descriptor ....336Specifying Non-Default Principal-to-RoleMapping in the DeploymentDescriptor ....................................................................................................................337
Further Information about Security .................................................................................337
PartVIII Java EE SupportingTechnologies ... ................................................................................339
20 JavaMessage Service Concepts .. ....................................................................................341Overview of the JMSAPI ...................................................................................................341
What IsMessaging? ....................................................................................................341What Is the JMSAPI? .................................................................................................342When Can YouUse the JMSAPI? ............................................................................343HowDoes the JMSAPIWork with the Java EE Platform? ....................................344
Basic JMSAPI Concepts ....................................................................................................345
Contents
xv
JMSAPI Architecture .................................................................................................345Messaging Domains ....................................................................................................346Message Consumption ...............................................................................................348
The JMSAPI ProgrammingModel ..................................................................................348JMSAdministeredObjects .........................................................................................349JMSConnections.........................................................................................................351JMS Sessions.................................................................................................................352JMSMessage Producers ..............................................................................................352JMSMessage Consumers............................................................................................353JMSMessages ...............................................................................................................355JMSQueue Browsers...................................................................................................358JMS ExceptionHandling ............................................................................................358
Creating Robust JMSApplications .. ................................................................................359Using Basic ReliabilityMechanisms..........................................................................359Using Advanced ReliabilityMechanisms .................................................................364
Using the JMSAPI in Java EEApplications .....................................................................368Using @ResourceAnnotations in Enterprise Bean orWeb Components............369Using Session Beans to Produce and to Synchronously ReceiveMessages ..........369UsingMessage-Driven Beans to ReceiveMessages Asynchronously ...................370Managing Distributed Transactions .........................................................................373Using the JMSAPI with Application Clients andWebComponents ...................375
Further Information about JMS ........................................................................................376
21 JavaMessage Service Examples .. ...................................................................................377Writing Simple JMSApplications ....................................................................................378
A Simple Example of SynchronousMessage Receives............................................378A Simple Example of AsynchronousMessage Consumption................................388A Simple Example of BrowsingMessages in a Queue .............................................394Running JMSClients onMultiple Systems...............................................................398Undeploying and Cleaning the Simple JMS Examples ...........................................405
Writing Robust JMSApplications.....................................................................................406AMessage Acknowledgment Example.....................................................................406ADurable Subscription Example ..............................................................................409A Local Transaction Example ....................................................................................411
AnApplication That Uses the JMSAPI with a Session Bean.........................................416
Contents
The Java EE 6Tutorialxvi
Writing the Application Components for the clientsessionmdb Example ......417Creating Resources for the clientsessionmdb Example ......................................419Running the clientsessionmdb Example ...............................................................419
AnApplication That Uses the JMSAPI with an Entity ..................................................421Overview of the clientmdbentity Example Application .....................................422Writing the Application Components for the clientmdbentity Example . .......423Creating Resources for the clientmdbentity Example.........................................426Running the clientmdbentity Example .................................................................426
AnApplication Example That ConsumesMessages from a Remote Server ...............429Overview of the consumeremote ExampleModules................................................430Writing theModule Components for the consumeremote Example ....................431Creating Resources for the consumeremote Example .............................................431Using TwoApplication Servers for the consumeremote Example ........................431Running the consumeremote Example .....................................................................432
AnApplication Example That Deploys aMessage-Driven Bean on Two Servers ......436Overview of the sendremote ExampleModules .....................................................436Writing theModule Components for the sendremote Example ..........................438Creating Resources for the sendremote Example ...................................................439
▼ To Enable Deployment on the Remote System .......................................................440▼ ToUse TwoApplication Servers for the sendremote Example .............................440
Running the sendremote Example ...........................................................................441▼ ToDisable Deployment on the Remote System ......................................................446
22 BeanValidation: AdvancedTopics .. ................................................................................449Creating CustomConstraints ...........................................................................................449
Using the Built-In Constraints toMake a NewConstraint.....................................449Customizing ValidatorMessages .....................................................................................450
The ValidationMessages Resource Bundle .. ........................................................450Grouping Constraints ........................................................................................................451
Customizing GroupValidationOrder .....................................................................451
23 Using Java EE Interceptors .. .............................................................................................453Overview of Interceptors ...................................................................................................453
Interceptor Classes .. ...................................................................................................454Interceptor Lifecycle....................................................................................................454
Contents
xvii
Interceptors and CDI ..................................................................................................455Using Interceptors ..............................................................................................................455
InterceptingMethod Invocations .............................................................................456Intercepting Lifecycle Callback Events .....................................................................457Intercepting Timeout Events .....................................................................................458
The interceptor Example Application...........................................................................460Running the interceptor Example .........................................................................460
24 TheResourceAdapter Example . .....................................................................................463The Resource Adapter ........................................................................................................463TheMessage-Driven Bean ................................................................................................464TheWebApplication .........................................................................................................464Running the mailconnector Example ............................................................................465
▼ Before YouDeploy the mailconnector Example ...................................................465▼ To Build, Package, andDeploy the mailconnector Example Using NetBeans
IDE ................................................................................................................................465▼ To Build, Package, andDeploy the mailconnector Example Using Ant ............466▼ To Run the mailconnector Example .......................................................................466
Part IX Case Studies . ......................................................................................................................469
25 Duke’s Bookstore Case Study Example . .........................................................................471Design and Architecture of Duke’s Bookstore ................................................................471TheDuke’s Bookstore Interface ........................................................................................472
The Book Java Persistence API Entity .......................................................................472Enterprise Beans Used in Duke’s Bookstore ............................................................473Facelets Pages andManaged Beans Used in Duke’s Bookstore .............................473CustomComponents andOther CustomObjects Used in Duke’s Bookstore ...475Properties Files Used in Duke’s Bookstore ...............................................................476Deployment Descriptors Used in Duke’s Bookstore ..............................................477
Running the Duke’s Bookstore Case Study Application ................................................477▼ To Build andDeploy Duke’s Bookstore Using NetBeans IDE ...............................477▼ To Build andDeploy Duke’s Bookstore Using Ant .................................................478▼ To RunDuke’s Bookstore ...........................................................................................478
Contents
The Java EE 6Tutorialxviii
26 Duke’sTutoringCase Study Example . ............................................................................479Design and Architecture of Duke’s Tutoring...................................................................479Main Interface .....................................................................................................................481
Java Persistence API Entities Used in theMain Interface .. ....................................481Enterprise Beans Used in theMain Interface .. ........................................................482Facelets Files Used in theMain Interface...................................................................483Helper Classes Used in theMain Interface................................................................484Properties Files .............................................................................................................484Deployment Descriptors Used in Duke’s Tutoring..................................................485
Administration Interface....................................................................................................486Enterprise Beans Used in the Administration Interface..........................................486
Facelets Files Used in the Administration Interface.................................................486Running the Duke’s Tutoring Case Study Application...................................................487
Setting UpGlassFish Server ........................................................................................487Running Duke’s Tutoring............................................................................................488
27 Duke’s Forest Case Study Example . ................................................................................491Design and Architecture of Duke’s Forest........................................................................492
The events Project ......................................................................................................494The entities Project ..................................................................................................495The dukes-payment Project........................................................................................497The dukes-resources Project....................................................................................498TheDuke’s Store Project..............................................................................................498TheDuke’s Shipment Project......................................................................................503
Building andDeploying the Duke’s Forest Case Study Application .............................506Prerequisite Task..........................................................................................................506
▼ To Build andDeploy the Duke’s Forest ApplicationUsing NetBeans IDE ...........507▼ To Build andDeploy the Duke’s Forest ApplicationUsing Ant .............................508Running the Duke’s Forest Application ...........................................................................509▼ To Register as a Duke’s Store Customer.....................................................................509▼ To Purchase Products ..................................................................................................509▼ ToApprove Shipment of a Product............................................................................510▼ ToCreate a New Product.............................................................................................510
Index ....................................................................................................................................513
Contents
xix
This page intentionally left blank
Preface
This tutorial is the second volume of a guide to developing enterprise applications forthe Java Platform, Enterprise Edition 6 (Java EE 6) using GlassFish Server Open SourceEdition.
Oracle GlassFish Server, a Java EE compatible application server, is based onGlassFishServer Open Source Edition, the leading open-source and open-community platformfor building and deploying next-generation applications and services. GlassFish ServerOpen Source Edition, developed by the GlassFish project open-source community athttp://glassfish.java.net/, is the first compatible implementation of the Java EE6 platform specification. This lightweight, flexible, and open-source application serverenables organizations not only to leverage the new capabilities introduced within theJava EE 6 specification, but also to add to their existing capabilities through a faster andmore streamlined development and deployment cycle. Oracle GlassFish Server, theproduct version, andGlassFish Server Open Source Edition, the open-source version,are hereafter referred to as GlassFish Server.
BeforeYouReadThis Book
Before proceeding with this book, you should be familiar with VolumeOne of thistutorial, The Java EE 6 Tutorial: Basic Concepts. Both volumes assume that you have agood knowledge of the Java programming language. A good way to get to that point isto read the Java Tutorials, available at http://docs.oracle.com/javase/.
RelatedDocumentation
TheGlassFish Server documentation set describes deployment planning and systeminstallation. To obtain documentation for GlassFish Server Open Source Edition, go tohttp://glassfish.java.net/docs/. The UniformResource Locator (URL) for theOracle GlassFish Server product documentation is http://docs.oracle.com/cd/E26576_01/index.htm.
xxi
Javadoc tool reference documentation for packages that are provided with GlassFishServer is available as follows.■ The API specification for version 6 of Java EE is located at http://
docs.oracle.com/javaee/6/api/.■ The API specification for GlassFish Server, including Java EE 6 platform packages
and nonplatform packages that are specific to the GlassFish Server product, islocated at http://glassfish.java.net/nonav/docs/v3/api/.
Additionally, the Java EE Specifications at http://www.oracle.com/technetwork/java/javaee/tech/index.htmlmight be useful.
For information about creating enterprise applications in the NetBeans IntegratedDevelopment Environment (IDE), see http://www.netbeans.org/kb/.
For information about the Java DB database for use with the GlassFish Server, seehttp://www.oracle.com/technetwork/java/javadb/overview/index.html.
The GlassFish Samples project is a collection of sample applications that demonstratea broad range of Java EE technologies. The GlassFish Samples are bundled with theJava EE Software Development Kit (SDK) and are also available from the GlassFishSamples project page at http://glassfish-samples.java.net/.
Typographic Conventions
Table P–1 describes the typographic changes that are used in this book.
TABLE P–1 TypographicConventions
Typeface Meaning Example
AaBbCc123 The names of commands, files, anddirectories, and onscreen computeroutput
Edit your .login file.
Use ls -a to list all files.
machine_name% you have mail.
AaBbCc123 What you type, contrasted withonscreen computer output
machine_name% su
Password:
AaBbCc123 Aplaceholder to be replaced with areal name or value
The command to remove a file is rmfilename.
AaBbCc123 Book titles, new terms, and terms tobe emphasized (note that someemphasized items appear bold online)
Read Chapter 6 in theUser’s Guide.
A cache is a copy that is stored locally.
Do not save the file.
Preface
The Java EE 6Tutorialxxii
Default Paths andFileNames
Table P–2 describes the default paths and file names that are used in this book.
TABLE P–2 Default Paths and FileNames
Placeholder Description DefaultValue
as-install Represents the baseinstallation directory for theGlassFish Server or the SDKof which the GlassFish Serveris a part.
Installations on the Solaris operating system,Linux operating system, andMac operatingsystem:
user’s-home-directory/glassfish3/glassfish
Windows, all installations:
SystemDrive:\glassfish3\glassfish
as-install-parent Represents the parent of thebase installation directory forGlassFish Server.
Installations on the Solaris operating system,Linux operating system, andMac operatingsystem:
user’s-home-directory/glassfish3
Windows, all installations:
SystemDrive:\glassfish3
tut-install Represents the baseinstallation directory for theJava EE Tutorial after youinstall the GlassFish Server orthe SDK and run the UpdateTool.
as-install/docs/javaee-tutorial
domain-root-dir Represents the directory inwhich a domain is created bydefault.
as-install/domains/
domain-dir Represents the directory inwhich a domain’sconfiguration is stored.
domain-root-dir/domain-name
Third-PartyWebSite References
Third-party URLs are referenced in this document and provide additional, relatedinformation.
Preface
xxiii
Note –Oracle is not responsible for the availability of third-party web sitesmentionedin this document. Oracle does not endorse and is not responsible or liable for anycontent, advertising, products, or othermaterials that are available on or through suchsites or resources. Oracle will not be responsible or liable for any actual or allegeddamage or loss caused or alleged to be caused by or in connection with use of orreliance on any such content, goods, or services that are available on or through suchsites or resources.
Acknowledgments
The Java EE tutorial teamwould like to thank the Java EE specification leads: RobertoChinnici, Bill Shannon, Kenneth Saks, Linda DeMichiel, Ed Burns, Roger Kitain, RonMonzillo, Binod PG, Sivakumar Thyagarajan, Kin-ManChung, Jitendra Kotamraju,Marc Hadley, Paul Sandoz, Gavin King, Emmanuel Bernard, Rod Johnson, Bob Lee,and RajivMordani.
Thanks also to AlejandroMurillo for the original version of the connector example.
Wewould also like to thank the Java EE 6 SDK team, especially Carla Carlson,Snjezana Sevo-Zenzerovic, Adam Leftik, and John Clingan.
The JavaServer Faces technology chapters benefited greatly from suggestions byManfred Riem as well as by the spec leads.
The EJB technology, Java Persistence API, and Criteria API chapters were written withextensive input from the EJB and Persistence teams, includingMarina Vatkina andMiteshMeswani.
We'd like to thank Sivakumar Thyagarajan for his reviews of the CDI chapters andTimQuinn for assistance with the application client container. Thanks also to theNetBeans engineering and documentation teams, particularly Petr Jiricka, JohnJullion-Ceccarelli, and Troy Giunipero, for their help in enabling NetBeans IDEsupport for the code examples.
Chang Feng, AlejandroMurillo, and Scott Fordin helped internationalize the Duke'sTutoring case study.
Wewould like to thank ourmanager, Alan Sommerer, for his support and steadyinginfluence.
We also thank JordanDouglas andDawn Tyler for developing and updating theillustrations. Sheila Cepero helped smooth our path inmany ways. Steve Cogornoprovided invaluable help with our tools.
Preface
The Java EE 6Tutorialxxiv
Finally, we would like to express our profound appreciation to Greg Doench, JohnFuller, Elizabeth Ryan, Steve Freedkin, and the production team at Addison-Wesleyfor graciously seeing ourmanuscript to publication.
Preface
xxv
This page intentionally left blank
JavaServer FacesTechnology: AdvancedConcepts
The Java EE 6 Tutorial: Basic Concepts introduces JavaServer Faces technology andFacelets, the preferred presentation layer for the Java EE platform. This chapter andthe following chapters introduce advanced concepts in this area.■ This chapter describes the JavaServer Faces lifecycle in detail. Some of the complex
JavaServer Faces applications use the well-defined lifecycle phases to customizeapplication behavior.
■ Chapter 4, “Using Ajax with JavaServer Faces Technology,” introduces Ajaxconcepts and the use of Ajax in JavaServer Faces applications.
■ Chapter 5, “Composite Components: Advanced Topics and Example,” introducesadvanced features of composite components.
■ Chapter 6, “Creating CustomUI Components andOther CustomObjects,”describes the process of creating new components, renderers, converters, listeners,and validators from scratch.
■ Chapter 7, “Configuring JavaServer Faces Applications,” introduces the process ofcreating and deploying JavaServer Faces applications, the use of variousconfiguration files, and the deployment structure.
The following topics are addressed here:■ “The Lifecycle of a JavaServer Faces Application” on page 50■ “Partial Processing and Partial Rendering” on page 56■ “The Lifecycle of a Facelets Application” on page 56■ “User Interface ComponentModel” on page 57
3C H A P T E R 3
49
The Lifecycle of a JavaServer FacesApplication
The lifecycle of an application refers to the various stages of processing of thatapplication, from its initiation to its conclusion. All applications have lifecycles.During a web application lifecycle, common tasks such as the following are performed:■ Handling incoming requests■ Decoding parameters■ Modifying and saving state■ Rendering web pages to the browser
The JavaServer Faces web application frameworkmanages lifecycle phasesautomatically for simple applications or allows you tomanage themmanually formore complex applications as required.
JavaServer Faces applications that use advanced featuresmay require interaction withthe lifecycle at certain phases. For example, Ajax applications use partial processingfeatures of the lifecycle. A clearer understanding of the lifecycle phases is key tocreating well-designed components.
A simplified view of the JavaServer faces lifecycle, consisting of the twomain phases ofa JavaServer Faces web application, is introduced in “The Lifecycle of the helloApplication” in The Java EE 6 Tutorial: Basic Concepts. This section examines theJavaServer Faces lifecycle inmore detail.
Overviewof the JavaServer Faces Lifecycle
The lifecycle of a JavaServer Faces application begins when the client makes anHTTPrequest for a page and ends when the server responds with the page, translated toHTML.
The lifecycle can be divided into twomain phases, execute and render. The executephase is further divided into subphases to support the sophisticated component tree.This structure requires that component data be converted and validated, componentevents be handled, and component data be propagated to beans in an orderly fashion.
A JavaServer Faces page is represented by a tree of components, called a view. Duringthe lifecycle, the JavaServer Faces implementationmust build the viewwhileconsidering the state saved from a previous submission of the page.When the clientrequests a page, the JavaServer Faces implementation performs several tasks, such asvalidating the data input of components in the view and converting input data to typesspecified on the server side.
The JavaServer Faces implementation performs all these tasks as a series of steps in theJavaServer Faces request-response lifecycle. Figure 3–1 illustrates these steps.
The Lifecycle of a JavaServer Faces Application
The Java EE 6Tutorial50
FIGURE 3–1 JavaServer Faces StandardRequest-Response Lifecycle
Restore View
Apply Requests
Process Events
Process Validations
Process Events
FacesRequest
Render Response
Process Events
Invoke Application
Process Events
Update Model Values
FacesResponse
ResponseComplete
ResponseComplete
ResponseComplete
ResponseComplete
Validation/Conversion Errors/Render Response
Conversion Errors/Render Response
RenderResponse
The Lifecycle of a JavaServer Faces Application
Chapter 3 • JavaServer FacesTechnology: Advanced Concepts 51
The request-response lifecycle handles two kinds of requests: initial requests andpostbacks. An initial request occurs when a usermakes a request for a page for the firsttime. A postback request occurs when a user submits the form contained on a page thatwas previously loaded into the browser as a result of executing an initial request.
When the lifecycle handles an initial request, it executes only the Restore View andRender Response phases, because there is no user input or action to process.Conversely, when the lifecycle handles a postback, it executes all of the phases.
Usually, the first request for a JavaServer Faces page comes in from a client, as a resultof clicking a link or button component on a JavaServer Faces page. To render aresponse that is another JavaServer Faces page, the application creates a new view andstores it in the javax.faces.context.FacesContext instance, which represents all ofthe information associated with processing an incoming request and creating aresponse. The application then acquires object references needed by the view and callsthe FacesContext.renderResponsemethod, which forces immediate rendering of theview by skipping to the Render Response phase of the lifecycle, as is shown by thearrows labelled Render Response in the diagram.
Sometimes, an applicationmight need to redirect to a different web applicationresource, such as a web service, or generate a response that does not contain JavaServerFaces components. In these situations, the developermust skip the Render Responsephase by calling the FacesContext.responseCompletemethod. This situation is alsoshown in the diagram, with the arrows labelled Response Complete.
Themost common situation is that a JavaServer Faces component submits a requestfor another JavaServer Faces page. In this case, the JavaServer Faces implementationhandles the request and automatically goes through the phases in the lifecycle toperform any necessary conversions, validations, andmodel updates, and to generatethe response.
There is one exception to the lifecycle described in this section.When a component'simmediate attribute is set to true, the validation, conversion, and events associatedwith these components are processed during the Apply Request Values phase ratherthan in a later phase.
The details of the lifecycle explained in the following sections are primarily intendedfor developers who need to know information such as when validations, conversions,and events are usually handled and ways to change how andwhen they are handled.Formore information on each of the lifecycle phases, download the latest JavaServerFaces Specification documentation from http://jcp.org/en/jsr/detail?id=314.
The JavaServer Faces application lifecycle execute phase contains the followingsubphases:■ “Restore View Phase” on page 53■ “Apply Request Values Phase” on page 53
The Lifecycle of a JavaServer Faces Application
The Java EE 6Tutorial52
■ “Process Validations Phase” on page 54■ “UpdateModel Values Phase” on page 55■ “Invoke Application Phase” on page 55■ “Render Response Phase” on page 55
RestoreViewPhase
When a request for a JavaServer Faces page is made, usually by an action such as whena link or a button component is clicked, the JavaServer Faces implementation beginsthe Restore View phase.
During this phase, the JavaServer Faces implementation builds the view of the page,wires event handlers and validators to components in the view, and saves the view inthe FacesContext instance, which contains all the information needed to process asingle request. All the application’s components, event handlers, converters, andvalidators have access to the FacesContext instance.
If the request for the page is an initial request, the JavaServer Faces implementationcreates an empty view during this phase and the lifecycle advances to the RenderResponse phase, during which the empty view is populated with the componentsreferenced by the tags in the page.
If the request for the page is a postback, a view corresponding to this page alreadyexists in the FacesContext instance. During this phase, the JavaServer Facesimplementation restores the view by using the state information saved on the client orthe server.
Apply RequestValues Phase
After the component tree is restored during a postback request, each component in thetree extracts its new value from the request parameters by using its decode(processDecodes()) method. The value is then stored locally on each component.
If any decodemethods or event listeners have called the renderResponsemethod onthe current FacesContext instance, the JavaServer Faces implementation skips to theRender Response phase.
If any events have been queued during this phase, the JavaServer Facesimplementation broadcasts the events to interested listeners.
If some components on the page have their immediate attributes (see “The immediateAttribute” in The Java EE 6 Tutorial: Basic Concepts) set to true, then the validations,conversions, and events associated with these components will be processed duringthis phase. If any conversion fails, an errormessage associated with the component is
The Lifecycle of a JavaServer Faces Application
Chapter 3 • JavaServer FacesTechnology: Advanced Concepts 53
generated and queued on FacesContext. This message will be displayed during theRender Response phase, along with any validation errors resulting from the ProcessValidations phase.
At this point, if the application needs to redirect to a different web application resourceor generate a response that does not contain any JavaServer Faces components, it cancall the FacesContext.responseCompletemethod.
At the end of this phase, the components are set to their new values, andmessages andevents have been queued.
If the current request is identified as a partial request, the partial context is retrievedfrom the FacesContext, and the partial processingmethod is applied.
ProcessValidations Phase
During this phase, the JavaServer Faces implementation processes all validatorsregistered on the components in the tree, by using its validate (processValidators)method. It examines the component attributes that specify the rules for the validationand compares these rules to the local value stored for the component. The JavaServerFaces implementation also completes conversions for input components that do nothave the immediate attribute set to true.
If the local value is invalid, or if any conversion fails, the JavaServer Facesimplementation adds an errormessage to the FacesContext instance, and the lifecycleadvances directly to the Render Response phase so that the page is rendered again withthe errormessages displayed. If there were conversion errors from the Apply RequestValues phase, themessages for these errors are also displayed.
If any validatemethods or event listeners have called the renderResponsemethodon the current FacesContext, the JavaServer Faces implementation skips to theRender Response phase.
At this point, if the application needs to redirect to a different web application resourceor generate a response that does not contain any JavaServer Faces components, it cancall the FacesContext.responseCompletemethod.
If events have been queued during this phase, the JavaServer Faces implementationbroadcasts them to interested listeners.
If the current request is identified as a partial request, the partial context is retrievedfrom the Faces Context, and the partial processing method is applied.
The Lifecycle of a JavaServer Faces Application
The Java EE 6Tutorial54
UpdateModelValues Phase
After the JavaServer Faces implementation determines that the data is valid, ittraverses the component tree and sets the corresponding server-side object propertiesto the components’ local values. The JavaServer Faces implementation updates onlythe bean properties pointed at by an input component’s value attribute. If the local datacannot be converted to the types specified by the bean properties, the lifecycleadvances directly to the Render Response phase so that the page is re-rendered witherrors displayed. This is similar to what happens with validation errors.
If any updateModelsmethods or any listeners have called the renderResponsemethod on the current FacesContext instance, the JavaServer Faces implementationskips to the Render Response phase.
At this point, if the application needs to redirect to a different web application resourceor generate a response that does not contain any JavaServer Faces components, it cancall the FacesContext.responseCompletemethod.
If any events have been queued during this phase, the JavaServer Facesimplementation broadcasts them to interested listeners.
If the current request is identified as a partial request, the partial context is retrievedfrom the FacesContext, and the partial processingmethod is applied.
InvokeApplicationPhase
During this phase, the JavaServer Faces implementation handles any application-levelevents, such as submitting a form or linking to another page.
At this point, if the application needs to redirect to a different web application resourceor generate a response that does not contain any JavaServer Faces components, it cancall the FacesContext.responseCompletemethod.
If the view being processed was reconstructed from state information from a previousrequest and if a component has fired an event, these events are broadcast to interestedlisteners.
Finally, the JavaServer Faces implementation transfers control to the Render Responsephase.
Render ResponsePhase
During this phase, JavaServer Faces builds the view and delegates authority to theappropriate resource for rendering the pages.
The Lifecycle of a JavaServer Faces Application
Chapter 3 • JavaServer FacesTechnology: Advanced Concepts 55
If this is an initial request, the components that are represented on the page will beadded to the component tree. If this is not an initial request, the components arealready added to the tree, so they need not be added again.
If the request is a postback and errors were encountered during the Apply RequestValues phase, Process Validations phase, or UpdateModel Values phase, the originalpage is rendered again during this phase. If the pages contain h:message orh:messages tags, any queued errormessages are displayed on the page.
After the content of the view is rendered, the state of the response is saved so thatsubsequent requests can access it. The saved state is available to the Restore Viewphase.
Partial Processing andPartial Rendering
The JavaServer Faces lifecycle spans all of the execute and render processes of anapplication. It is also possible to process and render only parts of an application, suchas a single component. For example, the JavaServer Faces Ajax framework cangenerate requests containing information on which particular componentmay beprocessed and which particular componentmay be rendered back to the client.
Once such a partial request enters the JavaServer Faces lifecycle, the information isidentified and processed by a javax.faces.context.PartialViewContext object.The JavaServer Faces lifecycle is still aware of such Ajax requests andmodifies thecomponent tree accordingly.
The execute and render attributes of the f:ajax tag are used to identify whichcomponentsmay be executed and rendered. Formore information on these attributes,see Chapter 4, “Using Ajax with JavaServer Faces Technology.”
The Lifecycle of a Facelets Application
The JavaServer Faces specification defines the lifecycle of a JavaServer Facesapplication. Formore information on this lifecycle, see “The Lifecycle of a JavaServerFaces Application” on page 50. The following steps describe that process as applied to aFacelets-based application.
1. When a client, such as a browser, makes a new request to a page that is createdusing Facelets, a new component tree or javax.faces.component.UIViewRoot iscreated and placed in the FacesContext.
2. The UIViewRoot is applied to the Facelets, and the view is populated withcomponents for rendering.
3. The newly built view is rendered back as a response to the client.
Partial Processing and Partial Rendering
The Java EE 6Tutorial56
4. On rendering, the state of this view is stored for the next request. The state of inputcomponents and form data is stored.
5. The client may interact with the view and request another view or change from theJavaServer Faces application. At this time the saved view is restored from the storedstate.
6. The restored view is once again passed through the JavaServer Faces lifecycle,which eventually will either generate a new view or re-render the current view ifthere were no validation problems and no action was triggered.
7. If the same view is requested, the stored view is rendered once again.8. If a new view is requested, then the process described in Step 2 is continued.9. The new view is then rendered back as a response to the client.
User Interface ComponentModel
In addition to the lifecycle description, an overview of JavaServer Faces architectureprovides better understanding of the technology.
JavaServer Faces components are the building blocks of a JavaServer Faces view. Acomponent can be a user interface (UI) component or a non-UI component.
JavaServer Faces UI components are configurable, reusable elements that compose theuser interfaces of JavaServer Faces applications. A component can be simple, such as abutton, or can be compound, such as a table, composed ofmultiple components.
JavaServer Faces technology provides a rich, flexible component architecture thatincludes the following:
■ A set of javax.faces.component.UIComponent classes for specifying the state andbehavior of UI components
■ A renderingmodel that defines how to render the components in various ways■ A conversionmodel that defines how to register data converters onto a component■ An event and listenermodel that defines how to handle component events■ A validationmodel that defines how to register validators onto a component■ Anavigationmodel that defines page navigation and the sequence in which pages
are loaded
This section briefly describes each of these pieces of the component architecture.
User Interface ComponentModel
Chapter 3 • JavaServer FacesTechnology: Advanced Concepts 57
User Interface Component Classes
JavaServer Faces technology provides a set of UI component classes and associatedbehavioral interfaces that specify all the UI component functionality, such as holdingcomponent state, maintaining a reference to objects, and driving event handling andrendering for a set of standard components.
The component classes are completely extensible, allowing component writers tocreate their own custom components. See Chapter 6, “Creating CustomUIComponents andOther CustomObjects,” formore information.
The abstract base class for all components is javax.faces.component.UIComponent.JavaServer Faces UI component classes extend the UIComponentBase class (a subclassof UIComponent), which defines the default state and behavior of a component. Thefollowing set of component classes is included with JavaServer Faces technology:■ UIColumn: Represents a single column of data in a UIData component.■ UICommand: Represents a control that fires actions when activated.■ UIData: Represents a data binding to a collection of data represented by a
javax.faces.model.DataModel instance.■ UIForm: Represents an input form to be presented to the user. Its child components
represent (among other things) the input fields to be included when the form issubmitted. This component is analogous to the form tag in HTML.
■ UIGraphic: Displays an image.■ UIInput: Takes data input from a user. This class is a subclass of UIOutput.■ UIMessage: Displays a localized errormessage.■ UIMessages: Displays a set of localized errormessages.■ UIOutcomeTarget: Displays a hyperlink in the form of a link or a button.■ UIOutput: Displays data output on a page.■ UIPanel: Manages the layout of its child components.■ UIParameter: Represents substitution parameters.■ UISelectBoolean: Allows a user to set a boolean value on a control by selecting or
deselecting it. This class is a subclass of the UIInput class.■ UISelectItem: Represents a single item in a set of items.■ UISelectItems: Represents an entire set of items.■ UISelectMany: Allows a user to select multiple items from a group of items. This
class is a subclass of the UIInput class.■ UISelectOne: Allows a user to select one item from a group of items. This class is a
subclass of the UIInput class.
User Interface ComponentModel
The Java EE 6Tutorial58
■ UIViewParameter: Represents the query parameters in a request. This class is asubclass of the UIInput class.
■ UIViewRoot: Represents the root of the component tree.
In addition to extending UIComponentBase, the component classes also implementone ormore behavioral interfaces, each of which defines certain behavior for a set ofcomponents whose classes implement the interface.
These behavioral interfaces, all defined in the javax.faces.component package unlessotherwise stated, are as follows:■ ActionSource: Indicates that the component can fire an action event. This
interface is intended for use with components based on JavaServer Facestechnology 1.1_01 and earlier versions. This interface is deprecated in JavaServerFaces 2.
■ ActionSource2: Extends ActionSource, and therefore provides the samefunctionality. However, it allows components to use the Expression Language (EL)when they are referencingmethods that handle action events.
■ EditableValueHolder: Extends ValueHolder and specifies additional features foreditable components, such as validation and emitting value-change events.
■ NamingContainer: Mandates that each component rooted at this component havea unique ID.
■ StateHolder: Denotes that a component has state that must be saved betweenrequests.
■ ValueHolder: Indicates that the componentmaintains a local value as well as theoption of accessing data in themodel tier.
■ javax.faces.event.SystemEventListenerHolder: Maintains a list ofjavax.faces.event.SystemEventListener instances for each type ofjavax.faces.event.SystemEvent defined by that class.
■ javax.faces.component.behavior.ClientBehaviorHolder: Adds the ability toattach javax.faces.component.behavior.ClientBehavior instances such as areusable script.
UICommand implements ActionSource2 and StateHolder. UIOutput and componentclasses that extend UIOutput implement StateHolder and ValueHolder. UIInput andcomponent classes that extend UIInput implement EditableValueHolder,StateHolder, and ValueHolder. UIComponentBase implements StateHolder.
Only component writers will need to use the component classes and behavioralinterfaces directly. Page authors and application developers will use a standardcomponent by including a tag that represents it on a page.Most of the components canbe rendered in different ways on a page. For example, a UICommand component can berendered as a button or a hyperlink.
User Interface ComponentModel
Chapter 3 • JavaServer FacesTechnology: Advanced Concepts 59
The next section explains how the renderingmodel works and how page authors canchoose to render the components by selecting the appropriate tags.
Component RenderingModel
The JavaServer Faces component architecture is designed such that the functionality ofthe components is defined by the component classes, whereas the componentrendering can be defined by a separate renderer class. This design has several benefits,including the following:■ Component writers can define the behavior of a component once but create
multiple renderers, each of which defines a different way to render the componentto the same client or to different clients.
■ Page authors and application developers can change the appearance of acomponent on the page by selecting the tag that represents the appropriatecombination of component and renderer.
A render kit defines how component classes map to component tags that areappropriate for a particular client. The JavaServer Faces implementation includes astandardHTML render kit for rendering to anHTML client.
The render kit defines a set of javax.faces.render.Renderer classes for eachcomponent that it supports. Each Renderer class defines a different way to render theparticular component to the output defined by the render kit. For example, aUISelectOne component has three different renderers. One of them renders thecomponent as a set of radio buttons. Another renders the component as a combo box.The third one renders the component as a list box. Similarly, a UICommand componentcan be rendered as a button or a hyperlink, using the h:commandButton orh:commandLink tag. The command part of each tag corresponds to the UICommand class,specifying the functionality, which is to fire an action. The Button or Link part of eachtag corresponds to a separate Renderer class that defines how the component appearson the page.
Each custom tag defined in the standardHTML render kit is composed of thecomponent functionality (defined in the UIComponent class) and the renderingattributes (defined by the Renderer class).
The section “Adding Components to a Page UsingHTMLTags” in The Java EE 6Tutorial: Basic Concepts lists all supported component tags and illustrates how to usethe tags in an example.
The JavaServer Faces implementation provides a custom tag library for renderingcomponents in HTML.
User Interface ComponentModel
The Java EE 6Tutorial60
ConversionModel
A JavaServer Faces application can optionally associate a component with server-sideobject data. This object is a JavaBeans component, such as amanaged bean. Anapplication gets and sets the object data for a component by calling the appropriateobject properties for that component.
When a component is bound to an object, the application has two views of thecomponent’s data:■ Themodel view, in which data is represented as data types, such as int or long.■ The presentation view, in which data is represented in amanner that can be read or
modified by the user. For example, a java.util.Datemight be represented as atext string in the format mm/dd/yy or as a set of three text strings.
The JavaServer Faces implementation automatically converts component databetween these two views when the bean property associated with the component is ofone of the types supported by the component’s data. For example, if aUISelectBoolean component is associated with a bean property of typejava.lang.Boolean, the JavaServer Faces implementation will automatically convertthe component’s data from String to Boolean. In addition, some component datamust be bound to properties of a particular type. For example, a UISelectBooleancomponentmust be bound to a property of type boolean or java.lang.Boolean.
Sometimes youmight want to convert a component’s data to a type other than astandard type, or youmight want to convert the format of the data. To facilitate this,JavaServer Faces technology allows you to register ajavax.faces.convert.Converter implementation on UIOutput components andcomponents whose classes subclass UIOutput. If you register the Converterimplementation on a component, the Converter implementation converts thecomponent’s data between the two views.
You can either use the standard converters supplied with the JavaServer Facesimplementation or create your own custom converter. Custom converter creation iscovered in Chapter 6, “Creating CustomUI Components andOther CustomObjects.”
Event and ListenerModel
The JavaServer Faces event and listenermodel is similar to the JavaBeans eventmodelin that it has strongly typed event classes and listener interfaces that an application canuse to handle events generated by components.
The JavaServer Faces specification defines three types of events: application events,system events, and data-model events.
User Interface ComponentModel
Chapter 3 • JavaServer FacesTechnology: Advanced Concepts 61
Application events are tied to a particular application and are generated by aUIComponent. They represent the standard events available in previous versions ofJavaServer Faces technology.
An event object identifies the component that generated the event and storesinformation about the event. To be notified of an event, an applicationmust providean implementation of the listener class andmust register it on the component thatgenerates the event.When the user activates a component, such as by clicking abutton, an event is fired. This causes the JavaServer Faces implementation to invokethe listenermethod that processes the event.
JavaServer Faces supports two kinds of application events: action events andvalue-change events.
An action event (class javax.faces.event.ActionEvent) occurs when the useractivates a component that implements javax.faces.component.ActionSource.These components include buttons and hyperlinks.
A value-change event (class javax.faces.event.ValueChangeEvent) occurs when theuser changes the value of a component represented by UIInput or one of its subclasses.An example is selecting a check box, an action that results in the component’s valuechanging to true. The component types that can generate these types of events are theUIInput, UISelectOne, UISelectMany, and UISelectBoolean components.Value-change events are fired only if no validation errors are detected.
Depending on the value of the immediate property (see “The immediate Attribute” inThe Java EE 6 Tutorial: Basic Concepts) of the component emitting the event, actionevents can be processed during the invoke application phase or the apply requestvalues phase, and value-change events can be processed during the process validationsphase or the apply request values phase.
System events are generated by an Object rather than a UIComponent. They aregenerated during the execution of an application at predefined times. They areapplicable to the entire application rather than to a specific component.
A data-model event occurs when a new row of a UIData component is selected.
There are two ways to cause your application to react to action events or value-changeevents that are emitted by a standard component:■ Implement an event listener class to handle the event and register the listener on
the component by nesting either an f:valueChangeListener tag or anf:actionListener tag inside the component tag.
■ Implement amethod of amanaged bean to handle the event and refer to themethod with amethod expression from the appropriate attribute of thecomponent’s tag.
User Interface ComponentModel
The Java EE 6Tutorial62
See “Implementing an Event Listener” on page 117 for information on how toimplement an event listener. See “Registering Listeners on Components” in The JavaEE 6 Tutorial: Basic Concepts for information on how to register the listener on acomponent.
See “Writing aMethod toHandle an Action Event” in The Java EE 6 Tutorial: BasicConcepts and “Writing aMethod toHandle a Value-Change Event” in The Java EE 6Tutorial: Basic Concepts for information on how to implementmanaged beanmethods that handle these events.
See “Referencing aManaged BeanMethod” in The Java EE 6 Tutorial: Basic Conceptsfor information on how to refer to themanaged beanmethod from the component tag.
When emitting events from custom components, youmust implement theappropriate event class andmanually queue the event on the component in addition toimplementing an event listener class or amanaged beanmethod that handles theevent. “Handling Events for CustomComponents” on page 119 explains how to dothis.
ValidationModel
JavaServer Faces technology supports amechanism for validating the local data ofeditable components (such as text fields). This validation occurs before thecorrespondingmodel data is updated tomatch the local value.
Like the conversionmodel, the validationmodel defines a set of standard classes forperforming common data validation checks. The JavaServer Faces core tag library alsodefines a set of tags that correspond to the standardjavax.faces.validator.Validator implementations. See “Using the StandardValidators” in The Java EE 6 Tutorial: Basic Concepts for a list of all the standardvalidation classes and corresponding tags.
Most of the tags have a set of attributes for configuring the validator’s properties, suchas theminimum andmaximum allowable values for the component’s data. The pageauthor registers the validator on a component by nesting the validator’s tag within thecomponent’s tag.
In addition to validators that are registered on the component, you can declare adefault validator which is registered on all UIInput components in the application. Formore information on default validators, see “Using Default Validators” on page 159.
User Interface ComponentModel
Chapter 3 • JavaServer FacesTechnology: Advanced Concepts 63
The validationmodel also allows you to create your own custom validator andcorresponding tag to perform custom validation. The validationmodel provides twoways to implement custom validation:■ Implement a Validator interface that performs the validation.■ Implement amanaged beanmethod that performs the validation.
If you are implementing a Validator interface, youmust also:■ Register the Validator implementation with the application.■ Create a custom tag or use an f:validator tag to register the validator on the
component.
In the previously described standard validationmodel, the validator is defined for eachinput component on a page. The Bean Validationmodel allows the validator to beapplied to all fields in a page. See “Using Bean Validation” inThe Java EE 6 Tutorial:Basic Concepts and Chapter 22, “Bean Validation: Advanced Topics,” formoreinformation on Bean Validation.
NavigationModel
The JavaServer Faces navigationmodel makes it easy to define page navigation and tohandle any additional processing that is needed to choose the sequence in which pagesare loaded.
In JavaServer Faces technology, navigation is a set of rules for choosing the next pageor view to be displayed after an application action, such as when a button or hyperlinkis clicked.
Navigation can be implicit or user-defined. Implicit navigation comes into play whenuser-defined navigation rules are not available. Formore information on implicitnavigation, see “Implicit Navigation Rules” on page 164.
User-defined navigation rules are declared in zero ormore application configurationresource files, such as faces-config.xml, by using a set of XML elements. The defaultstructure of a navigation rule is as follows:
<navigation-rule>
<description></description
<from-view-id></from-view-id>
<navigation-case>
<from-action></from-action>
<from-outcome></from-outcome>
<if></if>
<to-view-id></to-view-id>
</navigation-case>
</navigation-rule>
User Interface ComponentModel
The Java EE 6Tutorial64
User-defined navigation is handled as follows:■ Define the rules in the application configuration resource file.■ Refer to an outcome String from the button or hyperlink component’s action
attribute. This outcome String is used by the JavaServer Faces implementation toselect the navigation rule.
Here is an example navigation rule:
<navigation-rule>
<from-view-id>/greeting.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/response.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
This rule states that when a command component (such as an h:commandButton or anh:commandLink) on greeting.xhtml is activated, the application will navigate fromthe greeting.xhtml page to the response.xhtml page if the outcome referenced bythe button component’s tag is success. Here is the h:commandButton tag fromgreeting.xhtml that specifies a logical outcome of success:
<h:commandButton id="submit" action="success"value="Submit" />
As the example demonstrates, each navigation-rule element defines how to get fromone page (specified in the from-view-id element) to the other pages of the application.The navigation-rule elements can contain any number of navigation-caseelements, each of which defines the page to open next (defined by to-view-id) basedon a logical outcome (defined by from-outcome) .
Inmore complicated applications, the logical outcome can also come from the returnvalue of an actionmethod in amanaged bean. This method performs some processingto determine the outcome. For example, themethod can check whether the passwordthe user entered on the pagematches the one on file. If it does, themethodmightreturn success; otherwise, it might return failure. An outcome of failuremightresult in the logon page being reloaded. An outcome of successmight cause the pagedisplaying the user’s credit card activity to open. If you want the outcome to bereturned by amethod on a bean, youmust refer to themethod using amethodexpression, with the action attribute, as shown by this example:
<h:commandButton id="submit"action="#{userNumberBean.getOrderStatus}" value="Submit" />
When the user clicks the button represented by this tag, the corresponding componentgenerates an action event. This event is handled by the default
User Interface ComponentModel
Chapter 3 • JavaServer FacesTechnology: Advanced Concepts 65
javax.faces.event.ActionListener instance, which calls the actionmethodreferenced by the component that triggered the event. The actionmethod returns alogical outcome to the action listener.
The listener passes the logical outcome and a reference to the actionmethod thatproduced the outcome to the defaultjavax.faces.application.NavigationHandler. The NavigationHandler selectsthe page to display next bymatching the outcome or the actionmethod referenceagainst the navigation rules in the application configuration resource file by thefollowing process:
1. The NavigationHandler selects the navigation rule that matches the pagecurrently displayed.
2. It matches the outcome or the actionmethod reference that it received from thedefault javax.faces.event.ActionListener with those defined by thenavigation cases.
3. It tries tomatch both themethod reference and the outcome against the samenavigation case.
4. If the previous step fails, the navigation handler attempts tomatch the outcome.5. Finally, the navigation handler attempts tomatch the actionmethod reference if
the previous two attempts failed.6. If no navigation case is matched, it displays the same view again.
When the NavigationHandler achieves amatch, the render response phase begins.During this phase, the page selected by the NavigationHandlerwill be rendered.
The Duke's Tutoring case study example application uses navigation rules in thebusiness methods that handle creating, editing, and deleting the users of theapplication. For example, the form for creating a student has the followingh:commandButton tag:
<h:commandButton id="submit"action="#{adminBean.createStudent(studentManager.newStudent)}"value="#{bundle[’action.submit’]}"/>
The action event calls the dukestutoring.ejb.AdminBean.createStudentmethod:
public String createStudent(Student student) {
em.persist(student);
return "createdStudent";}
The return value of createdStudent has a corresponding navigation case in thefaces-config.xml configuration file:
<navigation-rule>
<from-view-id>/admin/student/createStudent.xhtml</from-view-id>
User Interface ComponentModel
The Java EE 6Tutorial66
<navigation-case>
<from-outcome>createdStudent</from-outcome>
<to-view-id>/admin/index.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
After the student is created, the user is returned to the Administration index page.
Formore information on how to define navigation rules, see “Configuring NavigationRules” on page 161.
Formore information on how to implement actionmethods to handle navigation, see“Writing aMethod toHandle an Action Event” in The Java EE 6 Tutorial: BasicConcepts.
Formore information on how to reference outcomes or actionmethods fromcomponent tags, see “Referencing aMethod That PerformsNavigation” in The JavaEE 6 Tutorial: Basic Concepts.
User Interface ComponentModel
Chapter 3 • JavaServer FacesTechnology: Advanced Concepts 67
This page intentionally left blank
Index
Numbers andSymbols
@Alternative annotation, 251–253@ApplicationScoped annotation, 143@AroundInvoke annotation, 454@AroundTimeout annotation, 454@Asynchronous annotation, 242@Context annotation, 193–196@CookieParam annotation, 193–196@CustomScoped annotation, 143@Decorator annotation, 262–263@Delegate annotation, 262–263@Disposes annotation, 256@FormParam annotation, 193–196@GroupSequence annotation, 451–452@HeaderParam annotation, 193–196@ManagedBean annotation, 142–143@MatrixParam annotation, 193–196@MessageDriven annotation, 419@MultipartConfig annotation, 175–176@NoneScoped annotation, 143@Observes annotation, 258–259@PathParam annotation, 193–196@PostConstruct annotation, 454
session beans using JMS, 418@PreDestroy annotation, 454
session beans using JMS, 418@Produces annotation, 254–256@QueryParam annotation, 193–196@RequestScoped annotation, 143@Resource annotation
JMS resources, 228, 350, 351@ResourceDependency annotation, 81
@SessionScoped annotation, 143@ViewScoped annotation, 143
A
acknowledgemethod, 360acknowledgingmessages, Seemessage
acknowledgmentaction events, 61–63, 65, 117–119
ActionEvent class, 117, 118actionListener attribute, 102ActionListener implementation, 117,
118–119f:actionListener tag, 98processAction(ActionEvent)method, 118
actionmethod, 65administered objects, 345, 349–351
See also connection factories, destinationscreating and removing, 381–383
Administration Console, 35starting, 42–43
Ajaxerror handling, 76–77event attribute of f:ajax tag, 74example, 81–85execute attribute of f:ajax tag, 74–75grouping components, 78–79immediate attribute of f:ajax tag, 75listener attribute of f:ajax tag, 75loading JavaScript resource library, 79–81monitoring events, 75–76
513
Ajax (Continued)onerror attribute of f:ajax tag, 76–77onevent attribute of f:ajax tag, 75–76overview, 70receiving responses, 77–78render attribute of f:ajax tag, 77–78request lifecycle, 78sending requests, 73–75using JavaScript API directly, 80–81using with Facelets, 71–73using with JavaServer Faces technology, 69–85
alternativesCDI, 251–253example, 265–270
annotations, 3interceptormetadata, 454JAX-RS, 193–196
Ant tool, 40–41appclient tool, 35applet container, 15applets, 9, 10application client container, 15application clients, 8–9
securing, 331–332application clients, JMS
building, 383, 386, 390examples, 228, 378–405packaging, 392running, 384–386, 386–388, 390–392, 392–393running onmultiple systems, 398–405
asadmin tool, 35asynchronousmessage consumption, 348
See alsomessage-driven beansJMS client example, 388–393
asynchronousmethod invocationcalling asynchronous business
methods, 243–244cancelling, 243–244checking status, 244creating asynchronous business methods, 242example, 244–248java.util.concurrent.Future<V>
interface, 241retrieving results, 243
session beans, 241–248authentication
certificate-basedmutual, 317client, 316, 319mutual, 317–321user name/password-basedmutual, 318
AUTO_ACKNOWLEDGEmode, 360auto commit, 28
Bbean-managed transactions, 374Bean Validation, 30
advanced, 449–452custom constraints, 449–450groups, 451–452localization, 450messages, 450ordering, 451–452resource bundles, 450
bundles, See resource bundlesBytesMessage interface, 357
CCallbackHandler interface, 331capture-schema tool, 35CDI, SeeContexts andDependency Injection
(CDI) for the Java EE platformcertificate authorities, 312certificates
client, 320–321digital, 311–316server, 315–316server, generating, 312–314using for authentication, 314
character encodings, 188–189character sets, 188CLIENT_ACKNOWLEDGEmode, 360client certificates, generating, 320–321client ID, for durable subscriptions, 364clients
authenticating, 316, 319
Index
The Java EE 6Tutorial514
securing, 331–332commitmethod (JMS), 366–368component binding, 133, 137–138
binding attribute, 133, 137component-managed sign-on, 332, 333component renderingmodel, 57, 60
decodemethod, 53, 111, 119, 124decoding, 99, 106delegated implementation, 99direct implementation, 99encodemethod, 125encodeBeginmethod, 109encodeChildrenmethod, 109encodeEndmethod, 109, 115encoding, 99, 106HTML render kit, 120, 165render kit, 60Renderer class, 60Renderer implementation, 165RenderKit class, 60RenderKit implementation, 165
component tag attributesaction attribute, 103actionListener attribute, 102alt attribute, 102binding attribute, 133, 137converter attribute, 126immediate attribute, 103rendered attribute, 137value attribute, 103, 133, 134–136var attribute, 187
component tags, 60, 62h:graphicImage tag, 102
composite componentsadvanced features, 87–93attributes, 87–88default attribute, 87example, 89–93f:validateBean tag, 89f:validateRegex tag, 89f:validateRequired tag, 89invokingmanaged beans, 88method-signature attribute, 88name attribute, 87
required attribute, 87type attribute, 88validating values, 89
concurrent access to entity data, 297–299conditional HTTP requests, JAX-RS, 199–200configuring JavaServer Faces applications
Application class, 145application configuration resource
files, 144–146configuringmanaged beans, 142–143, 146–155configuring navigation rules
See configuring navigation ruleserrormessage registration, 128faces-config.xml files, 162including the classes, pages, and other
resources, 173javax.faces.application.CONFIG_FILES
context parameter, 144registering custom converters, 160registering custom renderers, 165–167registering customUI components, 167–168registering custom validators, 159–160registeringmessages, 155–158specifying where UI component state is
saved, 114value binding, 134–136
configuringmanaged beans, 103, 146–155configuring navigation rules, 64, 161–164
from-action element, 162from-view-id element, 162navigation-case element, 162, 163navigation-rule element, 162to-view-id element, 162
connection factories, 350creating, 231, 381–382injecting resources, 228, 350specifying for remote servers, 400–401
Connection interface (JMS), 351ConnectionFactory interface (JMS), 350connections, JMS
introduction, 351managing in enterprise bean applications, 370
connectors, See Java EE Connector architecturecontainer-managed sign-on, 332, 333
Index
515
containers, 13–15See also EJB containerapplication client, 15configurable services, 13nonconfigurable services, 13services, 13web, 14
Contexts andDependency Injection (CDI) for theJava EE platform, 29advanced topics, 251–264alternatives, 251–253convertingmanaged beans to JAX-RS root
resource classes, 199decorators, 262–263disposermethods, 256events, 257–260examples, 265–289integrating with JAX-RS, 198–199interceptors, 260–262observermethods, 258–259producer fields, 254–256producermethods, 254–256specialization, 253stereotypes, 263–264
conversionmodel, 57, 61See also convertersconverter attribute, 126Converter implementations, 61, 126Converter interface, 124converting data betweenmodel and
presentation, 61model view, 124presentation view, 124
converter tags, f:converter tag, 126converters, 53, 57
custom converters, 61, 126–127standard, 61
converting data, See conversionmodelcreateBrowsermethod, 394criteria queries, string-based, 293–295cryptography, public-key, 312custom converters
binding tomanaged bean properties, 138–139creating, 123–127
getAsObject(FacesContext, UIComponent,
String)method, 124getAsObjectmethod, 124getAsString(FacesContext, UIComponent,
Object)method, 124getAsStringmethod, 125registering, 160using, 126–127
custom objectsSee also custom renderers, custom tags, custom
UI components, custom validatorscustom converters, 126–127using, 121–123using custom components, renderers and tags
together, 99–100custom renderers
creating the Renderer class, 115–116determining necessity of, 98–99performing decoding, 111–112performing encoding, 109–111registering with a render kit, 165–167
custom tags, 64, 99–100getRendererTypemethod, 117identifying the renderer type, 115specifying, 131tag library descriptor, 105, 131
customUI componentscreating, 95–139creating component classes, 106–114custom objects, 121delegating rendering, 114–117determining necessity of, 97–98handling events emitted by, 119–120queueEventmethod, 111registering
See registering customUI componentsrestoreState(FacesContext, Object)
method, 113–114saveState(FacesContext)method, 113–114saving state, 113–114steps for creating, 105–106
custom validators, 128–133binding tomanaged bean properties, 138–139custom validator tags, 131
Index
The Java EE 6Tutorial516
f:validator tag, 128, 131implementing the Validator
interface, 129–131registering, 159–160using, 132–133validatemethod, 129Validator implementation, 129, 131Validator interface, 128
Ddata encryption, 316databases, EIS tier, 6debugging, Java EE applications, 45–46decorators
CDI, 262–263example, 286–289
deliverymodes, 361–362JMSDeliveryModemessage header field, 356
DeliveryMode interface, 361–362Dependency Injection for Java (JSR 330), 29–30deployer roles, 21deployment descriptors, 17
Java EE, 18runtime, 18web application, 168
Destination interface, 350–351destinations, 350–351
See also queues, temporary destinations, topicscreating, 231, 381–382injecting resources, 228, 350JMSDestinationmessage header field, 356temporary, 363, 424, 438–439
development roles, 19–21application assemblers, 20application client developers, 20application component providers, 20application deployers and administrators, 21enterprise bean developers, 20Java EE product providers, 19tool providers, 19web component developers, 20
digital signatures, 312disposermethods, CDI, 256
domains, 41downloading, GlassFish Server, 38DUPS_OK_ACKNOWLEDGEmode, 361durable subscriptions, 364–366
examples, 409–410, 416–421
Eeager attribute, managed beans, 143EAR files, 17EIS tier, 12
security, 332–336EJB container, 14
See also embedded enterprise bean containermessage-driven beans, 370–372onMessagemethod, invoking, 230–231
EL, method-binding expressions, 65embedded enterprise bean container
See also EJB container, enterprise beanscreating, 237–238developing applications, 236examples, 239–240initializing enterprise beanmodules, 237–238overview, 235running applications, 236session bean references, 238shutting down, 238
enterprise applications, 3enterprise beans, 11, 25–26
See also embedded enterprise bean containerconverting to JAX-RS root resource
classes, 198–199finding, 238implementor of business logic, 11integrating with JAX-RS, 198–199interceptors, 453–461testing, 239–240
Enterprise Information Systems, See EIS tierentities, controlling caching, 304–305entity data
lockmodes, 299–302optimistic locking, 297, 298–299pessimistic locking, 298, 301–302
event and listenermodel, 57, 61–63
Index
517
event and listenermodel (Continued)See also action eventsbinding listeners tomanaged bean
properties, 138–139Event class, 62event handlers, 53, 105event listeners, 53, 54, 55handling events of customUI
components, 119–120implementing event listeners, 117–119Listener class, 62queueEventmethod, 111
eventsCDI, 257–260example, 280–286
examples, 37–46Ajax, 81–85asynchronousmethod invocation, session
beans, 244–248building, 43CDI, 265–289composite components, 89–93connectors, 463–467directory structure, 44Duke’s Bookstore case study, 471–478Duke’s Forest case study, 491–511Duke’s Tutoring case study, 479–489embedded enterprise bean container, 239–240file upload using servlets, 177–181interceptors, 460–461Java EE Connector architecture, 463–467JAX-RS, 209–223JMS asynchronousmessage
consumption, 388–393JMS durable subscriptions, 409–410JMS local transactions, 411–416JMSmessage acknowledgment, 406–408JMSmessage-driven beans, 227–233JMS onmultiple systems, 398–405, 429–436,
436–447JMS queue browsing, 394–398JMS synchronousmessage
consumption, 378–388JMSwith entities, 421–429
JMSwith session beans, 416–421message-driven beans, 227–233required software, 37–41resource adapters, 463–467
exceptions, JMS, 358expiration of JMSmessages, 362–363
JMSExpirationmessage header field, 356
F
Faceletsf:ajax tag, 71–73using Ajax with, 71–73
Facelets applicationslifecycle, 56–57using JavaScript in, 80–81
faces-config.xml file, 144–146FacesContext class, 52, 123
Apply Request Values phase, 53custom converters, 124performing encoding, 110Process Validations phase, 54UpdateModel Values phase, 55Validator interface, 129
form parameters, JAX-RS, 195–196
G
getPartmethod, 176–177getPartsmethod, 176–177getRollbackOnlymethod, 374GlassFish Server
downloading, 38enabling debugging, 46installation tips, 38server log, 45–46starting, 41–42stopping, 41tools, 35–36
Index
The Java EE 6Tutorial518
Hhandling events, See event and listenermodelHTTP, over SSL, 316HTTPS, 312
Iimplicit objects, 136–137
binding component values to, 136–137InitialContext interface, 32initializing properties with the managed-property
elementinitializing Array and List properties, 153initializingmanaged-bean properties, 153–155initializing Map properties, 152–153initializingmaps and lists, 155referencing a context initialization
parameter, 151–152interceptors, 453–461
CDI, 260–262classes, 454example, 460–461example (CDI), 280–286lifecycle, 454using, 455–459
internationalization, 183–189internationalizing JavaServer Faces applications
f:loadBundle tag, 187using the FacesMessage class to create a
message, 157ISO 8859 character encoding, 188
JJAAS, 34, 331–332
loginmodules, 332JACC, 31JAF, 33JAR files, 17JASPIC, 31Java API for XML Binding (JAXB), 33
using with JAX-RS, 202–208Java API for XML Processing (JAXP), 33
Java API for XMLWeb Services, See JAX-WSJava Authentication and Authorization Service, See
JAASJava Authentication Service Provider Interface for
Containers (JASPIC), 31Java Authorization Contract for Containers, See
JACCJava BluePrints, 44Java Database Connectivity API, See JDBCAPIJava DB, 35
starting, 43stopping, 43
Java EE applications, 6–12debugging, 45–46running onmore than one system, 429–436,
436–447tiers, 6–12
Java EE clients, 8–9See also application clientsweb clients, 8
Java EE components, 8Java EE Connector architecture, 30
example, 463–467Java EEmodules, 17, 18
application client modules, 19EJBmodules, 18resource adaptermodules, 19webmodules, 18
Java EE platformAPIs, 21–31JMS and, 344overview, 4–5
Java EE securitymodel, 13Java EE servers, 14Java EE transactionmodel, 13JavaMessage Service (JMS) API, See JMSJava Naming andDirectory Interface API, 32–33
See also JNDIJava Persistence API, 28Java Servlet technology, 26
See also servletsJava Transaction API, 28JavaBeans Activation Framework (JAF), 33JavaBeans components, 9
Index
519
JavaMail API, 31example, 463–467
JavaServer Faces applicationsconfiguring
See configuring JavaServer Faces applicationsJavaServer Faces core tag library
f:actionListener tag, 98f:ajax tag, 71–73f:converter tag, 126f:validator tag, 64, 128
custom validator tags, 131JavaServer Faces standardHTML render kit
library, 60, 165html_basic TLD, 120
JavaServer Faces standardHTML tag library, Seecomponent tags
JavaServer Faces standard UI components, 58, 95UIComponent component, 125
JavaServer Faces technology, 10, 26–27See also component renderingmodel,
component tags, conversionmodel, eventand listenermodel, FacesContext class,JavaServer Faces standard UI components,lifecycle of a JavaServer Faces application, UIcomponent behavioral interfaces, UIcomponent classes, validationmodel
composite components, 87–93FacesServlet class, 169partial processing, 56partial rendering, 56partial state saving, 107, 113–114using Ajax with, 69–85
JavaServer Pages Standard Tag Library, See JSTLJAX-RS, 29
accessing XML documents, 202–208advanced features, 193–223annotations, 193–196conditional HTTP requests, 199–200converting CDImanaged beans to root resource
classes, 199converting enterprise beans to root resource
classes, 198–199examples, 209–223extracting Java type of request or response, 196
form parameters, 195–196integrating with CDI, 198–199integrating with EJB technology, 198–199path parameters, 194–195query parameters, 195request headers, 193–196resource class methods, 197–198runtime content negotiation, 200–202runtime resource resolution, 197–198static content negotiation, 200–202subresource locators, 197subresourcemethods, 197subresources, 197–198URI, 193–196using JSON representations, 208using with JAXB, 202–208
JAX-WS, 34JAXB, 33
examples, 209–223generating Java entity classes fromXML
schema, 206–207generating XML schema from Java
classes, 204–205Java entity classes, 204–205returning Java entity classes in JAX-RS
resources, 204–205schema generator, 204–205using with JAX-RS, 202–208with JSON, 208xjc schema compiler tool, 206–207
JAXBElement, in JAX-RS resourcemethods, 206–207
JAXP, 33JDBCAPI, 32JMS, 30
achieving reliability and performance, 359–368administered objects, 349–351application client examples, 378–405architecture, 345basic concepts, 345–348definition, 342examples, 227–233, 377–447introduction, 341–344Java EE platform, 344, 368–375
Index
The Java EE 6Tutorial520
messaging domains, 346–348programmingmodel, 348–358
JMSCorrelationIDmessage header field, 356JMSDeliveryModemessage header field, 356JMSDestinationmessage header field, 356JMSException class, 358JMSExpirationmessage header field, 356JMSMessageIDmessage header field, 356JMSPrioritymessage header field, 356JMSRedeliveredmessage header field, 356JMSReplyTomessage header field, 356JMSTimestampmessage header field, 356JMSTypemessage header field, 356JNDI, 32–33
data source naming subcontexts, 33enterprise bean naming subcontexts, 33environment naming contexts, 33jms naming subcontext, 350namespace for JMS administered
objects, 349–351naming contexts, 32naming environments, 32naming subcontexts, 32
jsf.js file, 79–81JSON, with JAXB and JAX-RS, 208JSTL, 28JTA, 28JUnit, 239–240
Kkey pairs, 312keystores, 311–316
managing, 312keytool utility, 312
Llifecycle callback events, intercepting, 457–458lifecycle of a JavaServer Faces application, 50–56
action and value-change event processing, 62Apply Request Values phase, 53, 111custom converters, 124, 125
getRendererTypemethod (Render Responsephase), 117
immediate attribute, 103Invoke Application phase, 55performing encoding (Render Response
phase), 109Process Validations phase, 54Render Response phase, 55–56renderResponsemethod, 52, 53, 54, 55responseCompletemethod, 52, 54, 55Restore View phase, 53saving state, 114UpdateModel Values phase, 55updateModelsmethod, 55Validator interface, 130views, 53
local transactions, 366–368localization, 183–189
Bean Validation, 450log, server, 45–46loginmodules, 331–332
Mmanaged bean creation facility, 146–155managed bean declarations, 103
key-class element, 152list-entries element, 150managed-bean element, 147–150, 154managed-bean-name element, 149managed-property element, 150–155map-entries element, 150, 152map-entry element, 152null-value elements, 150value element, 150
managed bean properties, 133managed beans
See also value bindingcomposite components, 88configuring in JavaServer Faces
technology, 142–143conversionmodel, 61custom component alternative, 98event and listenermodel, 62
Index
521
managed beans (Continued)loading JavaScript, 81
Managed Beans specification, 29MapMessage interface, 357message acknowledgment, 360–361
bean-managed transactions, 375message-driven beans, 371
message bodies, 357message consumers, 353–355message consumption, 348
asynchronous, 348, 388–393synchronous, 348, 378–388
message-driven beans, 25coding, 229–231, 419, 424–425, 439examples, 227–233, 416–421, 421–429,
429–436, 436–447introduction, 370–372onMessagemethod, 230–231requirements, 229–231
message headers, 356message IDs, JMSMessageIDmessage header
field, 356Message interface, 357message listeners, 354–355
examples, 389, 424, 438–439message producers, 352–353message properties, 356message selectors, 355MessageConsumer interface, 353–355MessageListener interface, 354–355MessageProducer interface, 352–353messages
integrity, 316queueingmessages, 155using the FacesMessage class to create a
message, 157messages, JMS
body formats, 357browsing, 358definition, 345deliverymodes, 361–362expiration, 362–363headers, 356introduction, 355–357
persistence, 361–362priority levels, 362properties, 356
messaging, definition, 341–342messaging domains, 346–348
common interfaces, 347–348point-to-point, 346–347publish/subscribe, 347
method bindingmethod-binding expressions, 65, 163method expressions, 112
method expressions, 62method invocations, intercepting, 456–457mutual authentication, 317–321
Nnaming contexts, 32naming environments, 32navigationmodel, 64–67
action attribute, 103actionmethods, 161configuring navigation rules, 161–164logical outcome, 161NavigationHandler class, 66
NetBeans IDE, 39–40NON_PERSISTENT deliverymode, 361
OObjectMessage interface, 357objects, administered, 349–351
creating and removing, 381–383observermethods, CDI, 258–259onMessagemethod
introduction, 354–355message-driven beans, 230–231, 371
Ppackage-appclient tool, 35Part interface (Servlet), 176
Index
The Java EE 6Tutorial522
path parameters, JAX-RS, 194–195persistence
concurrent access to entity data, 297–302JMS example, 421–429JMSmessages, 361–362locking strategies, 297–302second-level cache, 303–308string-based criteria queries, 293–295
PERSISTENT deliverymode, 361point-to-point messaging domain, 346–347
See also queuesPOJOs, 4priority levels, for messages, 362
JMSPrioritymessage header field, 356producer fields
CDI, 254–256example, 273–280
producermethodsCDI, 254–256example, 271–273
programmingmodel, JMS, 348–358providers, JMS, 345public key certificates, 316public-key cryptography, 312publish/subscribemessaging domain
See also topicsdurable subscriptions, 364–366introduction, 347
Q
query parameters, JAX-RS, 195Queue interface, 350–351QueueBrowser interface, 358
JMS client example, 394–398queues, 350–351
browsing, 358, 394–398creating, 350–351, 381–382injecting resources, 228temporary, 363, 424
R
realms, certificate, 314recovermethod, 361redelivery of messages, 360, 361
JMSRedeliveredmessage header field, 356registering custom converters, 160
converter element, 160registering custom renderers, 165–167
render-kit element, 165renderer element, 165
registering customUI components, 105, 167–168component element, 167
registering custom validators, 159–160validator element, 159
registeringmessages, 155–158resource-bundle element, 156
reliability, JMSadvancedmechanisms, 364–368basic mechanisms, 359–363durable subscriptions, 364–366local transactions, 366–368message acknowledgment, 360–361message expiration, 362–363message persistence, 361–362message priority levels, 362temporary destinations, 363
RemoteMethod Invocation (RMI), andmessaging, 341–342
request headers, JAX-RS, 193–196Request objects, JAX-RS, 201request/replymechanism
JMSCorrelationIDmessage header field, 356JMSReplyTomessage header field, 356temporary destinations and, 363
requests, retrieving a locale, 185Required transaction attribute, 375resource adapters, 30
example, 463–467security, 334–335
resource bundles, 183Bean Validation, 450
resources, JMS, 370RESTful web services, 29rollbackmethod (JMS), 366–368
Index
523
S
SAAJ, 34schemagen, JAXB, 204–205schemagen tool, 35scopes, using in JavaServer Faces technology, 143security
application clients, 331–332callback handlers, 331component-managed sign-on, 333container-managed sign-on, 333EIS applications, 332–336JAAS loginmodules, 332login forms, 331loginmodules, 331–332programmatic login, 332resource adapters, 334–335
sendmethod, 352–353server authentication, 316server certificates, 311–316server log, 45–46servers, Java EE
deploying onmore than one, 429–436,436–447
running JMS clients onmore thanone, 398–405
servlets, 10uploading files with, 175–181
session beans, 25See also asynchronousmethod invocationexamples, 416–421
Session interface, 352sessions, JMS, 352
managing in enterprise bean applications, 370setRollbackOnlymethod, 374sign-on
component-managed, 332, 333container-managed, 332, 333
SOAPmessages, 16, 34SOAPwith Attachments API for Java (SAAJ), 34specialization, CDI, 253SQL, 32SSL, 316standard converters, 61standard validators, 63
stereotypes, CDI, 263–264StreamMessage interface, 357string-based criteria queries, 293–295subresources, JAX-RS, 197–198subscription names, for durable subscribers, 364synchronousmessage consumption, 348
JMS client example, 378–388
Ttemporary JMS destinations, 363
examples, 424, 438–439testing
enterprise beans, 239–240unit, 239–240
TextMessage interface, 357timeout events, intercepting, 458–459timestamps, formessages, JMSTimestampmessage
header field, 356Topic interface, 350–351topics, 350–351
creating, 350–351, 381–382durable subscriptions, 364–366temporary, 363, 438–439
transactionsbean-managed, 374container-managed, 373distributed, 373–375examples, 411–416JMS and enterprise bean applications, 370local, 366–368Required attribute, 375
truststores, 311–316managing, 312
UUI component behavioral interfaces, 59
ActionSource interface, 59, 62, 106, 117ActionSource2 interface, 59, 106ClientBehaviorHolder interface, 59ConvertibleValueHolder interface, 59EditableValueHolder interface, 59, 107
Index
The Java EE 6Tutorial524
NamingContainer interface, 59, 107StateHelper interface, 107, 112, 113–114StateHolder interface, 59, 107, 113–114SystemEventListenerHolder interface, 59ValueHolder interface, 59, 107
UI component classes, 58, 60, 97See also customUI componentsjavax.faces.component package, 106UIColumn class, 58UICommand class, 58, 60UIComponent class, 57, 60UIComponentBase class, 58, 106, 109UIData class, 58UIForm class, 58UIGraphic class, 58UIInput class, 58, 62UIMessage class, 58UIMessages class, 58UIOutput class, 58, 61UIPanel class, 58UIParameter class, 58UISelectBoolean class, 58UISelectItem class, 58UISelectItems class, 58UISelectMany class, 58UISelectOne class, 58, 60UIViewRoot class, 59
Unicode character set, 188US-ASCII character set, 188UserTransaction interface, message-driven
beans, 374UTF-8 character encoding, 189
Vvalidating input, See validationmodelvalidation
customizing, 449–450groups, 451–452localization, 450messages, 450ordering, 451–452
validationmodel, 57, 63–64See also validators
Validator implementation, 63, 132Validator interface, 64
custom validator tags, 131implementing, 129
Validator implementation classes, 63validator tags
composite components, 89f:validator tag, 64, 131
validators, 53, 57custom validators, 132–133default, 159
value bindingcomponent instances to bean properties
See component bindingcomponent values and instances tomanaged
bean properties, 133–138component values to implicit objects, 136–137component values tomanaged bean
properties, 134–136value attribute, 103, 133, 134–136value-binding expressions, 134value expressions, 112, 137
value-change events, 62, 117f:valueChangeListener tag, 98processValueChange(ValueChangeEvent)
method, 117ValueChangeEvent class, 117ValueChangeListener class, 117ValueChangeListener implementation, 117
Variant class, JAX-RS, 201
WW3C, 33WAR files, 17web applications
establishing the locale, 185internationalizing and localizing, 183parsing and formatting localized dates and
numbers, 187providing localizedmessages, 184retrieving localizedmessages, 186setting the resource bundle, 186
web clients, 8
Index
525
web components, 10applets bundled with, 10JMS and, 375types, 10utility classes bundled with, 10
web container, 14webmodules, 18web services, 15–16web.xml file, 168WSDL, 16wsgen tool, 36wsimport tool, 36
X
xjc schema compiler tool, JAXB, 206–207xjc tool, 35XML, 15–16
Index
The Java EE 6Tutorial526
top related