[1] Java Platform, Enterprise Edition The Java EE Tutorial Release 7 E39031-01 September 2014 Java Platform, Enterprise Edition The Java EE Tutorial, Release 7 E39031-01 Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Primary Author: Eric Jendrock, Ricardo Cervera-Navarro, Ian Evans, Kim Haase, William Markito Contributing Author: Contributor: This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable: U.S. GOVERNMENT END USERS: Oracle programs, including any operating system, integrated software, any programs installed on the hardware, and/or documentation, delivered to U.S. Government end users are "commercial computer software" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of the programs, including any operating system, integrated software, any programs installed on the hardware, and/or documentation, shall be subject to license terms and license restrictions applicable to the programs. No other rights are granted to the U.S. Government. This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group. This software or hardware and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services. Contents Preface ........................................................................................................................................................... xxxix Audience................................................................................................................................................. xxxix Documentation Accessibility ............................................................................................................... xxxix Before You Read This Book........................................................................................................................ xl Related Documentation .............................................................................................................................. xl Conventions ................................................................................................................................................. xl Default Paths and File Names ................................................................................................................... xl Part I Introduction 1 Overview 1.1 1.2 1.3 1.3.1 1.3.2 1.3.3 1.3.3.1 1.3.3.2 1.3.3.3 1.3.3.4 1.3.3.5 1.3.4 1.3.5 1.3.6 1.4 1.4.1 1.4.2 1.5 1.5.1 1.5.2 1.5.3 1.6 1.7 1.7.1 Java EE 7 Platform Highlights................................................................................................... 1-2 Java EE Application Model ....................................................................................................... 1-2 Distributed Multitiered Applications ...................................................................................... 1-3 Security.................................................................................................................................. 1-4 Java EE Components ........................................................................................................... 1-4 Java EE Clients ..................................................................................................................... 1-5 Web Clients.................................................................................................................... 1-5 Application Clients....................................................................................................... 1-5 Applets ........................................................................................................................... 1-5 The JavaBeans Component Architecture .................................................................. 1-6 Java EE Server Communications................................................................................ 1-6 Web Components ................................................................................................................ 1-6 Business Components ......................................................................................................... 1-7 Enterprise Information System Tier.................................................................................. 1-8 Java EE Containers...................................................................................................................... 1-8 Container Services ............................................................................................................... 1-9 Container Types ................................................................................................................... 1-9 Web Services Support.............................................................................................................. 1-10 XML .................................................................................................................................... 1-11 SOAP Transport Protocol ................................................................................................ 1-11 WSDL Standard Format................................................................................................... 1-11 Java EE Application Assembly and Deployment................................................................ 1-12 Java EE 7 APIs .......................................................................................................................... 1-12 Enterprise JavaBeans Technology .................................................................................. 1-15 iii 1.7.2 1.7.3 1.7.4 1.7.5 1.7.6 1.7.7 1.7.8 1.7.9 1.7.10 1.7.11 1.7.12 1.7.13 1.7.14 1.7.15 1.7.16 1.7.17 1.7.18 1.7.19 1.7.20 1.7.21 1.8 1.8.1 1.8.2 1.8.3 1.8.4 1.8.5 1.8.6 1.8.7 1.8.8 1.8.9 1.9 Java Servlet Technology................................................................................................... 1-15 JavaServer Faces Technology .......................................................................................... 1-16 JavaServer Pages Technology ......................................................................................... 1-16 JavaServer Pages Standard Tag Library ........................................................................ 1-17 Java Persistence API ......................................................................................................... 1-17 Java Transaction API ........................................................................................................ 1-17 Java API for RESTful Web Services................................................................................ 1-17 Managed Beans ................................................................................................................. 1-17 Contexts and Dependency Injection for Java EE.......................................................... 1-18 Dependency Injection for Java ........................................................................................ 1-18 Bean Validation ................................................................................................................. 1-18 Java Message Service API................................................................................................ 1-18 Java EE Connector Architecture ..................................................................................... 1-18 JavaMail API...................................................................................................................... 1-19 Java Authorization Contract for Containers................................................................. 1-19 Java Authentication Service Provider Interface for Containers................................. 1-19 Java API for WebSocket ................................................................................................... 1-19 Java API for JSON Processing......................................................................................... 1-20 Concurrency Utilities for Java EE................................................................................... 1-20 Batch Applications for the Java Platform ...................................................................... 1-20 Java EE 7 APIs in the Java Platform, Standard Edition 7 ................................................... 1-20 Java Database Connectivity API..................................................................................... 1-20 Java Naming and Directory Interface API .................................................................... 1-21 JavaBeans Activation Framework .................................................................................. 1-21 Java API for XML Processing.......................................................................................... 1-21 Java Architecture for XML Binding ............................................................................... 1-21 Java API for XML Web Services ..................................................................................... 1-22 SOAP with Attachments API for Java ........................................................................... 1-22 Java Authentication and Authorization Service........................................................... 1-22 Common Annotations for the Java Platform ................................................................ 1-22 GlassFish Server Tools ............................................................................................................ 1-22 2 Using the Tutorial Examples 2.1 2.1.1 2.1.2 2.1.2.1 2.1.3 2.1.4 2.1.4.1 2.1.4.2 2.1.5 2.2 2.2.1 2.2.2 2.2.3 2.2.4 Required Software ...................................................................................................................... 2-1 Java Platform, Standard Edition ........................................................................................ 2-1 Java EE 7 Software Development Kit................................................................................ 2-1 SDK Installation Tips ................................................................................................... 2-2 Java EE 7 Tutorial Component........................................................................................... 2-2 NetBeans IDE ....................................................................................................................... 2-2 To Install NetBeans IDE without GlassFish Server ................................................. 2-2 To Add GlassFish Server as a Server Using NetBeans IDE.................................... 2-3 Apache Maven ..................................................................................................................... 2-3 Starting and Stopping GlassFish Server .................................................................................. 2-3 To Start GlassFish Server Using NetBeans IDE............................................................... 2-3 To Stop GlassFish Server Using NetBeans IDE ............................................................... 2-3 To Start GlassFish Server Using the Command Line ..................................................... 2-3 To Stop GlassFish Server Using the Command Line ..................................................... 2-4 iv 2.3 2.3.1 2.4 2.4.1 2.5 2.6 2.7 2.7.1 2.7.1.1 2.7.1.2 2.8 2.8.1 2.8.2 2.9 2.9.1 2.9.1.1 2.9.2 2.9.2.1 Starting the Administration Console ....................................................................................... 2-4 To Start the Administration Console Using NetBeans IDE........................................... 2-4 Starting and Stopping the Java DB Server............................................................................... 2-4 To Start the Database Server Using NetBeans IDE......................................................... 2-5 Building the Examples ............................................................................................................... 2-5 Tutorial Example Directory Structure ..................................................................................... 2-5 Java EE 7 Maven Archetypes in the Tutorial .......................................................................... 2-6 Installing the Tutorial Archetypes .................................................................................... 2-6 Installing the Tutorial Archetypes Using NetBeans IDE ........................................ 2-6 Installing the Tutorial Archetypes Using Maven .................................................... 2-6 Getting the Latest Updates to the Tutorial.............................................................................. 2-6 To Update the Tutorial Using NetBeans IDE .................................................................. 2-6 To Update the Tutorial Using the Command Line......................................................... 2-6 Debugging Java EE Applications ............................................................................................. 2-7 Using the Server Log ........................................................................................................... 2-7 To Use the Administration Console Log Viewer..................................................... 2-7 Using a Debugger ................................................................................................................ 2-7 To Debug an Application Using a Debugger ........................................................... 2-7 Part II Platform Basics 3 Resource Creation 3.1 3.2 3.3 Resources and JNDI Naming .................................................................................................... 3-1 DataSource Objects and Connection Pools ............................................................................. 3-2 Creating Resources Administratively ...................................................................................... 3-2 4 Injection 4.1 4.2 4.3 Resource Injection ....................................................................................................................... 4-1 Dependency Injection................................................................................................................. 4-2 The Main Differences between Resource Injection and Dependency Injection................. 4-2 5 Packaging 5.1 5.2 5.2.1 5.2.2 5.3 5.4 Packaging Applications ............................................................................................................. 5-1 Packaging Enterprise Beans ...................................................................................................... 5-2 Packaging Enterprise Beans in EJB JAR Modules........................................................... 5-3 Packaging Enterprise Beans in WAR Modules ............................................................... 5-3 Packaging Web Archives ........................................................................................................... 5-4 Packaging Resource Adapter Archives ................................................................................... 5-5 Part III The Web Tier 6 Getting Started with Web Applications 6.1 6.2 6.3 Web Applications........................................................................................................................ 6-1 Web Application Lifecycle......................................................................................................... 6-2 A Web Module That Uses JavaServer Faces Technology: The hello1 Example................. 6-3 v 6.3.1 6.3.1.1 6.3.2 6.3.2.1 6.3.2.2 6.3.3 6.3.3.1 6.3.3.2 6.3.3.3 6.3.4 6.3.4.1 6.3.5 6.3.5.1 6.3.5.2 6.4 6.4.1 6.4.2 6.4.2.1 6.4.3 6.4.3.1 6.4.3.2 6.5 6.5.1 6.5.1.1 6.5.1.2 6.5.2 6.5.3 6.5.3.1 6.5.4 6.5.4.1 6.5.4.2 6.6 To View the hello1 Web Module Using NetBeans IDE.................................................. 6-3 Introduction to Scopes ................................................................................................. 6-6 Packaging and Deploying the hello1 Web Module ........................................................ 6-6 To Build and Package the hello1 Web Module Using NetBeans IDE................... 6-6 To Build and Package the hello1 Web Module Using Maven ............................... 6-7 Viewing Deployed Web Modules ..................................................................................... 6-7 To View Deployed Web Modules Using the Administration Console ................ 6-7 To View Deployed Web Modules Using the asadmin Command ........................ 6-7 To View Deployed Web Modules Using NetBeans IDE......................................... 6-7 Running the Deployed hello1 Web Module .................................................................... 6-7 Dynamic Reloading of Deployed Modules .............................................................. 6-8 Undeploying the hello1 Web Module .............................................................................. 6-8 To Undeploy the hello1 Web Module Using NetBeans IDE .................................. 6-8 To Undeploy the hello1 Web Module Using Maven............................................... 6-8 A Web Module That Uses Java Servlet Technology: The hello2 Example ......................... 6-8 Mapping URLs to Web Components................................................................................ 6-9 Examining the hello2 Web Module................................................................................... 6-9 To View the hello2 Web Module Using NetBeans IDE .......................................... 6-9 Running the hello2 Example ........................................................................................... 6-11 To Run the hello2 Example Using NetBeans IDE................................................. 6-11 To Run the hello2 Example Using Maven ............................................................. 6-11 Configuring Web Applications.............................................................................................. 6-11 Setting Context Parameters ............................................................................................. 6-12 To Add a Context Parameter Using NetBeans IDE .............................................. 6-12 To Create a web.xml File Using NetBeans IDE..................................................... 6-12 Declaring Welcome Files ................................................................................................. 6-12 Mapping Errors to Error Screens.................................................................................... 6-13 To Set Up Error Mapping Using NetBeans IDE.................................................... 6-13 Declaring Resource References....................................................................................... 6-14 Declaring a Reference to a Resource....................................................................... 6-14 Declaring a Reference to a Web Service ................................................................. 6-15 Further Information about Web Applications ..................................................................... 6-15 7 JavaServer Faces Technology 7.1 7.2 7.3 7.4 7.4.1 7.4.2 7.4.3 7.4.4 7.4.5 7.5 7.6 7.6.1 7.6.2 What Is a JavaServer Faces Application? ................................................................................ 7-2 JavaServer Faces Technology Benefits ..................................................................................... 7-3 A Simple JavaServer Faces Application................................................................................... 7-4 User Interface Component Model ............................................................................................ 7-5 User Interface Component Classes ................................................................................... 7-5 Component Rendering Model ........................................................................................... 7-7 Conversion Model ............................................................................................................... 7-8 Event and Listener Model .................................................................................................. 7-8 Validation Model ................................................................................................................. 7-9 Navigation Model .................................................................................................................... 7-10 The Lifecycle of a JavaServer Faces Application ................................................................. 7-13 Overview of the JavaServer Faces Lifecycle ................................................................. 7-13 Restore View Phase .......................................................................................................... 7-15 vi 7.6.3 7.6.4 7.6.5 7.6.6 7.6.7 7.7 7.8 Apply Request Values Phase .......................................................................................... 7-15 Process Validations Phase ............................................................................................... 7-16 Update Model Values Phase ........................................................................................... 7-16 Invoke Application Phase................................................................................................ 7-17 Render Response Phase ................................................................................................... 7-17 Partial Processing and Partial Rendering ............................................................................. 7-17 Further Information about JavaServer Faces Technology ................................................. 7-18 8 Introduction to Facelets 8.1 8.2 8.3 8.3.1 8.3.1.1 8.3.1.2 8.3.2 8.3.3 8.3.3.1 8.3.3.2 8.3.3.3 8.4 8.5 8.6 8.7 8.8 8.8.1 8.8.1.1 8.8.1.2 8.8.1.3 8.8.1.4 8.8.1.5 8.9 8.9.1 8.9.2 8.9.3 8.9.3.1 8.9.3.2 8.9.3.3 8.9.3.4 8.9.3.5 What Is Facelets? ......................................................................................................................... 8-1 The Lifecycle of a Facelets Application.................................................................................... 8-3 Developing a Simple Facelets Application: The guessnumber-jsf Example Application 8-3 Creating a Facelets Application ......................................................................................... 8-4 Developing a Managed Bean ...................................................................................... 8-4 Creating Facelets Views............................................................................................... 8-5 Configuring the Application .............................................................................................. 8-7 Running the guessnumber-jsf Facelets Example............................................................. 8-8 To Build, Package, and Deploy the guessnumber-jsf Example Using NetBeans IDE 8-8 To Build, Package, and Deploy the guessnumber-jsf Example Using Maven .... 8-8 To Run the guessnumber-jsf Example....................................................................... 8-8 Using Facelets Templates........................................................................................................... 8-8 Composite Components.......................................................................................................... 8-10 Web Resources ......................................................................................................................... 8-12 Relocatable Resources ............................................................................................................. 8-13 Resource Library Contracts .................................................................................................... 8-14 The hello1-rlc Example Application .............................................................................. 8-15 Configuring the hello1-rlc Example........................................................................ 8-15 The Facelets Pages for the hello1-rlc Example ...................................................... 8-16 To Build, Package, and Deploy the hello1-rlc Example Using NetBeans IDE . 8-16 To Build, Package, and Deploy the hello1-rlc Example Using Maven .............. 8-16 To Run the hello1-rlc Example ................................................................................ 8-16 HTML5-Friendly Markup....................................................................................................... 8-17 Using Pass-Through Elements........................................................................................ 8-17 Using Pass-Through Attributes ...................................................................................... 8-18 The reservation Example Application ........................................................................... 8-20 The Facelets Pages for the reservation Application.............................................. 8-20 The Managed Bean for the reservation Application ............................................ 8-21 To Build, Package, and Deploy the reservation Example Using NetBeans IDE ......... 8-21 To Build, Package, and Deploy the reservation Example Using Maven........... 8-21 To Run the reservation Example ............................................................................. 8-22 9 Expression Language 9.1 9.2 Overview of the EL ..................................................................................................................... 9-1 Immediate and Deferred Evaluation Syntax .......................................................................... 9-2 vii 9.2.1 9.2.2 9.3 9.3.1 9.3.1.1 9.3.1.2 9.3.1.3 9.3.1.4 9.3.1.5 9.3.2 9.3.3 9.4 9.5 9.6 9.7 9.8 Immediate Evaluation......................................................................................................... 9-2 Deferred Evaluation ............................................................................................................ 9-2 Value and Method Expressions ................................................................................................ 9-3 Value Expressions................................................................................................................ 9-3 Referencing Objects ...................................................................................................... 9-3 Referencing Object Properties or Collection Elements ........................................... 9-4 Referencing Literals...................................................................................................... 9-5 Parameterized Method Calls ...................................................................................... 9-5 Where Value Expressions Can Be Used .................................................................... 9-6 Method Expressions ............................................................................................................ 9-7 Lambda Expressions ........................................................................................................... 9-7 Operations on Collection Objects ............................................................................................. 9-8 Operators...................................................................................................................................... 9-9 Reserved Words ....................................................................................................................... 9-10 Examples of EL Expressions................................................................................................... 9-11 Further Information about the Expression Language ........................................................ 9-11 10 Using JavaServer Faces Technology in Web Pages 10.1 10.2 10.2.1 10.2.1.1 10.2.1.2 10.2.1.3 10.2.1.4 10.2.1.5 10.2.2 10.2.3 10.2.4 10.2.4.1 10.2.4.2 10.2.4.3 10.2.4.4 10.2.4.5 10.2.5 10.2.5.1 10.2.5.2 10.2.6 10.2.7 10.2.8 10.2.8.1 10.2.8.2 10.2.9 10.2.10 10.2.10.1 10.2.10.2 10.2.11 Setting Up a Page ..................................................................................................................... 10-1 Adding Components to a Page Using HTML Tag Library Tags ...................................... 10-2 Common Component Tag Attributes ............................................................................ 10-4 The id Attribute ......................................................................................................... 10-4 The immediate Attribute .......................................................................................... 10-5 The rendered Attribute ............................................................................................. 10-6 The style and styleClass Attributes......................................................................... 10-6 The value and binding Attributes ........................................................................... 10-6 Adding HTML Head and Body Tags ............................................................................ 10-7 Adding a Form Component ............................................................................................ 10-7 Using Text Components .................................................................................................. 10-8 Rendering a Field with the h:inputText Tag........................................................ 10-10 Rendering a Password Field with the h:inputSecret Tag .................................. 10-10 Rendering a Label with the h:outputLabel Tag .................................................. 10-10 Rendering a Link with the h:outputLink Tag ..................................................... 10-11 Displaying a Formatted Message with the h:outputFormat Tag ..................... 10-11 Using Command Component Tags for Performing Actions and Navigation....... 10-12 Rendering a Button with the h:commandButton Tag ........................................ 10-12 Rendering a Link with the h:commandLink Tag................................................ 10-13 Adding Graphics and Images with the h:graphicImage Tag ................................... 10-13 Laying Out Components with the h:panelGrid and h:panelGroup Tags .............. 10-14 Displaying Components for Selecting One Value ..................................................... 10-15 Displaying a Check Box Using the h:selectBooleanCheckbox Tag .................. 10-16 Displaying a Menu Using the h:selectOneMenu Tag ........................................ 10-16 Displaying Components for Selecting Multiple Values............................................ 10-17 Using the f:selectItem and f:selectItems Tags ............................................................. 10-18 Using the f:selectItems Tag .................................................................................... 10-18 Using the f:selectItem Tag ...................................................................................... 10-18 Displaying the Results from Selection Components ................................................. 10-19 viii 10.2.12 10.2.13 10.2.14 10.2.15 10.2.16 10.2.16.1 Using Data-Bound Table Components........................................................................ 10-19 Displaying Error Messages with the h:message and h:messages Tags .................. 10-22 Creating Bookmarkable URLs with the h:button and h:link Tags .......................... 10-23 Using View Parameters to Configure Bookmarkable URLs .................................... 10-23 The bookmarks Example Application ......................................................................... 10-24 To Build, Package, and Deploy the bookmarks Example Using NetBeans IDE ......... 10-25 To Build, Package, and Deploy the bookmarks Example Using Maven......... 10-25 To Run the bookmarks Example ........................................................................... 10-25 Resource Relocation Using h:outputScript and h:outputStylesheet Tags.............. 10-25 Using Core Tags ..................................................................................................................... 10-27 10.2.16.2 10.2.16.3 10.2.17 10.3 11 Using Converters, Listeners, and Validators 11.1 11.1.1 11.1.2 11.1.3 11.2 11.2.1 11.2.2 11.3 11.3.1 11.3.2 11.4 11.4.1 11.4.2 11.4.3 11.4.4 Using the Standard Converters.............................................................................................. 11-1 Converting a Component's Value .................................................................................. 11-2 Using DateTimeConverter .............................................................................................. 11-3 Using NumberConverter................................................................................................. 11-4 Registering Listeners on Components .................................................................................. 11-6 Registering a Value-Change Listener on a Component.............................................. 11-6 Registering an Action Listener on a Component ......................................................... 11-7 Using the Standard Validators............................................................................................... 11-8 Validating a Component's Value.................................................................................... 11-9 Using Validator Tags........................................................................................................ 11-9 Referencing a Managed Bean Method ................................................................................ 11-10 Referencing a Method That Performs Navigation..................................................... 11-11 Referencing a Method That Handles an Action Event.............................................. 11-11 Referencing a Method That Performs Validation ...................................................... 11-11 Referencing a Method That Handles a Value-Change Event................................... 11-12 12 Developing with JavaServer Faces Technology 12.1 Managed Beans in JavaServer Faces Technology................................................................ 12-1 Creating a Managed Bean................................................................................................ 12-1 12.1.1 Using the EL to Reference Managed Beans .................................................................. 12-2 12.1.2 12.2 Writing Bean Properties.......................................................................................................... 12-3 Writing Properties Bound to Component Values ........................................................ 12-4 12.2.1 UIInput and UIOutput Properties .......................................................................... 12-4 12.2.1.1 UIData Properties ...................................................................................................... 12-5 12.2.1.2 UISelectBoolean Properties ...................................................................................... 12-6 12.2.1.3 UISelectMany Properties .......................................................................................... 12-7 12.2.1.4 UISelectOne Properties ............................................................................................. 12-7 12.2.1.5 UISelectItem Properties ............................................................................................ 12-8 12.2.1.6 UISelectItems Properties .......................................................................................... 12-8 12.2.1.7 12.2.2 Writing Properties Bound to Component Instances.................................................... 12-9 Writing Properties Bound to Converters, Listeners, or Validators ......................... 12-10 12.2.3 12.3 Writing Managed Bean Methods......................................................................................... 12-10 Writing a Method to Handle Navigation .................................................................... 12-11 12.3.1 ix 12.3.2 12.3.3 12.3.4 Writing a Method to Handle an Action Event ........................................................... 12-12 Writing a Method to Perform Validation.................................................................... 12-12 Writing a Method to Handle a Value-Change Event ................................................ 12-13 13 Using Ajax with JavaServer Faces Technology Overview of Ajax ..................................................................................................................... 13-1 13.1 Using Ajax Functionality with JavaServer Faces Technology........................................... 13-2 13.2 Using Ajax with Facelets......................................................................................................... 13-2 13.3 Using the f:ajax Tag .......................................................................................................... 13-3 13.3.1 Sending an Ajax Request ........................................................................................................ 13-4 13.4 Using the event Attribute ................................................................................................ 13-5 13.4.1 Using the execute Attribute............................................................................................. 13-5 13.4.2 Using the immediate Attribute ....................................................................................... 13-5 13.4.3 13.4.4 Using the listener Attribute............................................................................................. 13-6 13.5 Monitoring Events on the Client............................................................................................ 13-6 Handling Errors ....................................................................................................................... 13-6 13.6 Receiving an Ajax Response................................................................................................... 13-7 13.7 Ajax Request Lifecycle ............................................................................................................ 13-7 13.8 Grouping of Components ....................................................................................................... 13-8 13.9 13.10 Loading JavaScript as a Resource .......................................................................................... 13-9 Using JavaScript API in a Facelets Application ........................................................... 13-9 13.10.1 13.10.2 Using the @ResourceDependency Annotation in a Bean Class ............................... 13-10 13.11 The ajaxguessnumber Example Application ..................................................................... 13-10 The ajaxguessnumber Source Files............................................................................... 13-10 13.11.1 The ajaxgreeting.xhtml Facelets Page................................................................... 13-10 13.11.1.1 The UserNumberBean Backing Bean.................................................................... 13-11 13.11.1.2 13.11.1.3 The DukesNumberBean CDI Managed Bean...................................................... 13-12 Running the ajaxguessnumber Example..................................................................... 13-12 13.11.2 13.11.2.1 To Build, Package, and Deploy the ajaxguessnumber Example Using NetBeans IDE 13-12 To Build, Package, and Deploy the ajaxguessnumber Example Using Maven........... 13-12 13.11.2.3 To Run the ajaxguessnumber Example ................................................................ 13-12 13.12 Further Information about Ajax in JavaServer Faces Technology.................................. 13-13 13.11.2.2 14 Composite Components: Advanced Topics and an Example 14.1 14.2 14.3 14.4 14.4.1 14.4.2 14.4.3 14.4.4 14.4.4.1 Attributes of a Composite Component................................................................................. 14-1 Invoking a Managed Bean ...................................................................................................... 14-2 Validating Composite Component Values .......................................................................... 14-2 The compositecomponentexample Example Application ................................................. 14-3 The Composite Component File..................................................................................... 14-3 The Using Page ................................................................................................................. 14-4 The Managed Bean ........................................................................................................... 14-4 Running the compositecomponentexample Example................................................. 14-5 To Build, Package, and Deploy the compositecomponentexample Example Using NetBeans IDE 14-5 x 14.4.4.2 14.4.4.3 To Build, Package, and Deploy the compositecomponentexample Example Using Maven 14-5 To Run the compositecomponentexample Example............................................ 14-5 15 Creating Custom UI Components and Other Custom Objects Determining Whether You Need a Custom Component or Renderer............................. 15-2 15.1 When to Use a Custom Component .............................................................................. 15-2 15.1.1 When to Use a Custom Renderer ................................................................................... 15-4 15.1.2 Component, Renderer, and Tag Combinations............................................................ 15-4 15.1.3 Understanding the Image Map Example ............................................................................. 15-5 15.2 Why Use JavaServer Faces Technology to Implement an Image Map? ................... 15-5 15.2.1 Understanding the Rendered HTML............................................................................. 15-5 15.2.2 Understanding the Facelets Page ................................................................................... 15-6 15.2.3 Configuring Model Data.................................................................................................. 15-7 15.2.4 Summary of the Image Map Application Classes........................................................ 15-8 15.2.5 Steps for Creating a Custom Component............................................................................. 15-9 15.3 Creating Custom Component Classes .................................................................................. 15-9 15.4 Specifying the Component Family............................................................................... 15-12 15.4.1 Performing Encoding ..................................................................................................... 15-12 15.4.2 Performing Decoding..................................................................................................... 15-14 15.4.3 Enabling Component Properties to Accept Expressions .......................................... 15-14 15.4.4 Saving and Restoring State............................................................................................ 15-15 15.4.5 Delegating Rendering to a Renderer................................................................................... 15-16 15.5 Creating the Renderer Class.......................................................................................... 15-17 15.5.1 Identifying the Renderer Type...................................................................................... 15-18 15.5.2 Implementing an Event Listener ......................................................................................... 15-18 15.6 Implementing Value-Change Listeners....................................................................... 15-19 15.6.1 Implementing Action Listeners .................................................................................... 15-20 15.6.2 Handling Events for Custom Components........................................................................ 15-20 15.7 Defining the Custom Component Tag in a Tag Library Descriptor............................... 15-21 15.8 15.9 Using a Custom Component ................................................................................................ 15-22 15.10 Creating and Using a Custom Converter ........................................................................... 15-23 15.10.1 Creating a Custom Converter ....................................................................................... 15-24 Using a Custom Converter............................................................................................ 15-26 15.10.2 15.11 Creating and Using a Custom Validator ............................................................................ 15-27 Implementing the Validator Interface ......................................................................... 15-28 15.11.1 Specifying a Custom Tag ............................................................................................... 15-29 15.11.2 15.11.3 Using a Custom Validator ............................................................................................. 15-30 15.12 Binding Component Values and Instances to Managed Bean Properties ..................... 15-31 Binding a Component Value to a Property................................................................. 15-32 15.12.1 Binding a Component Value to an Implicit Object.................................................... 15-33 15.12.2 15.12.3 Binding a Component Instance to a Bean Property................................................... 15-34 15.13 Binding Converters, Listeners, and Validators to Managed Bean Properties .............. 15-35 16 Configuring JavaServer Faces Applications 16.1 Using Annotations to Configure Managed Beans .............................................................. 16-1 xi Using Managed Bean Scopes .......................................................................................... 16-2 Application Configuration Resource File............................................................................. 16-3 Configuring Eager Application-Scoped Managed Beans ........................................... 16-4 Ordering of Application Configuration Resource Files .............................................. 16-4 Using Faces Flows.................................................................................................................... 16-5 Packaging Flows in an Application ............................................................................... 16-6 The Simplest Possible Flow: The simple-flow Example Application ....................... 16-7 16.1.1 16.2 16.2.1 16.2.2 16.3 16.3.1 16.3.2 16.3.2.1 16.3.3.6 16.3.2.2 16.3.2.3 16.3.3 16.3.3.1 16.3.3.2 16.3.3.3 16.3.3.4 16.3.3.5 To Build, Package, and Deploy the simple-flow Example Using NetBeans IDE........ 16-8 To Build, Package, and Deploy the simple-flow Example Using Maven ......... 16-8 To Run the simple-flow Example............................................................................ 16-9 The checkout-module Example Application ................................................................ 16-9 The Facelets Pages for the checkout-module Example ...................................... 16-10 Using a Configuration File to Configure a Flow................................................. 16-11 Using a Java Class to Configure a Flow ............................................................... 16-12 The Flow-Scoped Managed Beans ........................................................................ 16-13 To Build, Package, and Deploy the checkout-module Example Using NetBeans IDE 16-13 To Build, Package, and Deploy the checkout-module Example Using Maven........... 16-14 To Run the checkout-module Example ................................................................ 16-14 16.3.3.7 Configuring Managed Beans................................................................................................ 16-14 16.4 Using the managed-bean Element ............................................................................... 16-15 16.4.1 Initializing Properties Using the managed-property Element................................. 16-16 16.4.2 Referencing a Java Enum Type.............................................................................. 16-17 16.4.2.1 Referencing a Context Initialization Parameter .................................................. 16-17 16.4.2.2 Initializing Map Properties .................................................................................... 16-18 16.4.2.3 Initializing Array and List Properties................................................................... 16-19 16.4.2.4 Initializing Managed Bean Properties .................................................................. 16-19 16.4.2.5 Initializing Maps and Lists ............................................................................................ 16-21 16.4.3 Registering Application Messages ...................................................................................... 16-21 16.5 Using FacesMessage to Create a Message................................................................... 16-22 16.5.1 16.5.2 Referencing Error Messages.......................................................................................... 16-22 Using Default Validators ...................................................................................................... 16-23 16.6 Registering a Custom Validator........................................................................................... 16-24 16.7 Registering a Custom Converter ......................................................................................... 16-24 16.8 16.9 Configuring Navigation Rules ............................................................................................. 16-25 16.10 Registering a Custom Renderer with a Render Kit........................................................... 16-27 16.11 Registering a Custom Component ...................................................................................... 16-29 16.12 Basic Requirements of a JavaServer Faces Application.................................................... 16-29 Configuring an Application with a Web Deployment Descriptor .......................... 16-30 16.12.1 Identifying the Servlet for Lifecycle Processing.................................................. 16-31 16.12.1.1 To Specify a Path to an Application Configuration Resource File ................... 16-32 16.12.1.2 16.12.1.3 To Specify Where State Is Saved ........................................................................... 16-32 Configuring Project Stage.............................................................................................. 16-33 16.12.2 Including the Classes, Pages, and Other Resources .................................................. 16-33 16.12.3 xii 17 Java Servlet Technology 17.1 What Is a Servlet?..................................................................................................................... 17-1 Servlet Lifecycle........................................................................................................................ 17-2 17.2 Handling Servlet Lifecycle Events ................................................................................. 17-2 17.2.1 Defining the Listener Class ...................................................................................... 17-2 17.2.1.1 Handling Servlet Errors ................................................................................................... 17-3 17.2.2 Sharing Information ................................................................................................................ 17-3 17.3 Using Scope Objects ......................................................................................................... 17-4 17.3.1 Controlling Concurrent Access to Shared Resources.................................................. 17-4 17.3.2 17.4 Creating and Initializing a Servlet......................................................................................... 17-4 17.5 Writing Service Methods ........................................................................................................ 17-5 Getting Information from Requests ............................................................................... 17-5 17.5.1 Constructing Responses................................................................................................... 17-6 17.5.2 Filtering Requests and Responses ......................................................................................... 17-7 17.6 Programming Filters ........................................................................................................ 17-7 17.6.1 Programming Customized Requests and Responses.................................................. 17-8 17.6.2 Specifying Filter Mappings ............................................................................................. 17-9 17.6.3 To Specify Filter Mappings Using NetBeans IDE................................................. 17-9 17.6.3.1 Invoking Other Web Resources ........................................................................................... 17-10 17.7 Including Other Resources in the Response ............................................................... 17-11 17.7.1 Transferring Control to Another Web Component ................................................... 17-11 17.7.2 17.8 Accessing the Web Context .................................................................................................. 17-11 17.9 Maintaining Client State ....................................................................................................... 17-12 Accessing a Session ........................................................................................................ 17-12 17.9.1 Associating Objects with a Session .............................................................................. 17-12 17.9.2 Session Management...................................................................................................... 17-12 17.9.3 To Set the Timeout Period Using NetBeans IDE................................................. 17-13 17.9.3.1 17.9.4 Session Tracking ............................................................................................................. 17-13 17.10 Finalizing a Servlet ................................................................................................................ 17-13 Tracking Service Requests ............................................................................................. 17-14 17.10.1 Notifying Methods to Shut Down................................................................................ 17-14 17.10.2 17.10.3 Creating Polite Long-Running Methods ..................................................................... 17-15 17.11 Uploading Files with Java Servlet Technology.................................................................. 17-15 The @MultipartConfig Annotation .............................................................................. 17-15 17.11.1 17.11.2 The getParts and getPart Methods ............................................................................... 17-16 17.12 Asynchronous Processing..................................................................................................... 17-16 Asynchronous Processing in Servlets .......................................................................... 17-17 17.12.1 17.12.2 Waiting for a Resource................................................................................................... 17-18 17.13 Nonblocking I/O ................................................................................................................... 17-19 17.13.1 Reading a Large HTTP POST Request Using Nonblocking I/O............................. 17-21 17.14 Protocol Upgrade Processing ............................................................................................... 17-21 17.15 The mood Example Application.......................................................................................... 17-23 Components of the mood Example Application........................................................ 17-23 17.15.1 Running the mood Example ......................................................................................... 17-24 17.15.2 To Run the mood Example Using NetBeans IDE ............................................... 17-24 17.15.2.1 17.15.2.2 To Run the mood Example Using Maven............................................................ 17-24 17.16 The fileupload Example Application .................................................................................. 17-25 xiii 17.16.1 17.16.2 17.16.2.1 Architecture of the fileupload Example Application ................................................ 17-25 Running the fileupload Example.................................................................................. 17-27 To Build, Package, and Deploy the fileupload Example Using NetBeans IDE........... 17-27 To Build, Package, and Deploy the fileupload Example Using Maven .......... 17-28 17.16.2.2 17.16.2.3 To Run the fileupload Example............................................................................. 17-28 17.17 The dukeetf Example Application....................................................................................... 17-28 Architecture of the dukeetf Example Application ..................................................... 17-28 17.17.1 The Servlet ................................................................................................................ 17-29 17.17.1.1 The Enterprise Bean ................................................................................................ 17-30 17.17.1.2 17.17.1.3 The HTML Page....................................................................................................... 17-31 Running the dukeetf Example Application ................................................................ 17-31 17.17.2 To Run the dukeetf Example Application Using NetBeans IDE ...................... 17-31 17.17.2.1 17.17.2.2 To Run the dukeetf Example Application Using Maven................................... 17-32 17.18 Further Information about Java Servlet Technology ........................................................ 17-32 18 Java API for WebSocket Introduction to WebSocket ..................................................................................................... 18-1 18.1 Creating WebSocket Applications in the Java EE Platform............................................... 18-2 18.2 Programmatic Endpoints ........................................................................................................ 18-3 18.3 Annotated Endpoints .............................................................................................................. 18-4 18.4 Sending and Receiving Messages.......................................................................................... 18-5 18.5 Sending Messages............................................................................................................. 18-5 18.5.1 Sending Messages to All Peers Connected to an Endpoint................................. 18-6 18.5.1.1 18.5.2 Receiving Messages .......................................................................................................... 18-6 18.6 Maintaining Client State ......................................................................................................... 18-6 Using Encoders and Decoders ............................................................................................... 18-7 18.7 Implementing Encoders to Convert Java Objects into WebSocket Messages.......... 18-7 18.7.1 Implementing Decoders to Convert WebSocket Messages into Java Objects ......... 18-8 18.7.2 Path Parameters ....................................................................................................................... 18-9 18.8 18.9 Handling Errors ..................................................................................................................... 18-10 18.10 Specifying an Endpoint Configurator Class ...................................................................... 18-10 18.11 The dukeetf2 Example Application..................................................................................... 18-11 Architecture of the dukeetf2 Sample Application ..................................................... 18-11 18.11.1 The Endpoint............................................................................................................ 18-12 18.11.1.1 The Enterprise Bean ................................................................................................ 18-12 18.11.1.2 The HTML Page....................................................................................................... 18-13 18.11.1.3 Running the dukeetf2 Example Application .............................................................. 18-14 18.11.2 To Run the dukeetf2 Example Application Using NetBeans IDE .................... 18-14 18.11.2.1 18.11.2.2 To Run the dukeetf2 Example Application Using Maven................................. 18-14 18.12 The websocketbot Example Application ............................................................................ 18-14 Architecture of the websocketbot Example Application .......................................... 18-15 18.12.1 The CDI Bean ........................................................................................................... 18-15 18.12.1.1 The WebSocket Endpoint ....................................................................................... 18-15 18.12.1.2 The Application Messages ..................................................................................... 18-17 18.12.1.3 The Encoder Classes................................................................................................ 18-17 18.12.1.4 18.12.1.5 The Message Decoder ............................................................................................. 18-18 xiv The HTML Page....................................................................................................... 18-18 18.12.1.6 Running the websocketbot Example Application ..................................................... 18-19 18.12.2 To Run the websocketbot Example Application Using NetBeans IDE ........... 18-19 18.12.2.1 To Run the websocketbot Example Application Using Maven........................ 18-19 18.12.2.2 To Test the websocketbot Example Application................................................. 18-19 18.12.2.3 18.13 Further Information about WebSocket ............................................................................... 18-20 19 JSON Processing 19.1 19.1.1 19.1.2 19.1.3 19.2 19.3 19.3.1 19.3.2 19.3.3 19.3.4 19.4 19.4.1 19.4.2 19.5 19.6 19.6.1 19.6.2 19.6.2.1 19.6.2.2 19.7 19.7.1 19.7.2 19.7.2.1 19.7.2.2 19.8 Introduction to JSON............................................................................................................... 19-1 JSON Syntax ...................................................................................................................... 19-1 Uses of JSON ..................................................................................................................... 19-2 Generating and Parsing JSON Data ............................................................................... 19-2 JSON Processing in the Java EE Platform............................................................................. 19-3 Using the Object Model API................................................................................................... 19-4 Creating an Object Model from JSON Data.................................................................. 19-4 Creating an Object Model from Application Code...................................................... 19-4 Navigating an Object Model ........................................................................................... 19-5 Writing an Object Model to a Stream ............................................................................ 19-6 Using the Streaming API ........................................................................................................ 19-7 Reading JSON Data Using a Parser................................................................................ 19-7 Writing JSON Data Using a Generator.......................................................................... 19-8 JSON in Java EE RESTful Web Services ............................................................................... 19-9 The jsonpmodel Example Application ................................................................................. 19-9 Components of the jsonpmodel Example Application ............................................... 19-9 Running the jsonpmodel Example Application ......................................................... 19-10 To Run the jsonpmodel Example Application Using NetBeans IDE............... 19-10 To Run the jsonpmodel Example Application Using Maven ........................... 19-10 The jsonpstreaming Example Application ......................................................................... 19-10 Components of the jsonpstreaming Example Application....................................... 19-11 Running the jsonpstreaming Example Application .................................................. 19-11 To Run the jsonpstreaming Example Application Using NetBeans IDE ........ 19-11 To Run the jsonpstreaming Example Application Using Maven..................... 19-11 Further Information about the Java API for JSON Processing........................................ 19-12 20 Internationalizing and Localizing Web Applications 20.1 20.2 20.2.1 20.2.2 20.2.3 20.3 20.4 20.4.1 20.4.2 Java Platform Localization Classes........................................................................................ 20-1 Providing Localized Messages and Labels .......................................................................... 20-2 Establishing the Locale..................................................................................................... 20-2 Setting the Resource Bundle............................................................................................ 20-3 Retrieving Localized Messages....................................................................................... 20-3 Date and Number Formatting................................................................................................ 20-4 Character Sets and Encodings................................................................................................ 20-4 Character Sets .................................................................................................................... 20-4 Character Encoding .......................................................................................................... 20-5 Part IV Bean Validation xv 21 Introduction to Bean Validation 21.1 21.2 21.3 21.3.1 21.3.2 21.3.3 21.4 Using Bean Validation Constraints ....................................................................................... 21-1 Validating Null and Empty Strings....................................................................................... 21-4 Validating Constructors and Methods ................................................................................. 21-5 Cross-Parameter Constraints .......................................................................................... 21-5 Identifying Parameter Constraint Violations ............................................................... 21-6 Adding Constraints to Method Return Values ............................................................ 21-6 Further Information about Bean Validation ........................................................................ 21-6 22 Bean Validation: Advanced Topics 22.1 22.1.1 22.1.2 22.2 22.2.1 22.2.1.1 22.3 22.3.1 22.4 22.4.1 Creating Custom Constraints................................................................................................. 22-1 Using the Built-In Constraints to Make a New Constraint......................................... 22-1 Removing Ambiguity in Constraint Targets ................................................................ 22-2 Customizing Validator Messages .......................................................................................... 22-2 The ValidationMessages Resource Bundle ................................................................... 22-2 Localizing Validation Messages .............................................................................. 22-3 Grouping Constraints............................................................................................................. 22-3 Customizing Group Validation Order .......................................................................... 22-3 Using Method Constraints in Type Hierarchies.................................................................. 22-4 Rules for Using Method Constraints in Type Hierarchies ......................................... 22-5 Part V Contexts and Dependency Injection for Java EE 23 Introduction to Contexts and Dependency Injection for Java EE Getting Started.......................................................................................................................... 23-2 23.1 Overview of CDI ...................................................................................................................... 23-3 23.2 About Beans.............................................................................................................................. 23-4 23.3 About CDI Managed Beans.................................................................................................... 23-4 23.4 Beans as Injectable Objects...................................................................................................... 23-5 23.5 Using Qualifiers ....................................................................................................................... 23-5 23.6 Injecting Beans.......................................................................................................................... 23-6 23.7 Using Scopes............................................................................................................................. 23-7 23.8 23.9 Giving Beans EL Names.......................................................................................................... 23-8 23.10 Adding Setter and Getter Methods ....................................................................................... 23-9 23.11 Using a Managed Bean in a Facelets Page............................................................................ 23-9 23.12 Injecting Objects by Using Producer Methods .................................................................. 23-10 23.13 Configuring a CDI Application ........................................................................................... 23-10 23.14 Using the @PostConstruct and @PreDestroy Annotations with CDI Managed Bean Classes 23-11 23.14.1 23.14.2 To Initialize a Managed Bean Using the @PostConstruct Annotation ................... 23-11 To Prepare for the Destruction of a Managed Bean Using the @PreDestroy Annotation 23-11 23.15 Further Information about CDI ........................................................................................... 23-12 24 Running the Basic Contexts and Dependency Injection Examples 24.1 The simplegreeting CDI Example ......................................................................................... 24-1 xvi 24.1.1 24.1.2 24.1.3 24.1.3.1 24.1.3.2 24.1.3.3 24.2 24.2.1 24.2.1.1 24.2.1.2 24.2.1.3 24.2.2 24.2.3 24.2.3.1 24.2.3.2 24.2.3.3 The simplegreeting Source Files ..................................................................................... 24-1 The Facelets Template and Page..................................................................................... 24-2 Running the simplegreeting Example ........................................................................... 24-3 To Build, Package, and Run the simplegreeting Example Using NetBeans IDE ........ 24-3 To Build, Package, and Deploy the simplegreeting Example Using Maven .... 24-4 To Run the simplegreeting Example ...................................................................... 24-4 The guessnumber-cdi CDI Example ..................................................................................... 24-4 The guessnumber-cdi Source Files................................................................................. 24-4 The @MaxNumber and @Random Qualifier Interfaces....................................... 24-5 The Generator Managed Bean ................................................................................. 24-5 The UserNumberBean Managed Bean ................................................................... 24-6 The Facelets Page .............................................................................................................. 24-8 Running the guessnumber-cdi Example ....................................................................... 24-9 To Build, Package, and Deploy the guessnumber-cdi Example Using NetBeans IDE 24-9 To Build, Package, and Deploy the guessnumber-cdi Example Using Maven ........... 24-10 To Run the guessnumber Example ....................................................................... 24-10 25 Contexts and Dependency Injection for Java EE: Advanced Topics 25.1 25.2 25.2.1 25.3 25.3.1 25.3.2 25.3.3 25.4 25.5 25.5.1 25.5.2 25.5.3 25.6 25.7 25.8 Packaging CDI Applications .................................................................................................. 25-1 Using Alternatives in CDI Applications............................................................................... 25-2 Using Specialization ......................................................................................................... 25-3 Using Producer Methods, Producer Fields, and Disposer Methods in CDI Applications ...... 25-4 Using Producer Methods................................................................................................. 25-4 Using Producer Fields to Generate Resources ............................................................. 25-5 Using a Disposer Method ................................................................................................ 25-5 Using Predefined Beans in CDI Applications...................................................................... 25-5 Using Events in CDI Applications......................................................................................... 25-7 Defining Events................................................................................................................. 25-7 Using Observer Methods to Handle Events ................................................................. 25-7 Firing Events...................................................................................................................... 25-8 Using Interceptors in CDI Applications ............................................................................... 25-9 Using Decorators in CDI Applications ............................................................................... 25-10 Using Stereotypes in CDI Applications .............................................................................. 25-12 26 Running the Advanced Contexts and Dependency Injection Examples 26.1 26.1.1 26.1.2 26.1.3 26.1.3.1 26.1.3.2 26.1.3.3 26.1.3.4 The encoder Example: Using Alternatives........................................................................... 26-1 The Coder Interface and Implementations ................................................................... 26-1 The encoder Facelets Page and Managed Bean............................................................ 26-2 Running the encoder Example........................................................................................ 26-3 To Build, Package, and Deploy the encoder Example Using NetBeans IDE .... 26-4 To Run the encoder Example Using NetBeans IDE ............................................. 26-4 To Build, Package, and Deploy the encoder Example Using Maven ................ 26-4 To Run the encoder Example Using Maven .......................................................... 26-5 xvii 26.2 The producermethods Example: Using a Producer Method to Choose a Bean Implementation 26-5 26.2.1 26.2.2 26.2.2.1 26.2.2.2 26.2.2.3 26.3 26.3.1 26.3.2 26.3.3 26.3.4 26.3.4.1 26.3.4.2 26.3.4.3 26.4 26.4.1 26.4.2 26.4.3 26.4.4 26.4.5 26.4.5.1 26.4.5.2 26.4.5.3 26.5 26.5.1 26.5.2 26.5.2.1 26.5.2.2 26.5.2.3 Components of the producermethods Example .......................................................... 26-6 Running the producermethods Example ...................................................................... 26-7 To Build, Package, and Deploy the producermethods Example Using NetBeans IDE 26-7 To Build, Package, and Deploy the producermethods Example Using Maven 26-7 To Run the producermethods Example ................................................................. 26-7 The producerfields Example: Using Producer Fields to Generate Resources ................ 26-8 The Producer Field for the producerfields Example ................................................... 26-8 The producerfields Entity and Session Bean ................................................................ 26-9 The producerfields Facelets Pages and Managed Bean ............................................ 26-10 Running the producerfields Example.......................................................................... 26-12 To Build, Package, and Deploy the producerfields Example Using NetBeans IDE ... 26-12 To Build, Package, and Deploy the producerfields Example Using Maven... 26-13 To Run the producerfields Example ..................................................................... 26-13 The billpayment Example: Using Events and Interceptors ............................................. 26-13 The PaymentEvent Event Class .................................................................................... 26-13 The PaymentHandler Event Listener .......................................................................... 26-14 The billpayment Facelets Pages and Managed Bean................................................. 26-15 The LoggedInterceptor Interceptor Class ................................................................... 26-17 Running the billpayment Example .............................................................................. 26-18 To Build, Package, and Deploy the billpayment Example Using NetBeans IDE........ 26-18 To Build, Package, and Deploy the billpayment Example Using Maven ....... 26-18 To Run the billpayment Example.......................................................................... 26-18 The decorators Example: Decorating a Bean ..................................................................... 26-19 Components of the decorators Example ..................................................................... 26-19 Running the decorators Example ................................................................................. 26-20 To Build, Package, and Deploy the decorators Example Using NetBeans IDE .......... 26-20 To Build, Package, and Deploy the decorators Example Using Maven .......... 26-20 To Run the decorators Example ............................................................................ 26-21 Part VI Web Services 27 Introduction to Web Services 27.1 What Are Web Services? ......................................................................................................... 27-1 Types of Web Services............................................................................................................. 27-1 27.2 "Big" Web Services ............................................................................................................ 27-1 27.2.1 RESTful Web Services ...................................................................................................... 27-2 27.2.2 Deciding Which Type of Web Service to Use ...................................................................... 27-3 27.3 28 Building Web Services with JAX-WS 28.1 28.1.1 Creating a Simple Web Service and Clients with JAX-WS ................................................ 28-2 Requirements of a JAX-WS Endpoint ............................................................................ 28-2 xviii Coding the Service Endpoint Implementation Class .................................................. 28-3 28.1.2 Building, Packaging, and Deploying the Service......................................................... 28-3 28.1.3 To Build, Package, and Deploy the Service Using NetBeans IDE...................... 28-4 28.1.3.1 To Build, Package, and Deploy the Service Using Maven .................................. 28-4 28.1.3.2 Testing the Methods of a Web Service Endpoint ......................................................... 28-4 28.1.4 To Test the Service without a Client ....................................................................... 28-4 28.1.4.1 A Simple JAX-WS Application Client............................................................................ 28-5 28.1.5 Coding the Application Client................................................................................. 28-5 28.1.5.1 Running the Application Client .............................................................................. 28-6 28.1.5.2 A Simple JAX-WS Web Client ........................................................................................ 28-6 28.1.6 Coding the Servlet ..................................................................................................... 28-6 28.1.6.1 Running the Web Client ........................................................................................... 28-8 28.1.6.2 Types Supported by JAX-WS ................................................................................................. 28-9 28.2 Schema-to-Java Mapping................................................................................................. 28-9 28.2.1 28.2.2 Java-to-Schema Mapping................................................................................................. 28-9 28.3 Web Services Interoperability and JAX-WS....................................................................... 28-10 Further Information about JAX-WS .................................................................................... 28-10 28.4 29 Building RESTful Web Services with JAX-RS 29.1 What Are RESTful Web Services? ......................................................................................... 29-1 Creating a RESTful Root Resource Class.............................................................................. 29-2 29.2 Developing RESTful Web Services with JAX-RS ......................................................... 29-2 29.2.1 Overview of a JAX-RS Application ................................................................................ 29-4 29.2.2 The @Path Annotation and URI Path Templates ......................................................... 29-5 29.2.3 Responding to HTTP Methods and Requests .............................................................. 29-6 29.2.4 The Request Method Designator Annotations...................................................... 29-7 29.2.4.1 Using Entity Providers to Map HTTP Response and Request Entity Bodies... 29-8 29.2.4.2 Using @Consumes and @Produces to Customize Requests and Responses ........... 29-9 29.2.5 The @Produces Annotation...................................................................................... 29-9 29.2.5.1 The @Consumes Annotation.................................................................................. 29-10 29.2.5.2 Extracting Request Parameters ..................................................................................... 29-11 29.2.6 Configuring JAX-RS Applications................................................................................ 29-14 29.2.7 Configuring a JAX-RS Application Using a Subclass of Application .............. 29-14 29.2.7.1 Configuring the Base URI in web.xml.................................................................. 29-15 29.2.7.2 Example Applications for JAX-RS ....................................................................................... 29-15 29.3 Creating a Simple RESTful Web Service ..................................................................... 29-15 29.3.1 To Create a RESTful Web Service Using NetBeans IDE .................................... 29-15 29.3.1.1 The rsvp Example Application ..................................................................................... 29-16 29.3.2 Components of the rsvp Example Application................................................... 29-16 29.3.2.1 Running the rsvp Example Application............................................................... 29-17 29.3.2.2 Real-World Examples..................................................................................................... 29-18 29.3.3 Further Information about JAX-RS...................................................................................... 29-19 29.4 30 Accessing REST Resources with the JAX-RS Client API 30.1 30.1.1 Overview of the Client API .................................................................................................... 30-1 Creating a Basic Client Request Using the Client API ................................................ 30-1 xix 30.1.1.1 30.1.1.2 30.1.1.3 30.1.1.4 30.2 30.2.1 30.2.2 30.3 30.3.1 30.3.1.1 30.3.1.2 30.3.1.3 30.3.2 30.3.2.1 Obtaining the Client Instance .................................................................................. 30-2 Setting the Client Target ........................................................................................... 30-2 Setting Path Parameters in Targets ......................................................................... 30-2 Invoking the Request ................................................................................................ 30-3 Using the Client API in the JAX-RS Example Applications .............................................. 30-4 The Client API in the rsvp Example Application ........................................................ 30-4 The Client API in the customer Example Application ................................................ 30-5 Advanced Features of the Client API ................................................................................... 30-6 Configuring the Client Request ...................................................................................... 30-6 Setting Message Headers in the Client Request.................................................... 30-6 Setting Cookies in the Client Request..................................................................... 30-7 Adding Filters to the Client...................................................................................... 30-7 Asynchronous Invocations in the Client API ............................................................... 30-8 Using Custom Callbacks in Asynchronous Invocations...................................... 30-9 31 JAX-RS: Advanced Topics and an Example 31.1 31.1.1 31.1.2 31.1.3 31.1.4 31.2 31.2.1 31.2.2 31.2.3 31.3 31.3.1 31.3.2 31.4 31.5 31.6 31.7 31.7.1 31.7.2 31.7.3 31.8 31.8.1 31.8.2 31.8.3 31.8.4 31.8.5 31.8.5.1 31.8.5.2 Annotations for Field and Bean Properties of Resource Classes ...................................... 31-1 Extracting Path Parameters ............................................................................................. 31-2 Extracting Query Parameters.......................................................................................... 31-2 Extracting Form Data ....................................................................................................... 31-3 Extracting the Java Type of a Request or Response..................................................... 31-3 Validating Resource Data with Bean Validation................................................................. 31-4 Using Constraint Annotations on Resource Methods................................................. 31-4 Validating Entity Data ..................................................................................................... 31-5 Validation Exception Handling and Response Codes ................................................ 31-6 Subresources and Runtime Resource Resolution................................................................ 31-6 Subresource Methods....................................................................................................... 31-7 Subresource Locators ....................................................................................................... 31-7 Integrating JAX-RS with EJB Technology and CDI ............................................................ 31-8 Conditional HTTP Requests................................................................................................... 31-9 Runtime Content Negotiation................................................................................................ 31-9 Using JAX-RS with JAXB ...................................................................................................... 31-11 Using Java Objects to Model Your Data ...................................................................... 31-12 Starting from an Existing XML Schema Definition ................................................... 31-14 Using JSON with JAX-RS and JAXB ............................................................................ 31-15 The customer Example Application.................................................................................... 31-16 Overview of the customer Example Application....................................................... 31-16 The Customer and Address Entity Classes................................................................. 31-17 The CustomerService Class ........................................................................................... 31-19 Using the JAX-RS Client in the CustomerBean Classes ............................................ 31-20 Running the customer Example ................................................................................... 31-21 To Build, Package, and Deploy the customer Example Using NetBeans IDE 31-22 To Build, Package, and Deploy the customer Example Using Maven ............ 31-22 Part VII Enterprise Beans xx 32 Enterprise Beans 32.1 What Is an Enterprise Bean?................................................................................................... 32-1 Benefits of Enterprise Beans ............................................................................................ 32-1 32.1.1 32.1.2 When to Use Enterprise Beans........................................................................................ 32-2 Types of Enterprise Beans ............................................................................................... 32-2 32.1.3 32.2 What Is a Session Bean? .......................................................................................................... 32-2 Types of Session Beans..................................................................................................... 32-2 32.2.1 Stateful Session Beans ............................................................................................... 32-2 32.2.1.1 Stateless Session Beans ............................................................................................. 32-3 32.2.1.2 Singleton Session Beans............................................................................................ 32-3 32.2.1.3 32.2.2 When to Use Session Beans ............................................................................................. 32-3 32.3 What Is a Message-Driven Bean? .......................................................................................... 32-4 What Makes Message-Driven Beans Different from Session Beans?........................ 32-4 32.3.1 When to Use Message-Driven Beans ............................................................................. 32-5 32.3.2 Accessing Enterprise Beans .................................................................................................... 32-5 32.4 Using Enterprise Beans in Clients .................................................................................. 32-6 32.4.1 Portable JNDI Syntax ................................................................................................ 32-6 32.4.1.1 Deciding on Remote or Local Access............................................................................. 32-7 32.4.2 Local Clients ...................................................................................................................... 32-7 32.4.3 Accessing Local Enterprise Beans Using the No-Interface View ....................... 32-8 32.4.3.1 Accessing Local Enterprise Beans That Implement Business Interfaces ........... 32-8 32.4.3.2 Remote Clients .................................................................................................................. 32-9 32.4.4 Web Service Clients ........................................................................................................ 32-10 32.4.5 Method Parameters and Access.................................................................................... 32-10 32.4.6 Isolation..................................................................................................................... 32-10 32.4.6.1 Granularity of Accessed Data ................................................................................ 32-10 32.4.6.2 The Contents of an Enterprise Bean .................................................................................... 32-10 32.5 Naming Conventions for Enterprise Beans........................................................................ 32-11 32.6 The Lifecycles of Enterprise Beans ...................................................................................... 32-11 32.7 The Lifecycle of a Stateful Session Bean ...................................................................... 32-11 32.7.1 The Lifecycle of a Stateless Session Bean .................................................................... 32-12 32.7.2 The Lifecycle of a Singleton Session Bean................................................................... 32-13 32.7.3 32.7.4 The Lifecycle of a Message-Driven Bean..................................................................... 32-13 Further Information about Enterprise Beans ..................................................................... 32-13 32.8 33 Getting Started with Enterprise Beans Creating the Enterprise Bean.................................................................................................. 33-1 33.1 Coding the Enterprise Bean Class .................................................................................. 33-1 33.1.1 Creating the converter Web Client................................................................................. 33-2 33.1.2 Running the converter Example..................................................................................... 33-3 33.1.3 To Run the converter Example Using NetBeans IDE........................................... 33-3 33.1.3.1 33.1.3.2 To Run the converter Example Using Maven ....................................................... 33-3 33.2 Modifying the Java EE Application....................................................................................... 33-4 To Modify a Class File...................................................................................................... 33-4 33.2.1 xxi 34 Running the Enterprise Bean Examples 34.1 34.1.1 34.1.2 34.1.2.1 34.1.2.2 34.1.3 34.1.4 34.1.5 34.1.5.1 34.1.5.2 34.2 34.2.1 34.2.1.1 34.2.1.2 34.2.1.3 34.2.2 34.2.3 34.2.3.1 34.2.3.2 34.3 34.3.1 34.3.2 34.3.3 34.3.3.1 34.3.3.2 34.3.3.3 34.4 34.4.1 34.4.1.1 34.4.2 34.4.2.1 34.4.2.2 34.4.3 34.4.4 34.4.5 34.4.6 34.4.7 34.4.8 34.4.8.1 34.4.8.2 34.4.8.3 34.5 The cart Example...................................................................................................................... 34-1 The Business Interface...................................................................................................... 34-2 Session Bean Class ............................................................................................................ 34-2 Lifecycle Callback Methods ..................................................................................... 34-4 Business Methods ...................................................................................................... 34-4 The @Remove Method ..................................................................................................... 34-5 Helper Classes ................................................................................................................... 34-5 Running the cart Example ............................................................................................... 34-6 To Run the cart Example Using NetBeans IDE ..................................................... 34-6 To Run the cart Example Using Maven ................................................................. 34-6 A Singleton Session Bean Example: counter........................................................................ 34-7 Creating a Singleton Session Bean ................................................................................. 34-7 Initializing Singleton Session Beans........................................................................ 34-7 Managing Concurrent Access in a Singleton Session Bean................................. 34-8 Handling Errors in a Singleton Session Bean ...................................................... 34-11 The Architecture of the counter Example ................................................................... 34-11 Running the counter Example ...................................................................................... 34-13 To Run the counter Example Using NetBeans IDE ............................................ 34-13 To Run the counter Example Using Maven......................................................... 34-13 A Web Service Example: helloservice ................................................................................. 34-13 The Web Service Endpoint Implementation Class .................................................... 34-14 Stateless Session Bean Implementation Class............................................................. 34-14 Running the helloservice Example............................................................................... 34-15 To Build, Package, and Deploy the helloservice Example Using NetBeans IDE ........ 34-15 To Build, Package, and Deploy the helloservice Example Using Maven........ 34-15 To Test the Service without a Client ..................................................................... 34-15 Using the Timer Service ........................................................................................................ 34-16 Creating Calendar-Based Timer Expressions ............................................................. 34-16 Specifying Multiple Values in Calendar Expressions ........................................ 34-17 Programmatic Timers..................................................................................................... 34-18 The @Timeout Method ........................................................................................... 34-18 Creating Programmatic Timers ............................................................................. 34-19 Automatic Timers ........................................................................................................... 34-20 Canceling and Saving Timers ....................................................................................... 34-20 Getting Timer Information ............................................................................................ 34-21 Transactions and Timers................................................................................................ 34-21 The timersession Example............................................................................................. 34-21 Running the timersession Example.............................................................................. 34-23 To Run the timersession Example Using NetBeans IDE ................................... 34-24 To Build, Package, and Deploy the timersession Example Using Maven ...... 34-24 To Run the Web Client............................................................................................ 34-24 Handling Exceptions ............................................................................................................. 34-24 35 Using the Embedded Enterprise Bean Container 35.1 Overview of the Embedded Enterprise Bean Container.................................................... 35-1 xxii 35.2 35.2.1 35.2.2 35.2.2.1 35.2.3 35.2.4 35.3 35.3.1 35.3.2 Developing Embeddable Enterprise Bean Applications.................................................... 35-1 Running Embedded Applications.................................................................................. 35-2 Creating the Enterprise Bean Container........................................................................ 35-2 Explicitly Specifying Enterprise Bean Modules to Be Initialized ....................... 35-3 Looking Up Session Bean References ............................................................................ 35-3 Shutting Down the Enterprise Bean Container ............................................................ 35-3 The standalone Example Application................................................................................... 35-4 To Run the standalone Example Application Using NetBeans IDE ......................... 35-5 To Run the standalone Example Application Using Maven ...................................... 35-5 36 Using Asynchronous Method Invocation in Session Beans 36.1 36.1.1 36.1.2 36.1.2.1 36.1.2.2 36.1.2.3 36.2 36.2.1 36.2.2 36.2.2.1 36.2.2.2 Asynchronous Method Invocation........................................................................................ 36-1 Creating an Asynchronous Business Method .............................................................. 36-1 Calling Asynchronous Methods from Enterprise Bean Clients................................. 36-2 Retrieving the Final Result from an Asynchronous Method Invocation .......... 36-2 Cancelling an Asynchronous Method Invocation ................................................ 36-3 Checking the Status of an Asynchronous Method Invocation ........................... 36-3 The async Example Application ............................................................................................ 36-3 Architecture of the async-war Module.......................................................................... 36-3 Running the async Example............................................................................................ 36-4 To Run the async Example Application Using NetBeans IDE............................ 36-5 To Run the async Example Application Using Maven ........................................ 36-5 Part VIII Persistence 37 Introduction to the Java Persistence API 37.1 37.1.1 37.1.2 37.1.2.1 37.1.2.2 37.1.2.3 37.1.2.4 37.1.3 37.1.4 37.1.5 37.1.5.1 37.1.5.2 37.1.5.3 37.1.5.4 37.1.5.5 37.1.6 37.2 37.2.1 37.2.2 37.2.3 Entities ....................................................................................................................................... 37-1 Requirements for Entity Classes..................................................................................... 37-1 Persistent Fields and Properties in Entity Classes ....................................................... 37-2 Persistent Fields ......................................................................................................... 37-2 Persistent Properties.................................................................................................. 37-3 Using Collections in Entity Fields and Properties ................................................ 37-3 Validating Persistent Fields and Properties........................................................... 37-4 Primary Keys in Entities .................................................................................................. 37-6 Multiplicity in Entity Relationships ............................................................................... 37-7 Direction in Entity Relationships ................................................................................... 37-8 Bidirectional Relationships ...................................................................................... 37-8 Unidirectional Relationships ................................................................................... 37-8 Queries and Relationship Direction........................................................................ 37-9 Cascade Operations and Relationships.................................................................. 37-9 Orphan Removal in Relationships .......................................................................... 37-9 Embeddable Classes in Entities .................................................................................... 37-10 Entity Inheritance................................................................................................................... 37-11 Abstract Entities .............................................................................................................. 37-11 Mapped Superclasses ..................................................................................................... 37-11 Non-Entity Superclasses ................................................................................................ 37-12 xxiii Entity Inheritance Mapping Strategies ........................................................................ 37-12 37.2.4 The Single Table per Class Hierarchy Strategy ................................................... 37-12 37.2.4.1 The Table per Concrete Class Strategy................................................................. 37-13 37.2.4.2 37.2.4.3 The Joined Subclass Strategy ................................................................................. 37-14 37.3 Managing Entities .................................................................................................................. 37-14 The EntityManager Interface ........................................................................................ 37-14 37.3.1 Container-Managed Entity Managers .................................................................. 37-14 37.3.1.1 Application-Managed Entity Managers............................................................... 37-15 37.3.1.2 Finding Entities Using the EntityManager .......................................................... 37-16 37.3.1.3 Managing an Entity Instance's Lifecycle .............................................................. 37-16 37.3.1.4 Persisting Entity Instances ..................................................................................... 37-16 37.3.1.5 Removing Entity Instances..................................................................................... 37-17 37.3.1.6 37.3.1.7 Synchronizing Entity Data to the Database ......................................................... 37-17 Persistence Units ............................................................................................................. 37-17 37.3.2 Querying Entities ................................................................................................................... 37-18 37.4 Database Schema Creation ................................................................................................... 37-19 37.5 Configuring an Application to Create or Drop Database Tables ............................ 37-20 37.5.1 Loading Data Using SQL Scripts.................................................................................. 37-21 37.5.2 Further Information about Persistence ............................................................................... 37-21 37.6 38 Running the Persistence Examples 38.1 38.1.1 38.1.1.1 38.1.1.2 38.1.1.3 38.1.1.4 38.1.2 38.1.2.1 38.1.2.2 38.1.3 38.1.4 38.1.5 38.1.6 38.1.7 38.1.7.1 38.1.7.2 38.1.7.3 38.1.7.4 38.1.7.5 38.1.8 38.1.8.1 38.1.8.2 38.2 38.2.1 38.2.1.1 The order Application ............................................................................................................. 38-1 Entity Relationships in the order Application.............................................................. 38-2 Self-Referential Relationships .................................................................................. 38-2 One-to-One Relationships ........................................................................................ 38-3 One-to-Many Relationship Mapped to Overlapping Primary and Foreign Keys ...... 38-3 Unidirectional Relationships ................................................................................... 38-4 Primary Keys in the order Application ......................................................................... 38-4 Generated Primary Keys .......................................................................................... 38-4 Compound Primary Keys......................................................................................... 38-5 Entity Mapped to More Than One Database Table ..................................................... 38-7 Cascade Operations in the order Application .............................................................. 38-8 BLOB and CLOB Database Types in the order Application ...................................... 38-8 Temporal Types in the order Application..................................................................... 38-9 Managing the order Application's Entities ................................................................... 38-9 Creating Entities ........................................................................................................ 38-9 Finding Entities ........................................................................................................ 38-10 Setting Entity Relationships ................................................................................... 38-10 Using Queries........................................................................................................... 38-10 Removing Entities ................................................................................................... 38-11 Running the order Example .......................................................................................... 38-11 To Run the order Example Using NetBeans IDE ................................................ 38-11 To Run the order Example Using Maven ............................................................ 38-11 The roster Application........................................................................................................... 38-12 Relationships in the roster Application ....................................................................... 38-13 The Many-To-Many Relationship in roster ......................................................... 38-13 xxiv 38.2.2 38.2.3 38.2.3.1 38.2.3.2 38.2.3.3 38.2.4 38.2.5 38.2.5.1 38.2.5.2 38.3 38.3.1 38.3.2 38.3.3 38.3.4 38.3.4.1 38.3.4.2 Entity Inheritance in the roster Application ............................................................... 38-13 Criteria Queries in the roster Application................................................................... 38-15 Metamodel Classes in the roster Application...................................................... 38-15 Obtaining a CriteriaBuilder Instance in RequestBean ....................................... 38-15 Creating Criteria Queries in RequestBean's Business Methods ....................... 38-15 Automatic Table Generation in the roster Application............................................. 38-16 Running the roster Example ......................................................................................... 38-17 To Run the roster Example Using NetBeans IDE ............................................... 38-17 To Run the roster Example Using Maven............................................................ 38-17 The address-book Application............................................................................................. 38-18 Bean Validation Constraints in address-book ............................................................ 38-18 Specifying Error Messages for Constraints in address-book ................................... 38-19 Validating Contact Input from a JavaServer Faces Application.............................. 38-20 Running the address-book Example............................................................................ 38-20 To Run the address-book Example Using NetBeans IDE.................................. 38-20 To Run the address-book Example Using Maven .............................................. 38-21 39 The Java Persistence Query Language 39.1 39.2 39.2.1 39.2.2 39.3 39.3.1 39.3.2 39.4 39.4.1 39.4.1.1 39.4.1.2 39.4.1.3 39.4.2 39.4.2.1 39.4.2.2 39.4.2.3 39.4.2.4 39.4.2.5 39.4.3 39.4.3.1 39.4.3.2 39.4.3.3 39.4.3.4 39.4.3.5 39.4.4 39.4.4.1 39.4.4.2 39.5 39.5.1 Query Language Terminology............................................................................................... 39-1 Creating Queries Using the Java Persistence Query Language ........................................ 39-2 Named Parameters in Queries........................................................................................ 39-2 Positional Parameters in Queries ................................................................................... 39-3 Simplified Query Language Syntax ...................................................................................... 39-3 Select Statements............................................................................................................... 39-3 Update and Delete Statements........................................................................................ 39-4 Example Queries ...................................................................................................................... 39-4 Simple Queries .................................................................................................................. 39-4 A Basic Select Query ................................................................................................. 39-4 Eliminating Duplicate Values .................................................................................. 39-4 Using Named Parameters ........................................................................................ 39-5 Queries That Navigate to Related Entities .................................................................... 39-5 A Simple Query with Relationships ....................................................................... 39-5 Navigating to Single-Valued Relationship Fields................................................. 39-5 Traversing Relationships with an Input Parameter ............................................. 39-5 Traversing Multiple Relationships.......................................................................... 39-6 Navigating According to Related Fields ................................................................ 39-6 Queries with Other Conditional Expressions............................................................... 39-6 The LIKE Expression................................................................................................. 39-6 The IS NULL Expression .......................................................................................... 39-7 The IS EMPTY Expression........................................................................................ 39-7 The BETWEEN Expression ...................................................................................... 39-7 Comparison Operators ............................................................................................. 39-7 Bulk Updates and Deletes ............................................................................................... 39-8 Update Queries .......................................................................................................... 39-8 Delete Queries ............................................................................................................ 39-8 Full Query Language Syntax.................................................................................................. 39-8 BNF Symbols ..................................................................................................................... 39-8 xxv 39.5.2 39.5.3 39.5.3.1 39.5.3.2 39.5.3.3 39.5.3.4 39.5.3.5 39.5.4 39.5.4.1 39.5.4.2 39.5.4.3 39.5.5 39.5.5.1 39.5.5.2 39.5.5.3 39.5.5.4 39.5.5.5 39.5.5.6 39.5.5.7 39.5.5.8 39.5.5.9 39.5.5.10 39.5.5.11 39.5.5.12 39.5.5.13 39.5.5.14 39.5.5.15 39.5.6 39.5.6.1 39.5.6.2 39.5.6.3 39.5.7 39.5.8 BNF Grammar of the Java Persistence Query Language............................................ 39-9 FROM Clause .................................................................................................................. 39-12 Identifiers.................................................................................................................. 39-12 Identification Variables........................................................................................... 39-14 Range Variable Declarations.................................................................................. 39-15 Collection Member Declarations ........................................................................... 39-15 Joins ........................................................................................................................... 39-15 Path Expressions ............................................................................................................. 39-16 Examples of Path Expressions ............................................................................... 39-16 Expression Types ..................................................................................................... 39-17 Navigation ................................................................................................................ 39-17 WHERE Clause ............................................................................................................... 39-17 Literals....................................................................................................................... 39-17 Input Parameters ..................................................................................................... 39-18 Conditional Expressions......................................................................................... 39-18 Operators and Their Precedence ........................................................................... 39-18 BETWEEN Expressions .......................................................................................... 39-19 IN Expressions ......................................................................................................... 39-19 LIKE Expressions..................................................................................................... 39-20 NULL Comparison Expressions............................................................................ 39-20 Empty Collection Comparison Expressions ........................................................ 39-20 Collection Member Expressions ............................................................................ 39-21 Subqueries ................................................................................................................ 39-21 Functional Expressions ........................................................................................... 39-22 Case Expressions ..................................................................................................... 39-23 NULL Values............................................................................................................ 39-24 Equality Semantics .................................................................................................. 39-24 SELECT Clause................................................................................................................ 39-25 Return Types ............................................................................................................ 39-25 The DISTINCT Keyword........................................................................................ 39-26 Constructor Expressions......................................................................................... 39-26 ORDER BY Clause .......................................................................................................... 39-27 GROUP BY and HAVING Clauses .............................................................................. 39-27 40 Using the Criteria API to Create Queries 40.1 40.2 40.2.1 40.3 40.3.1 40.3.2 40.3.3 40.3.4 40.3.5 40.3.5.1 40.3.5.2 40.3.6 Overview of the Criteria and Metamodel APIs................................................................... 40-1 Using the Metamodel API to Model Entity Classes............................................................ 40-2 Using Metamodel Classes ............................................................................................... 40-3 Using the Criteria API and Metamodel API to Create Basic Typesafe Queries ............. 40-4 Creating a Criteria Query ................................................................................................ 40-4 Query Roots ....................................................................................................................... 40-5 Querying Relationships Using Joins .............................................................................. 40-5 Path Navigation in Criteria Queries .............................................................................. 40-6 Restricting Criteria Query Results ................................................................................. 40-6 The Expression Interface Methods.......................................................................... 40-6 Expression Methods in the CriteriaBuilder Interface........................................... 40-7 Managing Criteria Query Results................................................................................... 40-8 xxvi 40.3.6.1 40.3.6.2 40.3.7 40.3.7.1 40.3.7.2 Ordering Results........................................................................................................ 40-8 Grouping Results....................................................................................................... 40-9 Executing Queries............................................................................................................. 40-9 Single-Valued Query Results................................................................................... 40-9 Collection-Valued Query Results............................................................................ 40-9 41 Creating and Using String-Based Criteria Queries 41.1 41.2 41.3 Overview of String-Based Criteria API Queries.................................................................. 41-1 Creating String-Based Queries............................................................................................... 41-1 Executing String-Based Queries ............................................................................................ 41-2 42 Controlling Concurrent Access to Entity Data with Locking 42.1 42.1.1 42.2 42.2.1 42.2.2 42.2.2.1 Overview of Entity Locking and Concurrency.................................................................... 42-1 Using Optimistic Locking................................................................................................ 42-2 Lock Modes............................................................................................................................... 42-2 Setting the Lock Mode ..................................................................................................... 42-3 Using Pessimistic Locking............................................................................................... 42-4 Pessimistic Locking Timeouts.................................................................................. 42-4 43 Creating Fetch Plans with Entity Graphs 43.1 43.1.1 43.1.2 43.1.2.1 43.1.2.2 43.2 43.2.1 43.2.2 43.3 Entity Graph Basics.................................................................................................................. 43-1 The Default Entity Graph ................................................................................................ 43-1 Using Entity Graphs in Persistence Operations ........................................................... 43-2 Fetch Graphs .............................................................................................................. 43-2 Load Graphs ............................................................................................................... 43-2 Using Named Entity Graphs .................................................................................................. 43-3 Applying Named Entity Graph Annotations to Entity Classes................................. 43-3 Obtaining EntityGraph Instances from Named Entity Graphs ................................. 43-4 Using Entity Graphs in Query Operations........................................................................... 43-4 44 Using a Second-Level Cache with Java Persistence API Applications 44.1 44.1.1 44.2 44.2.1 44.2.1.1 44.2.1.2 44.2.1.3 44.2.2 44.2.2.1 44.2.2.2 44.2.2.3 Overview of the Second-Level Cache ................................................................................... 44-1 Controlling whether Entities May Be Cached .............................................................. 44-2 Specifying the Cache Mode Settings to Improve Performance......................................... 44-3 Setting the Cache Retrieval and Store Modes............................................................... 44-3 Cache Retrieval Mode............................................................................................... 44-3 Cache Store Mode...................................................................................................... 44-4 Setting the Cache Retrieval or Store Mode ............................................................ 44-4 Controlling the Second-Level Cache Programmatically............................................. 44-4 Checking whether an Entity's Data Is Cached ...................................................... 44-5 Removing an Entity from the Cache....................................................................... 44-5 Removing All Data from the Cache ........................................................................ 44-5 Part IX Messaging xxvii 45 Java Message Service Concepts 45.1 45.1.1 45.1.2 45.1.3 45.1.4 45.2 45.2.1 45.2.2 45.2.2.1 45.2.2.2 45.2.3 45.3 45.3.1 45.3.1.1 45.3.1.2 45.3.2 45.3.3 45.3.4 45.3.5 45.3.6 45.3.6.1 45.3.6.2 45.3.6.3 45.3.6.4 45.3.6.5 45.3.7 45.3.7.1 45.3.7.2 45.3.7.3 45.3.8 45.3.9 45.4 45.4.1 45.4.2 45.4.2.1 45.4.2.2 45.4.2.3 45.4.2.4 45.4.2.5 45.4.3 45.4.4 45.4.5 45.5 45.5.1 45.5.2 45.5.2.1 Overview of the JMS API........................................................................................................ 45-1 What Is Messaging?.......................................................................................................... 45-1 What Is the JMS API? ....................................................................................................... 45-2 When Can You Use the JMS API? .................................................................................. 45-2 How Does the JMS API Work with the Java EE Platform? ........................................ 45-3 Basic JMS API Concepts.......................................................................................................... 45-3 JMS API Architecture ....................................................................................................... 45-4 Messaging Styles............................................................................................................... 45-4 Point-to-Point Messaging Style ............................................................................... 45-5 Publish/Subscribe Messaging Style ....................................................................... 45-5 Message Consumption..................................................................................................... 45-6 The JMS API Programming Model ....................................................................................... 45-6 JMS Administered Objects .............................................................................................. 45-7 JMS Connection Factories......................................................................................... 45-8 JMS Destinations........................................................................................................ 45-8 Connections ....................................................................................................................... 45-9 Sessions .............................................................................................................................. 45-9 JMSContext Objects .......................................................................................................... 45-9 JMS Message Producers................................................................................................. 45-10 JMS Message Consumers............................................................................................... 45-10 JMS Message Listeners............................................................................................ 45-11 JMS Message Selectors ............................................................................................ 45-12 Consuming Messages from Topics ....................................................................... 45-12 Creating Durable Subscriptions ............................................................................ 45-13 Creating Shared Subscriptions .............................................................................. 45-15 JMS Messages .................................................................................................................. 45-16 Message Headers ..................................................................................................... 45-16 Message Properties.................................................................................................. 45-17 Message Bodies ........................................................................................................ 45-17 JMS Queue Browsers...................................................................................................... 45-18 JMS Exception Handling ............................................................................................... 45-19 Using Advanced JMS Features ............................................................................................ 45-19 Controlling Message Acknowledgment...................................................................... 45-20 Specifying Options for Sending Messages .................................................................. 45-21 Specifying Message Persistence ............................................................................ 45-21 Setting Message Priority Levels ............................................................................ 45-22 Allowing Messages to Expire ................................................................................ 45-22 Specifying a Delivery Delay................................................................................... 45-23 Using JMSProducer Method Chaining................................................................. 45-23 Creating Temporary Destinations................................................................................ 45-23 Using JMS Local Transactions ...................................................................................... 45-24 Sending Messages Asynchronously............................................................................. 45-25 Using the JMS API in Java EE Applications....................................................................... 45-26 Creating Resources for Java EE Applications............................................................. 45-26 Using Resource Injection in Enterprise Bean or Web Components ........................ 45-27 Injecting a ConnectionFactory, Queue, or Topic................................................. 45-27 xxviii 45.5.2.2 45.5.3 Injecting a JMSContext Object ............................................................................... 45-28 Using Java EE Components to Produce and to Synchronously Receive Messages ........... 45-28 45.5.3.1 45.5.3.2 45.5.4 45.5.5 45.6 Managing JMS Resources in Web and EJB Components................................... 45-29 Managing Transactions in Session Beans............................................................. 45-29 Using Message-Driven Beans to Receive Messages Asynchronously .................... 45-29 Managing JTA Transactions.......................................................................................... 45-32 Further Information about JMS............................................................................................ 45-33 46 Java Message Service Examples 46.1 Overview of the JMS Examples ............................................................................................. 46-1 46.2 Writing Simple JMS Applications.......................................................................................... 46-2 Starting the JMS Provider ................................................................................................ 46-3 46.2.1 Creating JMS Administered Objects .............................................................................. 46-3 46.2.2 To Create Resources for the Simple Examples ...................................................... 46-3 46.2.2.1 Building All the Simple Examples ................................................................................. 46-4 46.2.3 To Build All the Simple Examples Using NetBeans IDE ..................................... 46-4 46.2.3.1 To Build All the Simple Examples Using Maven ................................................. 46-4 46.2.3.2 Sending Messages............................................................................................................. 46-4 46.2.4 The Producer.java Client .......................................................................................... 46-5 46.2.4.1 To Run the Producer Client ..................................................................................... 46-6 46.2.4.2 Receiving Messages Synchronously .............................................................................. 46-7 46.2.5 The SynchConsumer.java Client ............................................................................. 46-7 46.2.5.1 To Run the SynchConsumer and Producer Clients.............................................. 46-7 46.2.5.2 Using a Message Listener for Asynchronous Message Delivery............................... 46-9 46.2.6 Writing the AsynchConsumer.java and TextListener.java Clients .................... 46-9 46.2.6.1 To Run the AsynchConsumer and Producer Clients ......................................... 46-10 46.2.6.2 Browsing Messages on a Queue ................................................................................... 46-11 46.2.7 The MessageBrowser.java Client .......................................................................... 46-11 46.2.7.1 To Run the QueueBrowser Client ......................................................................... 46-12 46.2.7.2 Running Multiple Consumers on the Same Destination .......................................... 46-13 46.2.8 Acknowledging Messages ............................................................................................. 46-14 46.2.9 46.2.9.1 To Run the ClientAckConsumer Client ............................................................... 46-15 46.3 Writing More Advanced JMS Applications ....................................................................... 46-16 Using Durable Subscriptions ........................................................................................ 46-16 46.3.1 To Create Resources for the Durable Subscription Example ............................ 46-16 46.3.1.1 To Run the Durable Subscription Example ......................................................... 46-17 46.3.1.2 To Run the unsubscriber Example ........................................................................ 46-18 46.3.1.3 Using Local Transactions............................................................................................... 46-18 46.3.2 46.3.2.1 To Create Resources for the transactedexample Example................................. 46-20 To Run the transactedexample Clients................................................................. 46-21 46.3.2.2 46.4 Writing High Performance and Scalable JMS Applications ............................................ 46-23 Using Shared Nondurable Subscriptions.................................................................... 46-23 46.4.1 Writing the Clients for the Shared Consumer Example .................................... 46-23 46.4.1.1 To Run the SharedConsumer and Producer Clients .......................................... 46-24 46.4.1.2 Using Shared Durable Subscriptions ........................................................................... 46-24 46.4.2 To Run the SharedDurableConsumer and Producer Clients ........................... 46-25 46.4.2.1 xxix 46.5 46.5.1 46.5.2 46.5.3 46.5.3.1 46.5.3.2 46.5.3.3 46.5.3.4 46.6 46.6.1 46.6.2 46.6.3 46.6.3.1 46.6.4 46.6.4.1 46.6.4.2 46.6.4.3 46.7 46.7.1 46.7.1.1 46.7.1.2 46.7.1.3 46.7.2 46.7.2.1 46.7.2.2 46.8 46.8.1 46.8.2 46.8.2.1 46.8.2.2 46.8.2.3 46.8.3 46.8.3.1 46.8.3.2 46.8.3.3 46.9 46.9.1 46.9.2 Sending and Receiving Messages Using a Simple Web Application ............................. 46-25 The websimplemessage Facelets Pages ....................................................................... 46-26 The websimplemessage Managed Beans .................................................................... 46-26 Running the websimplemessage Example ................................................................. 46-27 Creating Resources for the websimplemessage Example ................................. 46-28 To Package and Deploy websimplemessage Using NetBeans IDE ................. 46-28 To Package and Deploy websimplemessage Using Maven .............................. 46-28 To Run the websimplemessage Example............................................................. 46-28 Receiving Messages Asynchronously Using a Message-Driven Bean........................... 46-29 Overview of the simplemessage Example .................................................................. 46-29 The simplemessage Application Client ....................................................................... 46-29 The simplemessage Message-Driven Bean Class....................................................... 46-30 The onMessage Method.......................................................................................... 46-30 Running the simplemessage Example......................................................................... 46-31 Creating Resources for the simplemessage Example......................................... 46-31 To Run the simplemessage Example Using NetBeans IDE............................... 46-31 To Run the simplemessage Example Using Maven ........................................... 46-32 Sending Messages from a Session Bean to an MDB.......................................................... 46-32 Writing the Application Components for the clientsessionmdb Example............. 46-33 Coding the Application Client: MyAppClient.java............................................ 46-33 Coding the Publisher Session Bean....................................................................... 46-34 Coding the Message-Driven Bean: MessageBean.java....................................... 46-34 Running the clientsessionmdb Example ..................................................................... 46-35 To Run clientsessionmdb Using NetBeans IDE .................................................. 46-35 To Run clientsessionmdb Using Maven............................................................... 46-36 Using an Entity to Join Messages from Two MDBs.......................................................... 46-36 Overview of the clientmdbentity Example Application ........................................... 46-37 Writing the Application Components for the clientmdbentity Example ............... 46-38 Coding the Application Client: HumanResourceClient.java ............................ 46-38 Coding the Message-Driven Beans for the clientmdbentity Example............. 46-38 Coding the Entity Class for the clientmdbentity Example ................................ 46-39 Running the clientmdbentity Example........................................................................ 46-40 To Run clientmdbentity Using NetBeans IDE..................................................... 46-40 To Run clientmdbentity Using Maven ................................................................. 46-40 Viewing the Application Output........................................................................... 46-41 Using NetBeans IDE to Create JMS Resources .................................................................. 46-42 To Create JMS Resources Using NetBeans IDE.......................................................... 46-42 To Delete JMS Resources Using NetBeans IDE .......................................................... 46-43 Part X Security 47 Introduction to Security in the Java EE Platform 47.1 47.1.1 47.1.1.1 47.1.1.2 47.1.1.3 Overview of Java EE Security ................................................................................................ 47-1 A Simple Application Security Walkthrough............................................................... 47-2 Step 1: Initial Request................................................................................................ 47-2 Step 2: Initial Authentication ................................................................................... 47-2 Step 3: URL Authorization ....................................................................................... 47-3 xxx Step 4: Fulfilling the Original Request.................................................................... 47-3 47.1.1.4 Step 5: Invoking Enterprise Bean Business Methods ........................................... 47-3 47.1.1.5 Features of a Security Mechanism.................................................................................. 47-4 47.1.2 Characteristics of Application Security ......................................................................... 47-4 47.1.3 Security Mechanisms............................................................................................................... 47-5 47.2 Java SE Security Mechanisms ......................................................................................... 47-5 47.2.1 Java EE Security Mechanisms ......................................................................................... 47-6 47.2.2 Application-Layer Security ...................................................................................... 47-6 47.2.2.1 Transport-Layer Security.......................................................................................... 47-7 47.2.2.2 Message-Layer Security............................................................................................ 47-7 47.2.2.3 Securing Containers................................................................................................................. 47-8 47.3 Using Annotations to Specify Security Information.................................................... 47-8 47.3.1 Using Deployment Descriptors for Declarative Security............................................ 47-8 47.3.2 Using Programmatic Security ......................................................................................... 47-9 47.3.3 47.4 Securing GlassFish Server....................................................................................................... 47-9 47.5 Working with Realms, Users, Groups, and Roles ............................................................. 47-10 What Are Realms, Users, Groups, and Roles?............................................................ 47-10 47.5.1 What Is a Realm? ..................................................................................................... 47-11 47.5.1.1 What Is a User? ........................................................................................................ 47-11 47.5.1.2 What Is a Group? ..................................................................................................... 47-12 47.5.1.3 What Is a Role?......................................................................................................... 47-12 47.5.1.4 Some Other Terminology ....................................................................................... 47-12 47.5.1.5 Managing Users and Groups in GlassFish Server ..................................................... 47-12 47.5.2 To Add Users to GlassFish Server......................................................................... 47-12 47.5.2.1 Setting Up Security Roles .............................................................................................. 47-13 47.5.3 Mapping Roles to Users and Groups........................................................................... 47-14 47.5.4 Establishing a Secure Connection Using SSL..................................................................... 47-15 47.6 Verifying and Configuring SSL Support..................................................................... 47-16 47.6.1 Further Information about Security .................................................................................... 47-17 47.7 48 Getting Started Securing Web Applications 48.1 48.2 48.2.1 48.2.1.1 48.2.1.2 48.2.1.3 48.2.1.4 48.2.2 48.2.2.1 48.2.2.2 48.2.2.3 48.2.3 48.2.4 48.3 48.3.1 48.3.2 Overview of Web Application Security................................................................................ 48-1 Securing Web Applications .................................................................................................... 48-2 Specifying Security Constraints...................................................................................... 48-2 Specifying a Web Resource Collection ................................................................... 48-3 Specifying an Authorization Constraint ................................................................ 48-4 Specifying a Secure Connection .............................................................................. 48-4 Specifying Security Constraints for Resources...................................................... 48-5 Specifying Authentication Mechanisms........................................................................ 48-6 HTTP Basic Authentication...................................................................................... 48-6 Form-Based Authentication ..................................................................................... 48-7 Digest Authentication ............................................................................................... 48-8 Specifying an Authentication Mechanism in the Deployment Descriptor .............. 48-8 Declaring Security Roles .................................................................................................. 48-9 Using Programmatic Security with Web Applications .................................................... 48-10 Authenticating Users Programmatically..................................................................... 48-10 Checking Caller Identity Programmatically ............................................................... 48-12 xxxi 48.3.3 48.3.4 48.4 48.4.1 48.4.2 48.4.2.1 48.4.2.2 48.4.2.3 48.4.2.4 48.4.3 Example Code for Programmatic Security.................................................................. 48-12 Declaring and Linking Role References ...................................................................... 48-13 Examples: Securing Web Applications ............................................................................... 48-14 To Set Up Your System for Running the Security Examples ................................... 48-14 The hello2-basicauth Example: Basic Authentication with a Servlet ...................... 48-15 Specifying Security for Basic Authentication Using Annotations.................... 48-16 To Build, Package, and Deploy the hello2-basicauth Example Using NetBeans IDE 48-16 To Build, Package, and Deploy the hello2-basicauth Example Using Maven 48-17 To Run the hello2-basicauth Example .................................................................. 48-17 The hello1-formauth Example: Form-Based Authentication with a JavaServer Faces Application 48-18 48.4.3.1 48.4.3.2 48.4.3.3 48.4.3.4 48.4.3.5 Creating the Login Form and the Error Page ...................................................... 48-18 Specifying Security for the Form-Based Authentication Example................... 48-19 To Build, Package, and Deploy the hello1-formauth Example Using NetBeans IDE 48-20 To Build, Package, and Deploy the hello1-formauth Example Using Maven and the asadmin Command 48-20 To Run the hello1-formauth Example .................................................................. 48-20 49 Getting Started Securing Enterprise Applications 49.1 49.2 49.2.1 49.2.1.1 49.2.1.2 49.2.2 49.2.2.1 49.2.3 49.2.3.1 49.2.3.2 49.2.4 49.3 49.3.1 49.3.1.1 49.3.1.2 49.3.1.3 49.3.2 Basic Security Tasks for Enterprise Applications................................................................ 49-1 Securing Enterprise Beans ...................................................................................................... 49-1 Securing an Enterprise Bean Using Declarative Security ........................................... 49-3 Specifying Authorized Users by Declaring Security Roles ................................. 49-3 Specifying an Authentication Mechanism and Secure Connection ................... 49-6 Securing an Enterprise Bean Programmatically........................................................... 49-6 Accessing an Enterprise Bean Caller's Security Context ..................................... 49-6 Propagating a Security Identity (Run-As)..................................................................... 49-8 Configuring a Component's Propagated Security Identity................................. 49-8 Trust between Containers ........................................................................................ 49-9 Deploying Secure Enterprise Beans ............................................................................... 49-9 Examples: Securing Enterprise Beans ................................................................................... 49-9 The cart-secure Example: Securing an Enterprise Bean with Declarative Security 49-9 Annotating the Bean................................................................................................ 49-10 To Run the cart-secure Example Using NetBeans IDE ...................................... 49-11 To Run the cart-secure Example Using Maven................................................... 49-12 The converter-secure Example: Securing an Enterprise Bean with Programmatic Security 49-13 49.3.2.1 49.3.2.2 49.3.2.3 49.3.2.4 49.3.2.5 Modifying ConverterBean...................................................................................... 49-13 Modifying ConverterServlet .................................................................................. 49-14 To Run the converter-secure Example Using NetBeans IDE ............................ 49-14 To Run the converter-secure Example Using Maven......................................... 49-15 To Run the converter-secure Example ................................................................. 49-15 50 Java EE Security: Advanced Topics 50.1 Working with Digital Certificates.......................................................................................... 50-1 xxxii 50.1.1 50.1.1.1 50.1.2 50.1.3 50.1.3.1 50.2 50.2.1 50.2.2 50.2.2.1 50.2.2.2 50.3 50.3.1 50.4 50.5 50.5.1 50.5.2 50.6 50.6.1 50.6.2 50.6.3 50.6.4 50.7 50.7.1 50.7.2 Creating a Server Certificate ........................................................................................... 50-2 To Use keytool to Create a Server Certificate........................................................ 50-3 Adding Users to the Certificate Realm .......................................................................... 50-4 Using a Different Server Certificate with GlassFish Server........................................ 50-4 To Specify a Different Server Certificate................................................................ 50-4 Authentication Mechanisms................................................................................................... 50-5 Client Authentication ....................................................................................................... 50-5 Mutual Authentication..................................................................................................... 50-5 Enabling Mutual Authentication over SSL ............................................................ 50-7 Creating a Client Certificate for Mutual Authentication ..................................... 50-7 Using the JDBC Realm for User Authentication ................................................................. 50-9 To Configure a JDBC Authentication Realm ................................................................ 50-9 Securing HTTP Resources .................................................................................................... 50-10 Securing Application Clients................................................................................................ 50-13 Using Login Modules..................................................................................................... 50-13 Using Programmatic Login ........................................................................................... 50-14 Securing Enterprise Information Systems Applications .................................................. 50-14 Container-Managed Sign-On ........................................................................................ 50-14 Component-Managed Sign-On..................................................................................... 50-15 Configuring Resource Adapter Security ..................................................................... 50-15 Mapping an Application Principal to EIS Principals................................................. 50-16 Configuring Security Using Deployment Descriptors ..................................................... 50-17 Specifying Security for Basic Authentication in the Deployment Descriptor........ 50-17 Specifying Non-Default Principal-to-Role Mapping in the Deployment Descriptor ........ 50-17 50.8 Further Information about Advanced Security Topics .................................................... 50-18 Part XI Java EE Supporting Technologies 51 Transactions 51.1 Transactions in Java EE Applications ................................................................................... 51-1 51.2 What Is a Transaction? ............................................................................................................ 51-2 Container-Managed Transactions ......................................................................................... 51-2 51.3 Transaction Attributes ..................................................................................................... 51-3 51.3.1 Required Attribute .................................................................................................... 51-3 51.3.1.1 RequiresNew Attribute............................................................................................. 51-3 51.3.1.2 Mandatory Attribute ................................................................................................. 51-4 51.3.1.3 NotSupported Attribute ........................................................................................... 51-4 51.3.1.4 Supports Attribute..................................................................................................... 51-4 51.3.1.5 Never Attribute.......................................................................................................... 51-4 51.3.1.6 Summary of Transaction Attributes ....................................................................... 51-4 51.3.1.7 Setting Transaction Attributes ................................................................................. 51-5 51.3.1.8 Rolling Back a Container-Managed Transaction ......................................................... 51-6 51.3.2 Synchronizing a Session Bean's Instance Variables ..................................................... 51-6 51.3.3 Methods Not Allowed in Container-Managed Transactions..................................... 51-6 51.3.4 Bean-Managed Transactions .................................................................................................. 51-7 51.4 JTA Transactions............................................................................................................... 51-7 51.4.1 xxxiii 51.4.2 51.4.3 51.5 51.5.1 51.6 51.7 51.8 Returning without Committing...................................................................................... 51-7 Methods Not Allowed in Bean-Managed Transactions.............................................. 51-8 Transaction Timeouts .............................................................................................................. 51-8 To Set a Transaction Timeout.......................................................................................... 51-8 Updating Multiple Databases ................................................................................................ 51-8 Transactions in Web Components......................................................................................... 51-9 Further Information about Transactions .............................................................................. 51-9 52 Resource Adapters and Contracts 52.1 What Is a Resource Adapter? ................................................................................................. 52-1 Management Contracts .................................................................................................... 52-2 52.1.1 Lifecycle Management .............................................................................................. 52-2 52.1.1.1 52.1.1.2 Work Management Contract ................................................................................... 52-2 Generic Work Context Contract ..................................................................................... 52-3 52.1.2 52.1.3 Outbound and Inbound Contracts................................................................................. 52-3 52.2 Metadata Annotations............................................................................................................. 52-4 Common Client Interface........................................................................................................ 52-5 52.3 Using Resource Adapters with Contexts and Dependency Injection for Java EE (CDI) 52-6 52.4 Further Information about Resource Adapters ................................................................... 52-7 52.5 53 The Resource Adapter Examples 53.1 53.1.1 53.1.2 53.1.3 53.1.3.1 53.1.3.2 53.2 53.2.1 53.2.2 53.2.3 53.2.3.1 53.2.3.2 The trading Example ............................................................................................................... 53-1 Using the Outbound Resource Adapter........................................................................ 53-2 Implementing the Outbound Resource Adapter ......................................................... 53-4 Running the trading Example......................................................................................... 53-5 To Run the trading Example Using NetBeans IDE............................................... 53-5 To Run the trading Example Using Maven ........................................................... 53-6 The traffic Example.................................................................................................................. 53-6 Using the Inbound Resource Adapter ........................................................................... 53-7 Implementing the Inbound Resource Adapter ............................................................ 53-8 Running the traffic Example ......................................................................................... 53-10 To Run the traffic Example Using NetBeans IDE ............................................... 53-11 To Run the traffic Example Using Maven............................................................ 53-11 54 Using Java EE Interceptors 54.1 54.1.1 54.1.2 54.1.3 54.2 54.2.1 54.2.1.1 54.2.1.2 54.2.2 54.2.2.1 54.2.2.2 Overview of Interceptors ........................................................................................................ 54-1 Interceptor Classes............................................................................................................ 54-2 Interceptor Lifecycle ......................................................................................................... 54-2 Interceptors and CDI........................................................................................................ 54-2 Using Interceptors.................................................................................................................... 54-2 Intercepting Method Invocations ................................................................................... 54-3 Using Multiple Method Interceptors ...................................................................... 54-3 Accessing Target Method Parameters from an Interceptor Class ...................... 54-4 Intercepting Lifecycle Callback Events.......................................................................... 54-4 Using AroundConstruct Interceptor Methods...................................................... 54-5 Using Multiple Lifecycle Callback Interceptors.................................................... 54-5 xxxiv 54.2.3 54.2.3.1 54.2.4 54.2.4.1 54.2.4.2 54.2.5 54.3 54.3.1 54.3.1.1 54.3.1.2 Intercepting Timeout Events........................................................................................... 54-6 Using Multiple Timeout Interceptors ..................................................................... 54-6 Binding Interceptors to Components............................................................................. 54-6 Declaring the Interceptor Bindings on an Interceptor Class ............................... 54-7 Binding a Component to an Interceptor ................................................................ 54-7 Ordering Interceptors....................................................................................................... 54-8 The interceptor Example Application................................................................................... 54-9 Running the interceptor Example .................................................................................. 54-9 To Run the interceptor Example Using NetBeans IDE ...................................... 54-10 To Run the interceptor Example Using Maven................................................... 54-10 55 Batch Processing 55.1 55.1.1 55.1.2 55.1.3 55.1.4 55.2 55.2.1 55.2.2 55.2.3 55.2.4 55.2.5 55.2.6 55.3 55.3.1 55.3.2 55.4 55.4.1 55.4.2 55.4.2.1 55.4.2.2 55.4.2.3 55.4.3 55.4.4 55.4.5 55.5 55.5.1 55.5.2 55.5.3 55.6 55.6.1 55.6.2 55.6.3 55.7 55.8 55.8.1 Introduction to Batch Processing........................................................................................... 55-1 Steps in Batch Jobs ............................................................................................................ 55-2 Parallel Processing............................................................................................................ 55-3 Status and Decision Elements ......................................................................................... 55-3 Batch Framework Functionality ..................................................................................... 55-4 Batch Processing in Java EE.................................................................................................... 55-4 The Batch Processing Framework .................................................................................. 55-4 Creating Batch Applications ........................................................................................... 55-5 Elements of a Batch Job.................................................................................................... 55-5 Properties and Parameters .............................................................................................. 55-6 Job Instances and Job Executions ................................................................................... 55-6 Batch and Exit Status........................................................................................................ 55-6 Simple Use Case ....................................................................................................................... 55-7 Chunk Step ........................................................................................................................ 55-7 Task Step ............................................................................................................................ 55-9 Using the Job Specification Language................................................................................. 55-10 The job Element............................................................................................................... 55-10 The step Element............................................................................................................. 55-11 The chunk Element.................................................................................................. 55-12 The batchlet Element............................................................................................... 55-14 The partition Element ............................................................................................. 55-14 The flow Element ............................................................................................................ 55-16 The split Element ............................................................................................................ 55-16 The decision Element ..................................................................................................... 55-17 Creating Batch Artifacts ........................................................................................................ 55-17 Batch Artifact Interfaces................................................................................................. 55-17 Dependency Injection in Batch Artifacts ..................................................................... 55-20 Using the Context Objects from the Batch Runtime .................................................. 55-21 Submitting Jobs to the Batch Runtime ................................................................................ 55-21 Starting a Job.................................................................................................................... 55-22 Checking the Status of a Job.......................................................................................... 55-22 Invoking the Batch Runtime in Your Application ..................................................... 55-22 Packaging Batch Applications.............................................................................................. 55-22 The webserverlog Example Application ............................................................................ 55-23 Architecture of the webserverlog Example Application........................................... 55-23 xxxv The Job Definition File ............................................................................................ 55-23 55.8.1.1 The LogLine and LogFilteredLine Items.............................................................. 55-24 55.8.1.2 The Chunk Step Batch Artifacts ............................................................................ 55-25 55.8.1.3 The Listener Batch Artifacts ................................................................................... 55-26 55.8.1.4 The Task Step Batch Artifact.................................................................................. 55-27 55.8.1.5 The JavaServer Faces Pages.................................................................................... 55-27 55.8.1.6 The Managed Bean .................................................................................................. 55-27 55.8.1.7 Running the webserverlog Example Application...................................................... 55-28 55.8.2 To Run the webserverlog Example Application Using NetBeans IDE............ 55-28 55.8.2.1 To Run the webserverlog Example Application Using Maven ........................ 55-28 55.8.2.2 The phonebilling Example Application.............................................................................. 55-29 55.9 Architecture of the phonebilling Example Application ............................................ 55-29 55.9.1 The Job Definition File ............................................................................................ 55-29 55.9.1.1 The CallRecord and PhoneBill Entities ................................................................ 55-30 55.9.1.2 The Call Records Chunk Step ................................................................................ 55-31 55.9.1.3 The Phone Billing Chunk Step............................................................................... 55-33 55.9.1.4 The JavaServer Faces Pages.................................................................................... 55-34 55.9.1.5 The Managed Bean .................................................................................................. 55-35 55.9.1.6 Running the phonebilling Example Application ....................................................... 55-35 55.9.2 To Run the phonebilling Example Application Using NetBeans IDE ............. 55-35 55.9.2.1 55.9.2.2 To Run the phonebilling Example Application Using Maven.......................... 55-36 55.10 Further Information about Batch Processing ..................................................................... 55-36 56 Concurrency Utilities for Java EE Concurrency Basics.................................................................................................................. 56-1 56.1 Threads and Processes ..................................................................................................... 56-1 56.1.1 56.2 Main Components of the Concurrency Utilities ................................................................. 56-2 Concurrency and Transactions .............................................................................................. 56-3 56.3 Concurrency and Security ...................................................................................................... 56-3 56.4 The jobs Concurrency Example ............................................................................................. 56-3 56.5 Running the jobs Example............................................................................................... 56-4 56.5.1 To Configure GlassFish Server for the Basic Concurrency Example................. 56-4 56.5.1.1 To Build, Package, and Deploy the jobs Example Using NetBeans IDE ........... 56-5 56.5.1.2 To Build, Package, and Deploy the jobs Example Using Maven........................ 56-5 56.5.1.3 To Run the jobs Example and Submit Jobs with Low Priority ........................... 56-5 56.5.1.4 56.5.1.5 To Run the jobs Example and Submit Jobs with High Priority .......................... 56-6 The taskcreator Concurrency Example................................................................................. 56-7 56.6 56.6.1 Running the taskcreator Example .................................................................................. 56-8 56.6.1.1 To Build, Package, and Deploy the taskcreator Example Using NetBeans IDE.......... 56-8 To Build, Package, and Deploy the taskcreator Example Using Maven ........... 56-8 To Run the taskcreator Example ............................................................................. 56-9 Further Information about the Concurrency Utilities ........................................................ 56-9 56.6.1.2 56.6.1.3 56.7 Part XII Case Studies xxxvi 57 Duke's Bookstore Case Study Example 57.1 57.2 57.2.1 57.2.2 57.2.3 57.2.4 57.2.5 57.2.6 57.3 57.3.1 57.3.2 57.3.3 Design and Architecture of Duke's Bookstore..................................................................... 57-1 The Duke's Bookstore Interface ............................................................................................. 57-2 The Book Java Persistence API Entity............................................................................ 57-2 Enterprise Beans Used in Duke's Bookstore ................................................................. 57-3 Facelets Pages and Managed Beans Used in Duke's Bookstore................................. 57-3 Custom Components and Other Custom Objects Used in Duke's Bookstore ......... 57-4 Properties Files Used in Duke's Bookstore ................................................................... 57-5 Deployment Descriptors Used in Duke's Bookstore ................................................... 57-5 Running the Duke's Bookstore Case Study Application.................................................... 57-6 To Build and Deploy Duke's Bookstore Using NetBeans IDE ................................... 57-6 To Build and Deploy Duke's Bookstore Using Maven................................................ 57-6 To Run Duke's Bookstore ................................................................................................ 57-6 58 Duke's Tutoring Case Study Example 58.1 Design and Architecture of Duke's Tutoring....................................................................... 58-1 58.2 Main Interface........................................................................................................................... 58-3 Java Persistence API Entities Used in the Main Interface........................................... 58-3 58.2.1 Enterprise Beans Used in the Main Interface................................................................ 58-4 58.2.2 WebSocket Endpoint Used in the Main Interface ........................................................ 58-4 58.2.3 Facelets Files Used in the Main Interface ...................................................................... 58-4 58.2.4 Helper Classes Used in the Main Interface ................................................................... 58-5 58.2.5 Properties Files .................................................................................................................. 58-5 58.2.6 Deployment Descriptors Used in Duke's Tutoring ..................................................... 58-6 58.2.7 Administration Interface......................................................................................................... 58-6 58.3 Enterprise Beans Used in the Administration Interface.............................................. 58-6 58.3.1 Facelets Files Used in the Administration Interface .................................................... 58-7 58.3.2 CDI Managed Beans Used in the Administration Interface ....................................... 58-7 58.3.3 Helper Classes Used in the Administration Interface ................................................. 58-7 58.3.4 Running the Duke's Tutoring Case Study Application...................................................... 58-8 58.4 Running Duke's Tutoring ................................................................................................ 58-8 58.4.1 To Build and Deploy Duke's Tutoring Using NetBeans IDE.............................. 58-8 58.4.1.1 To Build and Deploy Duke's Tutoring Using Maven .......................................... 58-8 58.4.1.2 Using Duke's Tutoring.............................................................................................. 58-9 58.4.1.3 59 Duke's Forest Case Study Example 59.1 59.1.1 59.1.2 59.1.3 59.1.4 59.1.5 59.1.5.1 59.1.5.2 59.1.5.3 59.1.5.4 Design and Architecture of Duke's Forest............................................................................ 59-2 The events Project ............................................................................................................. 59-4 The entities Project............................................................................................................ 59-5 The dukes-payment Project............................................................................................. 59-7 The dukes-resources Project............................................................................................ 59-7 The Duke's Store Project .................................................................................................. 59-8 Enterprise Beans Used in Duke's Store .................................................................. 59-9 Facelets Files Used in the Main Interface of Duke's Store ................................... 59-9 Facelets Files Used in the Administration Interface of Duke's Store ............... 59-10 Managed Beans Used in Duke's Store .................................................................. 59-10 xxxvii 59.1.5.5 59.1.5.6 59.1.5.7 59.1.5.8 59.1.6 59.1.6.1 59.1.6.2 59.1.6.3 59.1.6.4 59.1.6.5 59.1.6.6 59.2 59.2.1 59.2.2 59.3 59.3.1 59.3.2 59.3.3 59.3.4 Helper Classes Used in Duke's Store.................................................................... 59-11 Qualifiers Used in Duke's Store............................................................................. 59-11 Event Handlers Used in Duke's Store .................................................................. 59-11 Deployment Descriptors Used in Duke's Store................................................... 59-11 The Duke's Shipment Project ........................................................................................ 59-11 Enterprise Beans Used in Duke's Shipment ........................................................ 59-12 Facelets Files Used in Duke's Shipment ............................................................... 59-12 Managed Beans Used in Duke's Shipment .......................................................... 59-12 Helper Class Used in Duke's Shipment ............................................................... 59-13 Qualifier Used in Duke's Shipment ...................................................................... 59-13 Deployment Descriptors Used in Duke's Shipment........................................... 59-13 Building and Deploying the Duke's Forest Case Study Application ............................. 59-13 To Build and Deploy the Duke's Forest Application Using NetBeans IDE ........... 59-13 To Build and Deploy the Duke's Forest Application Using Maven........................ 59-13 Running the Duke's Forest Application ............................................................................. 59-14 To Register as a Duke's Store Customer...................................................................... 59-14 To Purchase Products..................................................................................................... 59-14 To Approve Shipment of a Product ............................................................................. 59-15 To Create a New Product .............................................................................................. 59-15 Index xxxviii Preface This tutorial is a guide to developing enterprise applications for the Java Platform, Enterprise Edition 7 (Java EE 7), using GlassFish Server Open Source Edition. GlassFish Server Open Source Edition is the leading open-source and open-community platform for building and deploying next-generation applications and services. GlassFish Server Open Source Edition, developed by the GlassFish project open-source community at https://glassfish.java.net/, is the first compatible implementation of the Java EE 7 platform specification. This lightweight, flexible, and open-source application server enables organizations not only to leverage the new capabilities introduced within the Java EE 7 specification, but also to add to their existing capabilities through a faster and more streamlined development and deployment cycle. GlassFish Server Open Source Edition is hereafter referred to as GlassFish Server. The following topics are addressed here: ■ Audience ■ Documentation Accessibility ■ ■ ■ Before You Read This Book Related Documentation Conventions ■ Default Paths and File Names Audience This tutorial is intended for programmers interested in developing and deploying Java EE 7 applications. It covers the technologies comprising the Java EE platform and describes how to develop Java EE components and deploy them on the Java EE Software Development Kit (SDK). Documentation Accessibility For information about Oracle's commitment to accessibility, visit the Oracle Accessibility Program website at http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacc. Access to Oracle Support Oracle customers have access to electronic support through My Oracle Support. For information, visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=info or xxxix visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=trs if you are hearing impaired. Before You Read This Book Before proceeding with this tutorial, you should have a good knowledge of the Java programming language. A good way to get to that point is to work through the Java Tutorials (http://docs.oracle.com/javase/tutorial/index.html). Related Documentation The GlassFish Server documentation set describes deployment planning and system installation. To obtain documentation for GlassFish Server Open Source Edition, go to https://glassfish.java.net/docs/. The Java EE 7 API specification can be viewed at http://docs.oracle.com/javaee/7/api/ and is also provided in the Java EE 7 SDK. Additionally, the Java EE Specifications at http://www.oracle.com/technetwork/java/javaee/tech/index.html might be useful. For information about creating enterprise applications in the NetBeans Integrated Development Environment (IDE), see https://netbeans.org/kb/. For information about the Java DB database for use with GlassFish Server, see http://www.oracle.com/technetwork/java/javadb/overview/index.html. The GlassFish Samples project is a collection of sample applications that demonstrate a broad range of Java EE technologies. The GlassFish Samples are bundled with the Java EE Software Development Kit (SDK) and are also available from the GlassFish Samples project page at https://glassfish-samples.java.net/. Conventions The following table describes the typographic conventions that are used in this book. Convention Meaning Example Boldface Boldface type indicates graphical user interface elements associated with an action or terms defined in text. From the File menu, choose Open Project. A cache is a copy that is stored locally. Monospace Monospace type indicates the names Edit your .login file. Italic of files and directories, commands within a paragraph, URLs, code in examples, text that appears on the screen, or text that you enter. Italic type indicates book titles, emphasis, or placeholder variables for which you supply particular values. Use ls -a to list all files. machine_name% you have mail. Read Chapter 6 in the User's Guide. Do not save the file. The command to remove a file is rm filename. Default Paths and File Names The following table describes the default paths and file names that are used in this book. xl Placeholder Description Default Value as-install Represents the base installation directory for GlassFish Server or the SDK of which GlassFish Server is a part. Installations on the Solaris operating system, Linux operating system, and Mac operating system: user's-home-directory/glassfish4/glassfish Windows, all installations: SystemDrive:\glassfish4\glassfish as-install-parent Represents the parent of the base installation directory for GlassFish Server. Installations on the Solaris operating system, Linux operating system, and Mac operating system: user's-home-directory/glassfish4 Windows, all installations: SystemDrive:\glassfish4 as-install-parent/docs/javaee-tutorial as-install/domains/domain1 tut-install domain-dir Represents the base installation directory for the Java EE Tutorial after you install GlassFish Server or the SDK and run the Update Tool. Represents the directory in which a domain's configuration is stored. xli xlii Part I Part I Introduction Part I introduces the platform, the tutorial, and the examples. This part contains the following chapters: ■ ■ Chapter 1, "Overview" Chapter 2, "Using the Tutorial Examples" 1 1Overview [2] This chapter introduces you to Java EE enterprise application development. Here you will review development basics, learn about the Java EE architecture and APIs, become acquainted with important terms and concepts, and find out how to approach Java EE application programming, assembly, and deployment. Developers today increasingly recognize the need for distributed, transactional, and portable applications that leverage the speed, security, and reliability of server-side technology. Enterprise applications provide the business logic for an enterprise. They are centrally managed and often interact with other enterprise software. In the world of information technology, enterprise applications must be designed, built, and produced for less money, with greater speed, and with fewer resources. With the Java Platform, Enterprise Edition (Java EE), development of Java enterprise applications has never been easier or faster. The aim of the Java EE platform is to provide developers with a powerful set of APIs while shortening development time, reducing application complexity, and improving application performance. The Java EE platform is developed through the Java Community Process (JCP), which is responsible for all Java technologies. Expert groups composed of interested parties have created Java Specification Requests (JSRs) to define the various Java EE technologies. The work of the Java Community under the JCP program helps to ensure Java technology's standards of stability and cross-platform compatibility. The Java EE platform uses a simplified programming model. XML deployment descriptors are optional. Instead, a developer can simply enter the information as an annotation directly into a Java source file, and the Java EE server will configure the component at deployment and runtime. These annotations are generally used to embed in a program data that would otherwise be furnished in a deployment descriptor. With annotations, you put the specification information in your code next to the program element affected. In the Java EE platform, dependency injection can be applied to all resources a component needs, effectively hiding the creation and lookup of resources from application code. Dependency injection can be used in Enterprise JavaBeans (EJB) containers, web containers, and application clients. Dependency injection allows the Java EE container to automatically insert references to other required components or resources, using annotations. This tutorial uses examples to describe the features available in the Java EE platform for developing enterprise applications. Whether you are a new or experienced enterprise developer, you should find the examples and accompanying text a valuable and accessible knowledge base for creating your own solutions. The following topics are addressed here: ■ Java EE 7 Platform Highlights Overview 1-1 Java EE 7 Platform Highlights ■ Java EE Application Model ■ Distributed Multitiered Applications ■ Java EE Containers ■ Web Services Support ■ ■ ■ Java EE Application Assembly and Deployment Java EE 7 APIs Java EE 7 APIs in the Java Platform, Standard Edition 7 ■ GlassFish Server Tools 1.1 Java EE 7 Platform Highlights The most important goal of the Java EE 7 platform is to simplify development by providing a common foundation for the various kinds of components in the Java EE platform. Developers benefit from productivity improvements with more annotations and less XML configuration, more Plain Old Java Objects (POJOs), and simplified packaging. The Java EE 7 platform includes the following new features: ■ New technologies, including the following: – Batch Applications for the Java Platform – Concurrency Utilities for Java EE – – Java API for JSON Processing (JSON-P) Java API for WebSocket ■ New features for EJB components (see Enterprise JavaBeans Technology for details) ■ New features for servlets (see Java Servlet Technology for details) ■ New features for JavaServer Faces components (see JavaServer Faces Technology for details) ■ New features for the Java Message Service (JMS) (see Java Message Service API for details) 1.2 Java EE Application Model The Java EE application model begins with the Java programming language and the Java virtual machine. The proven portability, security, and developer productivity they provide form the basis of the application model. Java EE is designed to support applications that implement enterprise services for customers, employees, suppliers, partners, and others who make demands on or contributions to the enterprise. Such applications are inherently complex, potentially accessing data from a variety of sources and distributing applications to a variety of clients. To better control and manage these applications, the business functions to support these various users are conducted in the middle tier. The middle tier represents an environment that is closely controlled by an enterprise's information technology department. The middle tier is typically run on dedicated server hardware and has access to the full services of the enterprise. The Java EE application model defines an architecture for implementing services as multitier applications that deliver the scalability, accessibility, and manageability 1-2 Java Platform, Enterprise Edition The Java EE Tutorial Distributed Multitiered Applications needed by enterprise-level applications. This model partitions the work needed to implement a multitier service into the following parts: ■ ■ The business and presentation logic to be implemented by the developer The standard system services provided by the Java EE platform The developer can rely on the platform to provide solutions for the hard systems-level problems of developing a multitier service. 1.3 Distributed Multitiered Applications The Java EE platform uses a distributed multitiered application model for enterprise applications. Application logic is divided into components according to function, and the application components that make up a Java EE application are installed on various machines depending on the tier in the multitiered Java EE environment to which the application component belongs. Figure 1–1 shows two multitiered Java EE applications divided into the tiers described in the following list. The Java EE application parts shown in Figure 1–1 are presented in Java EE Components. ■ Client-tier components run on the client machine. ■ Web-tier components run on the Java EE server. ■ ■ Business-tier components run on the Java EE server. Enterprise information system (EIS)-tier software runs on the EIS server. Although a Java EE application can consist of all tiers shown in Figure 1–1, Java EE multitiered applications are generally considered to be three-tiered applications because they are distributed over three locations: client machines, the Java EE server machine, and the database or legacy machines at the back end. Three-tiered applications that run in this way extend the standard two-tiered client-and-server model by placing a multithreaded application server between the client application and back-end storage. Overview 1-3 Distributed Multitiered Applications Figure 1–1 Multitiered Applications Java EE Application 1 Java EE Application 2 Application Client Web Pages JavaServer Faces Pages Enterprise Beans Enterprise Beans Database Database Client Tier Client Machine Java EE Server Web Tier Business Tier EIS Tier Database Server 1.3.1 Security Although other enterprise application models require platform-specific security measures in each application, the Java EE security environment enables security constraints to be defined at deployment time. The Java EE platform makes applications portable to a wide variety of security implementations by shielding application developers from the complexity of implementing security features. The Java EE platform provides standard declarative access control rules that are defined by the developer and interpreted when the application is deployed on the server. Java EE also provides standard login mechanisms so that application developers do not have to implement these mechanisms in their applications. The same application works in a variety of security environments without changing the source code. 1.3.2 Java EE Components Java EE applications are made up of components. A Java EE component is a self-contained functional software unit that is assembled into a Java EE application with its related classes and files and that communicates with other components. The Java EE specification defines the following Java EE components: ■ Application clients and applets are components that run on the client. ■ Java Servlet, JavaServer Faces, and JavaServer Pages (JSP) technology components are web components that run on the server. 1-4 Java Platform, Enterprise Edition The Java EE Tutorial Distributed Multitiered Applications ■ EJB components (enterprise beans) are business components that run on the server. Java EE components are written in the Java programming language and are compiled in the same way as any program in the language. The differences between Java EE components and "standard" Java classes are that Java EE components are assembled into a Java EE application, they are verified to be well formed and in compliance with the Java EE specification, and they are deployed to production, where they are run and managed by the Java EE server. 1.3.3 Java EE Clients A Java EE client is usually either a web client or an application client. 1.3.3.1 Web Clients A web client consists of two parts: ■ Dynamic web pages containing various types of markup language (HTML, XML, and so on), which are generated by web components running in the web tier ■ A web browser, which renders the pages received from the server A web client is sometimes called a thin client. Thin clients usually do not query databases, execute complex business rules, or connect to legacy applications. When you use a thin client, such heavyweight operations are off-loaded to enterprise beans executing on the Java EE server, where they can leverage the security, speed, services, and reliability of Java EE server-side technologies. 1.3.3.2 Application Clients An application client runs on a client machine and provides a way for users to handle tasks that require a richer user interface than can be provided by a markup language. An application client typically has a graphical user interface (GUI) created from the Swing API or the Abstract Window Toolkit (AWT) API, but a command-line interface is certainly possible. Application clients directly access enterprise beans running in the business tier. However, if application requirements warrant it, an application client can open an HTTP connection to establish communication with a servlet running in the web tier. Application clients written in languages other than Java can interact with Java EE servers, enabling the Java EE platform to interoperate with legacy systems, clients, and non-Java languages. 1.3.3.3 Applets A web page received from the web tier can include an embedded applet. Written in the Java programming language, an applet is a small client application that executes in the Java virtual machine installed in the web browser. However, client systems will likely need the Java Plug-in and possibly a security policy file for the applet to successfully execute in the web browser. Web components are the preferred API for creating a web client program because no plug-ins or security policy files are needed on the client systems. Also, web components enable cleaner and more modular application design because they provide a way to separate applications programming from web page design. Personnel involved in web page design thus do not need to understand Java programming language syntax to do their jobs. Overview 1-5 Distributed Multitiered Applications 1.3.3.4 The JavaBeans Component Architecture The server and client tiers might also include components based on the JavaBeans component architecture (JavaBeans components) to manage the data flow between the following: ■ An application client or applet and components running on the Java EE server ■ Server components and a database JavaBeans components are not considered Java EE components by the Java EE specification. JavaBeans components have properties and have get and set methods for accessing those properties. JavaBeans components used in this way are typically simple in design and implementation but should conform to the naming and design conventions outlined in the JavaBeans component architecture. 1.3.3.5 Java EE Server Communications Figure 1–2 shows the various elements that can make up the client tier. The client communicates with the business tier running on the Java EE server either directly or, as in the case of a client running in a browser, by going through web pages or servlets running in the web tier. Figure 1–2 Server Communication Application Client and Optional JavaBeans Components Web Browser, Web Pages, Applets, and Optional JavaBeans Components Client Tier Java EE Server Web Tier Business Tier 1.3.4 Web Components Java EE web components are either servlets or web pages created using JavaServer Faces technology and/or JSP technology (JSP pages). Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. JavaServer Faces technology builds on servlets and JSP technology and provides a user interface component framework for web applications. Static HTML pages and applets are bundled with web components during application assembly but are not considered web components by the Java EE specification. Server-side utility classes can also be bundled with web components and, like HTML pages, are not considered web components. 1-6 Java Platform, Enterprise Edition The Java EE Tutorial Distributed Multitiered Applications As shown in Figure 1–3, the web tier, like the client tier, might include a JavaBeans component to manage the user input and send that input to enterprise beans running in the business tier for processing. Figure 1–3 Web Tier and Java EE Applications Application Client and Optional JavaBeans Components Web Browser, Web Pages, Applets, and Optional JavaBeans Components Client Tier JavaBeans Components (Optional) Web Pages, Servlets Web Tier Java EE Server Business Tier 1.3.5 Business Components Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in either the business tier or the web tier. Figure 1–4 shows how an enterprise bean receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program. Overview 1-7 Java EE Containers Figure 1–4 Business and EIS Tiers Application Client and Optional JavaBeans Components Web Browser, Web Pages, Applets, and Optional JavaBeans Components Client Tier JavaBeans Components (Optional) Web Pages, Servlets Web Tier Java EE Server Java Persistence Entities, Session Beans, Message-Driven Beans Business Tier Database and Legacy Systems EIS Tier 1.3.6 Enterprise Information System Tier The enterprise information system tier handles EIS software and includes enterprise infrastructure systems, such as enterprise resource planning (ERP), mainframe transaction processing, database systems, and other legacy information systems. For example, Java EE application components might need access to enterprise information systems for database connectivity. 1.4 Java EE Containers Normally, thin-client multitiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling, and other complex low-level details. The component-based and platform-independent Java EE architecture makes applications easy to write because business logic is organized into reusable components. In addition, the Java EE server provides underlying services in the form of a container for every component type. Because you do not have to develop these services yourself, you are free to concentrate on solving the business problem at hand. 1-8 Java Platform, Enterprise Edition The Java EE Tutorial 1.4.1 Container Services Java EE Containers Containers are the interface between a component and the low-level, platform-specific functionality that supports the component. Before it can be executed, a web, enterprise bean, or application client component must be assembled into a Java EE module and deployed into its container. The assembly process involves specifying container settings for each component in the Java EE application and for the Java EE application itself. Container settings customize the underlying support provided by the Java EE server, including such services as security, transaction management, Java Naming and Directory Interface (JNDI) API lookups, and remote connectivity. Here are some of the highlights. ■ ■ ■ ■ The Java EE security model lets you configure a web component or enterprise bean so that system resources are accessed only by authorized users. The Java EE transaction model lets you specify relationships among methods that make up a single transaction so that all methods in one transaction are treated as a single unit. JNDI lookup services provide a unified interface to multiple naming and directory services in the enterprise so that application components can access these services. The Java EE remote connectivity model manages low-level communications between clients and enterprise beans. After an enterprise bean is created, a client invokes methods on it as if it were in the same virtual machine. Because the Java EE architecture provides configurable services, components within the same application can behave differently based on where they are deployed. For example, an enterprise bean can have security settings that allow it a certain level of access to database data in one production environment and another level of database access in another production environment. The container also manages nonconfigurable services, such as enterprise bean and servlet lifecycles, database connection resource pooling, data persistence, and access to the Java EE platform APIs (see Java EE 7 APIs). 1.4.2 Container Types The deployment process installs Java EE application components in the Java EE containers, as illustrated in Figure 1–5. Overview 1-9 Web Services Support Figure 1–5 Java EE Server and Containers Application Client Container Application Client Web Browser Servlet Web Page Enterprise Bean Enterprise Bean Client Machine Java EE Server Web Container EJB Container Database The server and containers are as follows: ■ ■ Java EE server: The runtime portion of a Java EE product. A Java EE server provides EJB and web containers. EJB container: Manages the execution of enterprise beans for Java EE applications. Enterprise beans and their container run on the Java EE server. ■ Web container: Manages the execution of web pages, servlets, and some EJB components for Java EE applications. Web components and their container run on the Java EE server. ■ Application client container: Manages the execution of application client components. Application clients and their container run on the client. ■ Applet container: Manages the execution of applets. Consists of a web browser and a Java Plug-in running on the client together. 1.5 Web Services Support Web services are web-based enterprise applications that use open, XML-based standards and transport protocols to exchange data with calling clients. The Java EE platform provides the XML APIs and tools you need to quickly design, develop, test, and deploy web services and clients that fully interoperate with other web services and clients running on Java-based or non-Java-based platforms. To write web services and clients with the Java EE XML APIs, all you need to do is pass parameter data to the method calls and process the data returned; for document-oriented web services, you send documents containing the service data back and forth. No low-level programming is needed because the XML API 1-10 Java Platform, Enterprise Edition The Java EE Tutorial 1.5.1 XML Web Services Support implementations do the work of translating the application data to and from an XML-based data stream that is sent over the standardized XML-based transport protocols. These XML-based standards and protocols are introduced in the following sections. The translation of data to a standardized XML-based data stream is what makes web services and clients written with the Java EE XML APIs fully interoperable. This does not necessarily mean that the data being transported includes XML tags, because the transported data can itself be plain text, XML data, or any kind of binary data, such as audio, video, maps, program files, computer-aided design (CAD) documents, and the like. The next section introduces XML and explains how parties doing business can use XML tags and schemas to exchange data in a meaningful way. Extensible Markup Language (XML) is a cross-platform, extensible, text-based standard for representing data. Parties that exchange XML data can create their own tags to describe the data, set up schemas to specify which tags can be used in a particular kind of XML document, and use XML style sheets to manage the display and handling of the data. For example, a web service can use XML and a schema to produce price lists, and companies that receive the price lists and schema can have their own style sheets to handle the data in a way that best suits their needs. Here are examples. ■ One company might put XML pricing information through a program to translate the XML into HTML so that it can post the price lists to its intranet. ■ A partner company might put the XML pricing information through a tool to create a marketing presentation. ■ Another company might read the XML pricing information into an application for processing. 1.5.2 SOAP Transport Protocol Client requests and web service responses are transmitted as Simple Object Access Protocol (SOAP) messages over HTTP to enable a completely interoperable exchange between clients and web services, all running on different platforms and at various locations on the Internet. HTTP is a familiar request-and-response standard for sending messages over the Internet, and SOAP is an XML-based protocol that follows the HTTP request-and-response model. The SOAP portion of a transported message does the following: ■ Defines an XML-based envelope to describe what is in the message and explain how to process the message ■ Includes XML-based encoding rules to express instances of application-defined data types within the message ■ Defines an XML-based convention for representing the request to the remote service and the resulting response 1.5.3 WSDL Standard Format The Web Services Description Language (WSDL) is a standardized XML format for describing network services. The description includes the name of the service, the location of the service, and ways to communicate with the service. WSDL service descriptions can be published on the Web. GlassFish Server provides a tool for Overview 1-11 Java EE Application Assembly and Deployment generating the WSDL specification of a web service that uses remote procedure calls to communicate with clients. 1.6 Java EE Application Assembly and Deployment A Java EE application is packaged into one or more standard units for deployment to any Java EE platform-compliant system. Each unit contains ■ A functional component or components, such as an enterprise bean, web page, servlet, or applet ■ An optional deployment descriptor that describes its content Once a Java EE unit has been produced, it is ready to be deployed. Deployment typically involves using a platform's deployment tool to specify location-specific information, such as a list of local users who can access it and the name of the local database. Once deployed on a local platform, the application is ready to run. 1.7 Java EE 7 APIs Figure 1–6 shows the relationships among the Java EE containers. Figure 1–6 Java EE Containers Client System Browser Java EE Server Web Container JavaServer Faces Servlet Database Application Client Container EJB Container Application Client EJB EJB Figure 1–7 shows the availability of the Java EE 7 APIs in the web container. 1-12 Java Platform, Enterprise Edition The Java EE Tutorial Figure 1–7 Java EE APIs in the Web Container Web Container WebSocket Java SE Java EE 7 APIs Servlet JavaServer Faces Concurrency Utilities Batch JSON-P Bean Validation EJB Lite EL JavaMail JSP Connectors Java Persistence JMS Management WS Metadata Web Services JACC JASPIC JAX-RS JAX-WS JSTL JTA CDI Dependency Injection New in Java EE 7 Figure 1–8 shows the availability of the Java EE 7 APIs in the EJB container. Overview 1-13 Java EE 7 APIs Figure 1–8 Java EE APIs in the EJB Container EJB Container Concurrency Utilities Java SE Batch JSON-P CDI Dependency Injection JavaMail Java Persistence JTA Connectors JMS Management WS Metadata Web Services JACC JASPIC Bean Validation JAX-RS JAX-WS EJB New in Java EE 7 Figure 1–9 shows the availability of the Java EE 7 APIs in the application client container. 1-14 Java Platform, Enterprise Edition The Java EE Tutorial Figure 1–9 Java EE APIs in the Application Client Container Application Client Container Java Persistence Java SE Java EE 7 APIs Management WS Metadata Web Services JSON-P JMS JAX-WS Bean Validation JavaMail CDI Dependency Injection Application Client New in Java EE 7 The following sections give a brief summary of the technologies required by the Java EE platform and the APIs used in Java EE applications. 1.7.1 Enterprise JavaBeans Technology An Enterprise JavaBeans (EJB) component, or enterprise bean, is a body of code that has fields and methods to implement modules of business logic. You can think of an enterprise bean as a building block that can be used alone or with other enterprise beans to execute business logic on the Java EE server. Enterprise beans are either session beans or message-driven beans. ■ A session bean represents a transient conversation with a client. When the client finishes executing, the session bean and its data are gone. ■ A message-driven bean combines features of a session bean and a message listener, allowing a business component to receive messages asynchronously. Commonly, these are Java Message Service (JMS) messages. In the Java EE 7 platform, new enterprise bean features include the following: ■ Asynchronous local session beans in EJB Lite ■ Nonpersistent timers in EJB Lite The Java EE 7 platform requires Enterprise JavaBeans 3.2 and Interceptors 1.2. The Interceptors specification is part of the EJB specification. 1.7.2 Java Servlet Technology Java Servlet technology lets you define HTTP-specific servlet classes. A servlet class extends the capabilities of servers that host applications accessed by way of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. In the Java EE 7 platform, new Java Servlet technology features include the following: ■ Nonblocking I/O Overview 1-15 Java EE 7 APIs ■ HTTP protocol upgrade The Java EE 7 platform requires Servlet 3.1. 1.7.3 JavaServer Faces Technology JavaServer Faces technology is a user interface framework for building web applications. The main components of JavaServer Faces technology are as follows: ■ A GUI component framework. ■ A flexible model for rendering components in different kinds of HTML or different markup languages and technologies. A Renderer object generates the markup to render the component and converts the data stored in a model object to types that can be represented in a view. ■ A standard RenderKit for generating HTML 4.01 markup. The following features support the GUI components: ■ ■ Input validation Event handling ■ Data conversion between model objects and components ■ Managed model object creation ■ ■ Page navigation configuration Expression Language (EL) All this functionality is available using standard Java APIs and XML-based configuration files. In the Java EE 7 platform, new features of JavaServer Faces technology include the following: ■ HTML5-friendly markup ■ ■ Faces Flows Resource library contracts The Java EE 7 platform requires JavaServer Faces 2.2 and Expression Language 3.0. 1.7.4 JavaServer Pages Technology JavaServer Pages (JSP) technology lets you put snippets of servlet code directly into a text-based document. A JSP page is a text-based document that contains two types of text: ■ ■ Static data, which can be expressed in any text-based format, such as HTML or XML JSP elements, which determine how the page constructs dynamic content For information about JSP technology, see the The Java EE 5 Tutorial at http://docs.oracle.com/javaee/5/tutorial/doc/. The Java EE 7 platform requires JavaServer Pages 2.3 for compatibility with earlier releases but recommends the use of Facelets as the display technology in new applications. 1-16 Java Platform, Enterprise Edition The Java EE Tutorial Java EE 7 APIs 1.7.5 JavaServer Pages Standard Tag Library The JavaServer Pages Standard Tag Library (JSTL) encapsulates core functionality common to many JSP applications. Instead of mixing tags from numerous vendors in your JSP applications, you use a single, standard set of tags. This standardization allows you to deploy your applications on any JSP container that supports JSTL and makes it more likely that the implementation of the tags is optimized. JSTL has iterator and conditional tags for handling flow control, tags for manipulating XML documents, internationalization tags, tags for accessing databases using SQL, and tags for commonly used functions. The Java EE 7 platform requires JSTL 1.2. 1.7.6 Java Persistence API The Java Persistence API (JPA) is a Java standards–based solution for persistence. Persistence uses an object/relational mapping approach to bridge the gap between an object-oriented model and a relational database. The Java Persistence API can also be used in Java SE applications outside of the Java EE environment. Java Persistence consists of the following areas: ■ ■ The Java Persistence API The query language ■ Object/relational mapping metadata The Java EE 7 platform requires Java Persistence API 2.1. 1.7.7 Java Transaction API The Java Transaction API (JTA) provides a standard interface for demarcating transactions. The Java EE architecture provides a default auto commit to handle transaction commits and rollbacks. An auto commit means that any other applications that are viewing data will see the updated data after each database read or write operation. However, if your application performs two separate database access operations that depend on each other, you will want to use the JTA API to demarcate where the entire transaction, including both operations, begins, rolls back, and commits. The Java EE 7 platform requires Java Transaction API 1.2. 1.7.8 Java API for RESTful Web Services The Java API for RESTful Web Services (JAX-RS) defines APIs for the development of web services built according to the Representational State Transfer (REST) architectural style. A JAX-RS application is a web application that consists of classes packaged as a servlet in a WAR file along with required libraries. The Java EE 7 platform requires JAX-RS 2.0. 1.7.9 Managed Beans Managed Beans, lightweight container-managed objects (POJOs) with minimal requirements, support a small set of basic services, such as resource injection, lifecycle callbacks, and interceptors. Managed Beans represent a generalization of the managed beans specified by JavaServer Faces technology and can be used anywhere in a Java EE application, not just in web modules. Overview 1-17 Java EE 7 APIs The Managed Beans specification is part of the Java EE 7 platform specification (JSR 342). The Java EE 7 platform requires Managed Beans 1.0. 1.7.10 Contexts and Dependency Injection for Java EE Contexts and Dependency Injection for Java EE (CDI) defines a set of contextual services, provided by Java EE containers, that make it easy for developers to use enterprise beans along with JavaServer Faces technology in web applications. Designed for use with stateful objects, CDI also has many broader uses, allowing developers a great deal of flexibility to integrate different kinds of components in a loosely coupled but typesafe way. The Java EE 7 platform requires CDI 1.1. 1.7.11 Dependency Injection for Java Dependency Injection for Java defines a standard set of annotations (and one interface) for use on injectable classes. In the Java EE platform, CDI provides support for Dependency Injection. Specifically, you can use injection points only in a CDI-enabled application. The Java EE 7 platform requires Dependency Injection for Java 1.0. 1.7.12 Bean Validation The Bean Validation specification defines a metadata model and API for validating data in JavaBeans components. Instead of distributing validation of data over several layers, such as the browser and the server side, you can define the validation constraints in one place and share them across the different layers. The Java EE 7 platform requires Bean Validation 1.1. 1.7.13 Java Message Service API The Java Message Service (JMS) API is a messaging standard that allows Java EE application components to create, send, receive, and read messages. It enables distributed communication that is loosely coupled, reliable, and asynchronous. In the platform, new features of JMS include the following. ■ A new, simplified API offers a simpler alternative to the previous API. This API includes a JMSContext object that combines the functions of a Connection and a Session. ■ All objects with a close method implement the java.lang.Autocloseable interface so that they can be used in a Java SE 7 try-with-resources statement. The Java EE 7 platform requires JMS 2.0. 1.7.14 Java EE Connector Architecture The Java EE Connector Architecture is used by tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged in to any Java EE product. A resource adapter is a software component that allows Java EE application components to access and interact with the underlying resource manager of the EIS. Because a resource adapter is specific to its resource manager, a different resource adapter typically exists for each type of database or enterprise information system. 1-18 Java Platform, Enterprise Edition The Java EE Tutorial Java EE 7 APIs The Java EE Connector Architecture also provides a performance-oriented, secure, scalable, and message-based transactional integration of Java EE platform–based web services with existing EISs that can be either synchronous or asynchronous. Existing applications and EISs integrated through the Java EE Connector Architecture into the Java EE platform can be exposed as XML-based web services by using JAX-WS and Java EE component models. Thus JAX-WS and the Java EE Connector Architecture are complementary technologies for enterprise application integration (EAI) and end-to-end business integration. The Java EE 7 platform requires Java EE Connector Architecture 1.7. 1.7.15 JavaMail API Java EE applications use the JavaMail API to send email notifications. The JavaMail API has two parts: ■ An application-level interface used by the application components to send mail ■ A service provider interface The Java EE platform includes the JavaMail API with a service provider that allows application components to send Internet mail. The Java EE 7 platform requires JavaMail 1.5. 1.7.16 Java Authorization Contract for Containers The Java Authorization Contract for Containers (JACC) specification defines a contract between a Java EE application server and an authorization policy provider. All Java EE containers support this contract. The JACC specification defines java.security.Permission classes that satisfy the Java EE authorization model. The specification defines the binding of container-access decisions to operations on instances of these permission classes. It defines the semantics of policy providers that use the new permission classes to address the authorization requirements of the Java EE platform, including the definition and use of roles. The Java EE 7 platform requires JACC 1.5. 1.7.17 Java Authentication Service Provider Interface for Containers The Java Authentication Service Provider Interface for Containers (JASPIC) specification defines a service provider interface (SPI) by which authentication providers that implement message authentication mechanisms may be integrated in client or server message-processing containers or runtimes. Authentication providers integrated through this interface operate on network messages provided to them by their calling containers. The authentication providers transform outgoing messages so that the source of each message can be authenticated by the receiving container, and the recipient of the message can be authenticated by the message sender. Authentication providers authenticate each incoming message and return to their calling containers the identity established as a result of the message authentication. The Java EE 7 platform requires JASPIC 1.1. 1.7.18 Java API for WebSocket WebSocket is an application protocol that provides full-duplex communications between two peers over TCP. The Java API for WebSocket enables Java EE applications Overview 1-19 Java EE 7 APIs in the Java Platform, Standard Edition 7 to create endpoints using annotations that specify the configuration parameters of the endpoint and designate its lifecycle callback methods. The WebSocket API is new to the Java EE 7 platform. The Java EE 7 platform requires Java API for WebSocket 1.0. 1.7.19 Java API for JSON Processing JSON is a text-based data exchange format derived from JavaScript that is used in web services and other connected applications. The Java API for JSON Processing (JSON-P) enables Java EE applications to parse, transform, and query JSON data using the object model or the streaming model. JSON-P is new to the Java EE 7 platform. The Java EE 7 platform requires JSON-P 1.0. 1.7.20 Concurrency Utilities for Java EE Concurrency Utilities for Java EE is a standard API for providing asynchronous capabilities to Java EE application components through the following types of objects: managed executor service, managed scheduled executor service, managed thread factory, and context service. Concurrency Utilities for Java EE is new to the Java EE 7 platform. The Java EE 7 platform requires Concurrency Utilities for Java EE 1.0. 1.7.21 Batch Applications for the Java Platform Batch jobs are tasks that can be executed without user interaction. The Batch Applications for the Java Platform specification is a batch framework that provides support for creating and running batch jobs in Java applications. The batch framework consists of a batch runtime, a job specification language based on XML, a Java API to interact with the batch runtime, and a Java API to implement batch artifacts. Batch Applications for the Java Platform is new to the Java EE 7 platform. The Java EE 7 platform requires Batch Applications for the Java Platform 1.0. 1.8 Java EE 7 APIs in the Java Platform, Standard Edition 7 Several APIs that are required by the Java EE 7 platform are included in the Java Platform, Standard Edition 7 (Java SE 7) and are thus available to Java EE applications. 1.8.1 Java Database Connectivity API The Java Database Connectivity (JDBC) API lets you invoke SQL commands from Java programming language methods. You use the JDBC API in an enterprise bean when you have a session bean access the database. You can also use the JDBC API from a servlet or a JSP page to access the database directly without going through an enterprise bean. The JDBC API has two parts: ■ An application-level interface used by the application components to access a database ■ A service provider interface to attach a JDBC driver to the Java EE platform The Java SE 7 platform requires JDBC 4.1. 1-20 Java Platform, Enterprise Edition The Java EE Tutorial 1.8.2 Java Naming and Directory Interface API Java EE 7 APIs in the Java Platform, Standard Edition 7 The Java Naming and Directory Interface (JNDI) API provides naming and directory functionality, enabling applications to access multiple naming and directory services, such as LDAP, DNS, and NIS. The JNDI API provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a Java EE application can store and retrieve any type of named Java object, allowing Java EE applications to coexist with many legacy applications and systems. Java EE naming services provide application clients, enterprise beans, and web components with access to a JNDI naming environment. A naming environment allows a component to be customized without the need to access or change the component's source code. A container implements the component's environment and provides it to the component as a JNDI naming context. The naming environment provides four logical namespaces: java:comp, java:module, java:app, and java:global for objects available to components, modules, or applications or shared by all deployed applications. A Java EE component can access named system-provided and user-defined objects. The names of some system-provided objects, such as a default JDBC DataSource object, a default JMS connection factory, and a JTA UserTransaction object, are stored in the java:comp namespace. The Java EE platform allows a component to name user-defined objects, such as enterprise beans, environment entries, JDBC DataSource objects, and messaging destinations. A Java EE component can also locate its environment naming context by using JNDI interfaces. A component can create a javax.naming.InitialContext object and look up the environment naming context in InitialContext under the name java:comp/env. A component's naming environment is stored directly in the environment naming context or in any of its direct or indirect subcontexts. 1.8.3 JavaBeans Activation Framework The JavaBeans Activation Framework (JAF) is used by the JavaMail API. JAF provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations. 1.8.4 Java API for XML Processing The Java API for XML Processing (JAXP), part of the Java SE platform, supports the processing of XML documents using Document Object Model (DOM), Simple API for XML (SAX), and Extensible Stylesheet Language Transformations (XSLT). JAXP enables applications to parse and transform XML documents independently of a particular XML-processing implementation. JAXP also provides namespace support, which lets you work with schemas that might otherwise have naming conflicts. Designed to be flexible, JAXP lets you use any XML-compliant parser or XSL processor from within your application and supports the Worldwide Web Consortium (W3C) schema. You can find information on the W3C schema at http://www.w3.org/XML/Schema. 1.8.5 Java Architecture for XML Binding The Java Architecture for XML Binding (JAXB) provides a convenient way to bind an XML schema to a representation in Java language programs. JAXB can be used independently or in combination with JAX-WS, in which case it provides a standard Overview 1-21 GlassFish Server Tools data binding for web service messages. All Java EE application client containers, web containers, and EJB containers support the JAXB API. The Java EE 7 platform requires JAXB 2.2. 1.8.6 Java API for XML Web Services The Java API for XML Web Services (JAX-WS) specification provides support for web services that use the JAXB API for binding XML data to Java objects. The JAX-WS specification defines client APIs for accessing web services as well as techniques for implementing web service endpoints. The Implementing Enterprise Web Services specification describes the deployment of JAX-WS-based services and clients. The EJB and Java Servlet specifications also describe aspects of such deployment. JAX-WS-based applications can be deployed using any of these deployment models. The JAX-WS specification describes the support for message handlers that can process message requests and responses. In general, these message handlers execute in the same container and with the same privileges and execution context as the JAX-WS client or endpoint component with which they are associated. These message handlers have access to the same JNDI namespace as their associated component. Custom serializers and deserializers, if supported, are treated in the same way as message handlers. The Java EE 7 platform requires JAX-WS 2.2. 1.8.7 SOAP with Attachments API for Java The SOAP with Attachments API for Java (SAAJ) is a low-level API on which JAX-WS depends. SAAJ enables the production and consumption of messages that conform to the SOAP 1.1 and 1.2 specifications and the SOAP with Attachments note. Most developers do not use the SAAJ API, instead using the higher-level JAX-WS API. 1.8.8 Java Authentication and Authorization Service The Java Authentication and Authorization Service (JAAS) provides a way for a Java EE application to authenticate and authorize a specific user or group of users to run it. JAAS is a Java programming language version of the standard Pluggable Authentication Module (PAM) framework, which extends the Java platform security architecture to support user-based authorization. 1.8.9 Common Annotations for the Java Platform Annotations enable a declarative style of programming in the Java platform. The Java EE 7 platform requires Common Annotations for the Java Platform 1.2. 1.9 GlassFish Server Tools GlassFish Server is a compliant implementation of the Java EE 7 platform. In addition to supporting all the APIs described in the previous sections, GlassFish Server includes a number of Java EE tools that are not part of the Java EE 7 platform but are provided as a convenience to the developer. This section briefly summarizes the tools that make up GlassFish Server. Instructions for starting and stopping GlassFish Server, starting the Administration Console, and starting and stopping the Java DB server are in Chapter 2, "Using the Tutorial Examples". 1-22 Java Platform, Enterprise Edition The Java EE Tutorial GlassFish Server Tools GlassFish Server contains the tools listed in Table 1–1. Basic usage information for many of the tools appears throughout the tutorial. For detailed information, see the online help in the GUI tools. Table 1–1 GlassFish Server Tools Tool Description Administration Console A web-based GUI GlassFish Server administration utility. Used to stop GlassFish Server and to manage users, resources, and applications. asadmin appclient capture-schema A command-line GlassFish Server administration utility. Used to start and stop GlassFish Server and to manage users, resources, and applications. A command-line tool that launches the application client container and invokes the client application packaged in the application client JAR file. A command-line tool to extract schema information from a database, producing a schema file that GlassFish Server can use for container-managed persistence. package-appclient A command-line tool to package the application client container libraries and JAR files. Java DB database A copy of the Java DB server. xjc schemagen wsimport wsgen A command-line tool to transform, or bind, a source XML schema to a set of JAXB content classes in the Java programming language. A command-line tool to create a schema file for each namespace referenced in your Java classes. A command-line tool to generate JAX-WS portable artifacts for a given WSDL file. After generation, these artifacts can be packaged in a WAR file with the WSDL and schema documents, along with the endpoint implementation, and then deployed. A command-line tool to read a web service endpoint class and generate all the required JAX-WS portable artifacts for web service deployment and invocation. Overview 1-23 GlassFish Server Tools 1-24 Java Platform, Enterprise Edition The Java EE Tutorial 2 2Using the Tutorial Examples [3] This chapter tells you everything you need to know to install, build, and run the examples. The following topics are addressed here: ■ ■ ■ ■ ■ ■ ■ Required Software Starting and Stopping GlassFish Server Starting the Administration Console Starting and Stopping the Java DB Server Building the Examples Tutorial Example Directory Structure Java EE 7 Maven Archetypes in the Tutorial ■ Getting the Latest Updates to the Tutorial ■ Debugging Java EE Applications 2.1 Required Software The following software is required to run the examples: ■ ■ ■ Java Platform, Standard Edition Java EE 7 Software Development Kit Java EE 7 Tutorial Component ■ NetBeans IDE ■ Apache Maven 2.1.1 Java Platform, Standard Edition To build, deploy, and run the examples, you need a copy of the Java Platform, Standard Edition Development Kit (JDK). You must use JDK 7 Update 65 or above or JDK 8 Update 20 or above. You can download JDK software from http://www.oracle.com/technetwork/java/javase/downloads/index.html. 2.1.2 Java EE 7 Software Development Kit GlassFish Server Open Source Edition 4.1 is targeted as the build and runtime environment for the tutorial examples. To build, deploy, and run the examples, you need a copy of GlassFish Server and, optionally, NetBeans IDE. To obtain GlassFish Using the Tutorial Examples 2-1 Required Software Server, you must install the Java EE 7 Software Development Kit (SDK) Update 1, which you can download from http://www.oracle.com/technetwork/java/javaee/downloads/index.html. Make sure that you download the Java EE 7 SDK Update 1, not the Java EE 7 Web Profile SDK Update 1. 2.1.2.1 SDK Installation Tips The Java EE 7 SDK Update 1 is installed from a ZIP file. It sets the default administration user name as admin with no required password. The Admin Port is set to 4848, and the HTTP Port is set to 8080. This tutorial refers to as-install-parent, the directory where you install GlassFish Server. For example, the default installation directory on Microsoft Windows is C:\glassfish4, so as-install-parent is C:\glassfish4. GlassFish Server itself is installed in as-install, the glassfish directory under as-install-parent. So on Microsoft Windows, as-install is C:\glassfish4\glassfish. After you install GlassFish Server, add the following directories to your PATH to avoid having to specify the full path when you use commands: as-install-parent/bin as-install/bin 2.1.3 Java EE 7 Tutorial Component The tutorial component, including the documentation and example source, is contained in the Java EE 7 SDK Update 1. Updates to the Java EE 7 Tutorial are published periodically. For details on obtaining these updates, see Getting the Latest Updates to the Tutorial. 2.1.4 NetBeans IDE The NetBeans integrated development environment (IDE) is a free, open-source IDE for developing Java applications, including enterprise applications. NetBeans IDE supports the Java EE platform. You can build, package, deploy, and run the tutorial examples from within NetBeans IDE. To run the tutorial examples, you need the latest version of NetBeans IDE. You can download NetBeans IDE from https://netbeans.org/downloads/index.html. Make sure that you download the Java EE bundle. 2.1.4.1 To Install NetBeans IDE without GlassFish Server When you install NetBeans IDE, do not install the version of GlassFish Server that comes with NetBeans IDE. To skip the installation of GlassFish Server, follow these steps. 1. On the first page of the NetBeans IDE Installer wizard, deselect the check box for GlassFish Server and click OK. 2. Accept both the License Agreement and the Junit License Agreement. A few of the tutorial examples use the Junit library, so you should install it. 3. Continue with the installation of NetBeans IDE. 2-2 Java Platform, Enterprise Edition The Java EE Tutorial Starting and Stopping GlassFish Server 2.1.4.2 To Add GlassFish Server as a Server Using NetBeans IDE To run the tutorial examples in NetBeans IDE, you must add your GlassFish Server as a server in NetBeans IDE. Follow these instructions to add GlassFish Server to NetBeans IDE. 1. From the Tools menu, choose Servers. 2. In the Servers wizard, click Add Server. 3. Under Choose Server, select GlassFish Server and click Next. 4. Under Server Location, browse to the location of the Java EE 7 SDK and click Next. 5. Under Domain Location, select Register Local Domain. 6. Click Finish. 2.1.5 Apache Maven Maven is a Java technology–based build tool developed by the Apache Software Foundation and is used to build, package, and deploy the tutorial examples. To run the tutorial examples from the command line, you need Maven 3.0 or higher. If you do not already have Maven, you can install it from: http://maven.apache.org Be sure to add the maven-install/bin directory to your path. If you are using NetBeans IDE to build and run the examples, it includes a copy of Maven. 2.2 Starting and Stopping GlassFish Server You can start and stop GlassFish Server using either NetBeans IDE or the command line. 2.2.1 To Start GlassFish Server Using NetBeans IDE 1. Click the Services tab. 2. Expand Servers. 3. Right-click the GlassFish Server instance and select Start. 2.2.2 To Stop GlassFish Server Using NetBeans IDE To stop GlassFish Server using NetBeans IDE, right-click the GlassFish Server instance and select Stop. 2.2.3 To Start GlassFish Server Using the Command Line To start GlassFish Server from the command line, open a terminal window or command prompt and execute the following: asadmin start-domain --verbose A domain is a set of one or more GlassFish Server instances managed by one administration server. The following elements are associated with a domain: ■ The GlassFish Server port number: The default is 8080. Using the Tutorial Examples 2-3 Starting the Administration Console ■ The administration server's port number: The default is 4848. ■ An administration user name and password: The default user name is admin, and by default no password is required. You specify these values when you install GlassFish Server. The examples in this tutorial assume that you chose the default ports as well as the default user name and lack of password. With no arguments, the start-domain command initiates the default domain, which is domain1. The --verbose flag causes all logging and debugging output to appear on the terminal window or command prompt. The output also goes into the server log, which is located in domain-dir/logs/server.log. 2.2.4 To Stop GlassFish Server Using the Command Line To stop GlassFish Server, open a terminal window or command prompt and execute: asadmin stop-domain domain1 2.3 Starting the Administration Console To administer GlassFish Server and manage users, resources, and Java EE applications, use the Administration Console tool. GlassFish Server must be running before you invoke the Administration Console. To start the Administration Console, open a browser at http://localhost:4848/. 2.3.1 To Start the Administration Console Using NetBeans IDE 1. Click the Services tab. 2. Expand Servers. 3. Right-click the GlassFish Server instance and select View Domain Admin Console. Note: NetBeans IDE uses your default web browser to open the Administration Console. 2.4 Starting and Stopping the Java DB Server GlassFish Server includes the Java DB database server. To start the Java DB server from the command line, open a terminal window or command prompt and execute: asadmin start-database To stop the Java DB server from the command line, open a terminal window or command prompt and execute: asadmin stop-database For information about the Java DB included with GlassFish Server, see http://www.oracle.com/technetwork/java/javadb/overview/index.html. 2-4 Java Platform, Enterprise Edition The Java EE Tutorial Tutorial Example Directory Structure 2.4.1 To Start the Database Server Using NetBeans IDE When you start GlassFish Server using NetBeans IDE, the database server starts automatically. If you ever need to start the server manually, however, follow these steps. 1. Click the Services tab. 2. Expand Databases. 3. Right-click Java DB and select Start Server. Next Steps To stop the database using NetBeans IDE, right-click Java DB and select Stop Server. 2.5 Building the Examples The tutorial examples are distributed with a configuration file for either NetBeans IDE or Maven. Either NetBeans IDE or Maven may be used to build, package, deploy, and run the examples. Directions for building the examples are provided in each chapter. 2.6 Tutorial Example Directory Structure To facilitate iterative development and keep application source files separate from compiled files, the tutorial examples use the Maven application directory structure. Each application module has the following structure: ■ ■ ■ ■ ■ pom.xml: Maven build file src/main/java: Java source files for the module src/main/resources: configuration files for the module, with the exception of web applications src/main/webapp: web pages, style sheets, tag files, and images (web applications only) src/main/webapp/WEB-INF: configuration files for web applications (web applications only) When an example has multiple application modules packaged into an EAR file, its submodule directories use the following naming conventions: ■ ■ ■ ■ ■ example-name-app-client: application clients example-name-ejb: enterprise bean JAR files example-name-war: web applications example-name-ear: enterprise applications example-name-common: library JAR containing components, classes, and files used by other modules The Maven build files (pom.xml) distributed with the examples contain goals to compile and assemble the application into the target directory and deploy the archive to GlassFish Server. Using the Tutorial Examples 2-5 Java EE 7 Maven Archetypes in the Tutorial 2.7 Java EE 7 Maven Archetypes in the Tutorial Some of the chapters have instructions on how to build an example application using Maven archetypes. Archetypes are templates for generating a particular Maven project. The Tutorial includes several Maven archetypes for generating Java EE 7 projects. 2.7.1 Installing the Tutorial Archetypes You must install the included Maven archetypes into your local Maven repository before you can create new projects based on the archetypes. You can install the archetypes using NetBeans IDE or Maven. 2.7.1.1 Installing the Tutorial Archetypes Using NetBeans IDE 1. From the File menu, choose Open Project. 2. In the Open Project dialog box, navigate to: tut-install/examples 3. Select the archetypes folder. 4. Click Open Project. 5. In the Projects tab, right-click the archetypes project and select Build. 2.7.1.2 Installing the Tutorial Archetypes Using Maven 1. In a terminal window, go to: tut-install/examples/archetypes/ 2. Enter the following command: mvn install 2.8 Getting the Latest Updates to the Tutorial Check for any updates to the tutorial by using the Update Tool included with the Java EE 7 SDK. 2.8.1 To Update the Tutorial Using NetBeans IDE 1. Open the Services tab in NetBeans IDE and expand Servers. 2. Right-click the GlassFish Server instance and select View Domain Update Center to display the Update Tool. 3. Select Available Updates in the tree to display a list of updated packages. 4. Look for updates to the Java EE 7 Tutorial (javaee-tutorial) package. 5. If there is an updated version of the Tutorial, select Java EE 7 Tutorial (javaee-tutorial) and click Install. 2.8.2 To Update the Tutorial Using the Command Line 1. Open a terminal window and enter the following command to display the Update Tool: updatetool 2-6 Java Platform, Enterprise Edition The Java EE Tutorial Debugging Java EE Applications 2. Select Available Updates in the tree to display a list of updated packages. 3. Look for updates to the Java EE 7 Tutorial (javaee-tutorial) package. 4. If there is an updated version of the Tutorial, select Java EE 7 Tutorial (javaee-tutorial) and click Install. 2.9 Debugging Java EE Applications This section explains how to determine what is causing an error in your application deployment or execution. 2.9.1 Using the Server Log One way to debug applications is to look at the server log in domain-dir/logs/server.log. The log contains output from GlassFish Server and your applications. You can log messages from any Java class in your application with System.out.println and the Java Logging APIs (documented at http://docs.oracle.com/javase/7/docs/technotes/guides/logging/index.html) and from web components with the ServletContext.log method. If you use NetBeans IDE, logging output appears in the Output window as well as the server log. If you start GlassFish Server with the --verbose flag, all logging and debugging output will appear on the terminal window or command prompt and the server log. If you start GlassFish Server in the background, debugging information is available only in the log. You can view the server log with a text editor or with the Administration Console log viewer. 2.9.1.1 To Use the Administration Console Log Viewer 1. Select the GlassFish Server node. 2. Click View Log Files. The log viewer opens and displays the last 40 entries. 3. To display other entries, follow these steps. a. Click Modify Search. b. Specify any constraints on the entries you want to see. c. Click Search at the top of the log viewer. 2.9.2 Using a Debugger GlassFish Server supports the Java Platform Debugger Architecture (JPDA). With JPDA, you can configure GlassFish Server to communicate debugging information using a socket. 2.9.2.1 To Debug an Application Using a Debugger 1. Follow these steps to enable debugging in GlassFish Server using the Administration Console: a. Expand the Configurations node, then expand the server-config node. b. Select the JVM Settings node. The default debug options are set to: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=9009 Using the Tutorial Examples 2-7 Debugging Java EE Applications As you can see, the default debugger socket port is 9009. You can change it to a port not in use by GlassFish Server or another service. c. Select the Debug Enabled check box. d. Click Save. 2. Stop GlassFish Server and then restart it. 2-8 Java Platform, Enterprise Edition The Java EE Tutorial Part II Part II Platform Basics Part II introduces platform basics. This part contains the following chapters: ■ ■ ■ Chapter 3, "Resource Creation" Chapter 4, "Injection" Chapter 5, "Packaging" 3 3Resource Creation [4] A resource is a program object that provides connections to such systems as database servers and messaging systems. Java EE components can access a wide variety of resources, including databases, mail sessions, Java Message Service objects, and URLs. The Java EE 7 platform provides mechanisms that allow you to access all these resources in a similar manner. This chapter examines several types of resources and explains how to create them. The following topics are addressed here: ■ Resources and JNDI Naming ■ DataSource Objects and Connection Pools ■ Creating Resources Administratively 3.1 Resources and JNDI Naming In a distributed application, components need to access other components and resources, such as databases. For example, a servlet might invoke remote methods on an enterprise bean that retrieves information from a database. In the Java EE platform, the Java Naming and Directory Interface (JNDI) naming service enables components to locate other components and resources. A resource is a program object that provides connections to systems, such as database servers and messaging systems. (A Java Database Connectivity resource is sometimes referred to as a data source.) Each resource object is identified by a unique, people-friendly name, called the JNDI name. For example, the JNDI name of the preconfigured JDBC resource for the Java DB database that is shipped with GlassFish Server is java:comp/DefaultDataSource. An administrator creates resources in a JNDI namespace. In GlassFish Server, you can use either the Administration Console or the asadmin command to create resources. Applications then use annotations to inject the resources. If an application uses resource injection, GlassFish Server invokes the JNDI API, and the application is not required to do so. However, it is also possible for an application to locate resources by making direct calls to the JNDI API. A resource object and its JNDI name are bound together by the naming and directory service. To create a new resource, a new name/object binding is entered into the JNDI namespace. You inject resources by using the @Resource annotation in an application. You can use a deployment descriptor to override the resource mapping that you specify in an annotation. Using a deployment descriptor allows you to change an application by repackaging it rather than by both recompiling the source files and repackaging. However, for most applications a deployment descriptor is not necessary. Resource Creation 3-1 DataSource Objects and Connection Pools 3.2 DataSource Objects and Connection Pools To store, organize, and retrieve data, most applications use a relational database. Java EE 7 components may access relational databases through the JDBC API. For information on this API, see http://docs.oracle.com/javase/7/docs/technotes/guides/jdbc/. In the JDBC API, databases are accessed by using DataSource objects. A DataSource has a set of properties that identify and describe the real-world data source that it represents. These properties include such information as the location of the database server, the name of the database, the network protocol to use to communicate with the server, and so on. In GlassFish Server, a data source is called a JDBC resource. Applications access a data source by using a connection, and a DataSource object can be thought of as a factory for connections to the particular data source that the DataSource instance represents. In a basic DataSource implementation, a call to the getConnection method returns a connection object that is a physical connection to the data source. A DataSource object may be registered with a JNDI naming service. If so, an application can use the JNDI API to access that DataSource object, which can then be used to connect to the data source it represents. DataSource objects that implement connection pooling also produce a connection to the particular data source that the DataSource class represents. The connection object that the getConnection method returns is a handle to a PooledConnection object rather than a physical connection. An application uses the connection object in the same way that it uses a connection. Connection pooling has no effect on application code except that a pooled connection, like all connections, should always be explicitly closed. When an application closes a connection that is pooled, the connection is returned to a pool of reusable connections. The next time getConnection is called, a handle to one of these pooled connections will be returned if one is available. Because connection pooling avoids creating a new physical connection every time one is requested, applications can run significantly faster. A JDBC connection pool is a group of reusable connections for a particular database. Because creating each new physical connection is time consuming, the server maintains a pool of available connections to increase performance. When it requests a connection, an application obtains one from the pool. When an application closes a connection, the connection is returned to the pool. Applications that use the Persistence API specify the DataSource object they are using in the jta-data-source element of the persistence.xml file: jdbc/MyOrderDB This is typically the only reference to a JDBC object for a persistence unit. The application code does not refer to any JDBC objects. 3.3 Creating Resources Administratively Before you deploy or run many applications, you may need to create resources for them. An application can include a glassfish-resources.xml file that can be used to define resources for that application and others. You can then use the asadmin command, specifying as the argument a file named glassfish-resources.xml, to create the resources administratively, as shown. asadmin add-resources glassfish-resources.xml 3-2 Java Platform, Enterprise Edition The Java EE Tutorial Creating Resources Administratively The glassfish-resources.xml file can be created in any project using NetBeans IDE or by hand. Some of the JMS examples use this approach to resource creation. A file for creating the resources needed for the JMS simple producer example can be found in the jms/simple/producer/src/main/setup directory. You could also use the asadmin create-jms-resource command to create the resources for this example. When you are done using the resources, you would use the asadmin list-jms-resources command to display their names, and the asadmin delete-jms-resource command to remove them, regardless of the way you created the resources. Resource Creation 3-3 Creating Resources Administratively 3-4 Java Platform, Enterprise Edition The Java EE Tutorial 4 4Injection [5] This chapter provides an overview of injection in Java EE and describes the two injection mechanisms provided by the platform: resource injection and dependency injection. Java EE provides injection mechanisms that enable your objects to obtain references to resources and other dependencies without having to instantiate them directly. You declare the required resources and other dependencies in your classes by decorating fields or methods with one of the annotations that mark the field as an injection point. The container then provides the required instances at runtime. Injection simplifies your code and decouples it from the implementations of its dependencies. The following topics are addressed here: ■ Resource Injection ■ Dependency Injection ■ The Main Differences between Resource Injection and Dependency Injection 4.1 Resource Injection Resource injection enables you to inject any resource available in the JNDI namespace into any container-managed object, such as a servlet, an enterprise bean, or a managed bean. For example, you can use resource injection to inject data sources, connectors, or custom resources available in the JNDI namespace. The type you use for the reference to the injected instance is usually an interface, which decouples your code from the implementation of the resource. For example, the following code injects a data source object that provides connections to the default Java DB database shipped with GlassFish Server: public class MyServlet extends HttpServlet { @Resource(name="java:comp/DefaultDataSource") private javax.sql.DataSource dsc; ... } In addition to field-based injection as in the preceding example, you can inject resources using method-based injection: public class MyServlet extends HttpServlet { private javax.sql.DataSource dsc; ... @Resource(name="java:comp/DefaultDataSource") public void setDsc(java.sql.DataSource ds) { dsc = ds; Injection 4-1 Dependency Injection } } To use method-based injection, the setter method must follow the JavaBeans conventions for property names: The method name must begin with set, have a void return type, and have only one parameter. The @Resource annotation is in the javax.annotation package and is defined in JSR 250 (Common Annotations for the Java Platform). Resource injection resolves by name, so it is not typesafe: the type of the resource object is not known at compile time, so you can get runtime errors if the types of the object and its reference do not match. 4.2 Dependency Injection Dependency injection enables you to turn regular Java classes into managed objects and to inject them into any other managed object. Using dependency injection, your code can declare dependencies on any managed object. The container automatically provides instances of these dependencies at the injection points at runtime, and it also manages the lifecycle of these instances for you. Dependency injection in Java EE defines scopes, which determine the lifecycle of the objects that the container instantiates and injects. For example, a managed object that is only needed to respond to a single client request (such as a currency converter) has a different scope than a managed object that is needed to process multiple client requests within a session (such as a shopping cart). You can define managed objects (also called managed beans) that you can later inject by assigning a scope to a regular class: @javax.enterprise.context.RequestScoped public class CurrencyConverter { ... } Use the javax.inject.Inject annotation to inject managed beans; for example: public class MyServlet extends HttpServlet { @Inject CurrencyConverter cc; ... } As opposed to resource injection, dependency injection is typesafe because it resolves by type. To decouple your code from the implementation of the managed bean, you can reference the injected instances using an interface type and have your managed bean implement that interface. For more information about dependency injection, see Chapter 23, "Introduction to Contexts and Dependency Injection for Java EE" and JSR 299 (Contexts and Dependency Injection for the Java EE Platform). 4.3 The Main Differences between Resource Injection and Dependency Injection Table 4–1 lists the main differences between resource injection and dependency injection. 4-2 Java Platform, Enterprise Edition The Java EE Tutorial The Main Differences between Resource Injection and Dependency Injection Table 4–1 Differences between Resource Injection and Dependency Injection Injection Mechanism Can Inject JNDI Resources Directly Can Inject Regular Classes Directly Resolves By Typesafe Resource Injection Dependency Injection Yes No No Yes Resource name Type No Yes Injection 4-3 The Main Differences between Resource Injection and Dependency Injection 4-4 Java Platform, Enterprise Edition The Java EE Tutorial 5 5Packaging [6] This chapter describes packaging. A Java EE application is packaged into one or more standard units for deployment to any Java EE platform–compliant system. Each unit contains a functional component or components, such as an enterprise bean, web page, servlet, or applet, and an optional deployment descriptor that describes its content. The following topics are addressed here: ■ ■ ■ ■ Packaging Applications Packaging Enterprise Beans Packaging Web Archives Packaging Resource Adapter Archives 5.1 Packaging Applications A Java EE application is delivered in a Java Archive (JAR) file, a Web Archive (WAR) file, or an Enterprise Archive (EAR) file. A WAR or EAR file is a standard JAR (.jar) file with a .war or .ear extension. Using JAR, WAR, and EAR files and modules makes it possible to assemble a number of different Java EE applications using some of the same components. No extra coding is needed; it is only a matter of assembling (or packaging) various Java EE modules into Java EE JAR, WAR, or EAR files. An EAR file (see Figure 5–1) contains Java EE modules and, optionally, deployment descriptors. A deployment descriptor, an XML document with an .xml extension, describes the deployment settings of an application, a module, or a component. Because deployment descriptor information is declarative, it can be changed without the need to modify the source code. At runtime, the Java EE server reads the deployment descriptor and acts upon the application, module, or component accordingly. Deployment information is most commonly specified in the source code by annotations. Deployment descriptors, if present, override what is specified in the source code. Packaging 5-1 Packaging Enterprise Beans Figure 5–1 EAR File Structure Assembly Root META-INF Web Module Application Client Module Resource Adapter Module EJB Module application.xml glassfish-application.xml (optional) The two types of deployment descriptors are Java EE and runtime. A Java EE deployment descriptor is defined by a Java EE specification and can be used to configure deployment settings on any Java EE-compliant implementation. A runtime deployment descriptor is used to configure Java EE implementation-specific parameters. For example, the GlassFish Server runtime deployment descriptor contains such information as the context root of a web application as well as GlassFish Server implementation-specific parameters, such as caching directives. The GlassFish Server runtime deployment descriptors are named glassfish-moduleType.xml and are located in the same META-INF directory as the Java EE deployment descriptor. A Java EE module consists of one or more Java EE components for the same container type and, optionally, one component deployment descriptor of that type. An enterprise bean module deployment descriptor, for example, declares transaction attributes and security authorizations for an enterprise bean. A Java EE module can be deployed as a stand-alone module. Java EE modules are of the following types: ■ EJB modules, which contain class files for enterprise beans and, optionally, an EJB deployment descriptor. EJB modules are packaged as JAR files with a .jar extension. ■ Web modules, which contain servlet class files, web files, supporting class files, GIF and HTML files, and, optionally, a web application deployment descriptor. Web modules are packaged as JAR files with a .war (web archive) extension. ■ Application client modules, which contain class files and, optionally, an application client deployment descriptor. Application client modules are packaged as JAR files with a .jar extension. ■ Resource adapter modules, which contain all Java interfaces, classes, native libraries, and, optionally, a resource adapter deployment descriptor. Together, these implement the Connector architecture (see Java EE Connector Architecture) for a particular EIS. Resource adapter modules are packaged as JAR files with an .rar (resource adapter archive) extension. 5.2 Packaging Enterprise Beans This section explains how enterprise beans can be packaged in EJB JAR or WAR modules. 5-2 Java Platform, Enterprise Edition The Java EE Tutorial Packaging Enterprise Beans 5.2.1 Packaging Enterprise Beans in EJB JAR Modules An EJB JAR file is portable and can be used for various applications. To assemble a Java EE application, package one or more modules, such as EJB JAR files, into an EAR file, the archive file that holds the application. When deploying the EAR file that contains the enterprise bean's EJB JAR file, you also deploy the enterprise bean to GlassFish Server. You can also deploy an EJB JAR that is not contained in an EAR file. Figure 5–2 shows the contents of an EJB JAR file. Figure 5–2 Structure of an Enterprise Bean JAR Assembly Root META-INF All .class files for this module ejb-jar.xml glassfish-ejb-jar.xml (optional) MANIFEST.MF 5.2.2 Packaging Enterprise Beans in WAR Modules Enterprise beans often provide the business logic of a web application. In these cases, packaging the enterprise bean within the web application's WAR module simplifies deployment and application organization. Enterprise beans may be packaged within a WAR module as Java programming language class files or within a JAR file that is bundled within the WAR module. To include enterprise bean class files in a WAR module, the class files should be in the WEB-INF/classes directory. To include a JAR file that contains enterprise beans in a WAR module, add the JAR to the WEB-INF/lib directory of the WAR module. WAR modules that contain enterprise beans do not require an ejb-jar.xml deployment descriptor. If the application uses ejb-jar.xml, it must be located in the WAR module's WEB-INF directory. JAR files that contain enterprise bean classes packaged within a WAR module are not considered EJB JAR files, even if the bundled JAR file conforms to the format of an EJB JAR file. The enterprise beans contained within the JAR file are semantically equivalent to enterprise beans located in the WAR module's WEB-INF/classes directory, and the environment namespace of all the enterprise beans are scoped to the WAR module. For example, suppose that a web application consists of a shopping cart enterprise bean, a credit card–processing enterprise bean, and a Java servlet front end. The shopping cart bean exposes a local, no-interface view and is defined as follows: package com.example.cart; @Stateless Packaging 5-3 Packaging Web Archives public class CartBean { ... } The credit card–processing bean is packaged within its own JAR file, cc.jar, exposes a local, no-interface view, and is defined as follows: package com.example.cc; @Stateless public class CreditCardBean { ... } The servlet, com.example.web.StoreServlet, handles the web front end and uses both CartBean and CreditCardBean. The WAR module layout for this application is as follows: WEB-INF/classes/com/example/cart/CartBean.class WEB-INF/classes/com/example/web/StoreServlet WEB-INF/lib/cc.jar WEB-INF/ejb-jar.xml WEB-INF/web.xml 5.3 Packaging Web Archives In the Java EE architecture, a web module is the smallest deployable and usable unit of web resources. A web module contains web components and static web content files, such as images, which are called web resources. A Java EE web module corresponds to a web application as defined in the Java Servlet specification. In addition to web components and web resources, a web module can contain other files: ■ ■ Server-side utility classes, such as shopping carts Client-side classes, such as utility classes A web module has a specific structure. The top-level directory of a web module is the document root of the application. The document root is where XHTML pages, client-side classes and archives, and static web resources, such as images, are stored. The document root contains a subdirectory named WEB-INF, which can contain the following files and directories: ■ ■ classes, a directory that contains server-side classes: servlets, enterprise bean class files, utility classes, and JavaBeans components lib, a directory that contains JAR files that contain enterprise beans, and JAR archives of libraries called by server-side classes ■ Deployment descriptors, such as web.xml (the web application deployment descriptor) and ejb-jar.xml (an EJB deployment descriptor) A web module needs a web.xml file if it uses JavaServer Faces technology, if it must specify certain kinds of security information, or if you want to override information specified by web component annotations. You can also create application-specific subdirectories (that is, package directories) in either the document root or the WEB-INF/classes/ directory. A web module can be deployed as an unpacked file structure or can be packaged in a JAR file known as a Web Archive (WAR) file. Because the contents and use of WAR files differ from those of JAR files, WAR file names use a .war extension. The web module just described is portable; you can deploy it into any web container that conforms to the Java Servlet specification. 5-4 Java Platform, Enterprise Edition The Java EE Tutorial Packaging Resource Adapter Archives You can provide a runtime deployment descriptor (DD) when you deploy a WAR on GlassFish Server, but it is not required under most circumstances. The runtime DD is an XML file that may contain such information as the context root of the web application, the mapping of the portable names of an application's resources to GlassFish Server resources, and the mapping of an application's security roles to users, groups, and principals defined in GlassFish Server. The GlassFish Server web application runtime DD, if used, is named glassfish-web.xml and is located in the WEB-INF directory. The structure of a web module that can be deployed on GlassFish Server is shown in Figure 5–3. Figure 5–3 Web Module Structure Assembly Root WEB-INF lib classes Web pages web.xml glassfish-web.xml (optional) Library archive files All server-side .class files for this web module 5.4 Packaging Resource Adapter Archives A Resource Adapter Archive (RAR) file stores XML files, Java classes, and other objects for Java EE Connector Architecture (JCA) applications. A resource adapter can be deployed on any Java EE server, much like a Java EE application. A RAR file can be contained in an Enterprise Archive (EAR) file, or it can exist as a separate file. The RAR file contains ■ A JAR file with the implementation classes of the resource adapter ■ An optional META-INF/ directory that can store an ra.xml file and/or an application server–specific deployment descriptor used for configuration purposes A RAR file can be deployed on the application server as a standalone component or as part of a larger application. In both cases, the adapter is available to all applications using a lookup procedure. Packaging 5-5 Packaging Resource Adapter Archives 5-6 Java Platform, Enterprise Edition The Java EE Tutorial Part III Part III The Web Tier Part III explores the technologies in the web tier. This part contains the following chapters: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ Chapter 6, "Getting Started with Web Applications" Chapter 7, "JavaServer Faces Technology" Chapter 8, "Introduction to Facelets" Chapter 9, "Expression Language" Chapter 10, "Using JavaServer Faces Technology in Web Pages" Chapter 11, "Using Converters, Listeners, and Validators" Chapter 12, "Developing with JavaServer Faces Technology" Chapter 13, "Using Ajax with JavaServer Faces Technology" Chapter 14, "Composite Components: Advanced Topics and an Example" Chapter 15, "Creating Custom UI Components and Other Custom Objects" Chapter 16, "Configuring JavaServer Faces Applications" Chapter 17, "Java Servlet Technology" Chapter 18, "Java API for WebSocket" Chapter 19, "JSON Processing" Chapter 20, "Internationalizing and Localizing Web Applications" 6 6Getting Started with Web Applications [7] This chapter introduces web applications, which typically use JavaServer Faces technology and/or Java Servlet technology. A web application is a dynamic extension of a web or application server. Web applications are of the following types: ■ ■ Presentation-oriented: A presentation-oriented web application generates interactive web pages containing various types of markup language (HTML, XHTML, XML, and so on) and dynamic content in response to requests. Development of presentation-oriented web applications is covered in Chapter 7, "JavaServer Faces Technology," through Chapter 17, "Java Servlet Technology." Service-oriented: A service-oriented web application implements the endpoint of a web service. Presentation-oriented applications are often clients of service-oriented web applications. Development of service-oriented web applications is covered in Chapter 28, "Building Web Services with JAX-WS," and Chapter 29, "Building RESTful Web Services with JAX-RS," in Part VI, "Web Services." The following topics are addressed here: ■ Web Applications ■ Web Application Lifecycle ■ A Web Module That Uses JavaServer Faces Technology: The hello1 Example ■ A Web Module That Uses Java Servlet Technology: The hello2 Example ■ ■ Configuring Web Applications Further Information about Web Applications 6.1 Web Applications In the Java EE platform, web components provide the dynamic extension capabilities for a web server. Web components can be Java servlets, web pages implemented with JavaServer Faces technology, web service endpoints, or JSP pages. Figure 6–1 illustrates the interaction between a web client and a web application that uses a servlet. The client sends an HTTP request to the web server. A web server that implements Java Servlet and JavaServer Pages technology converts the request into an HTTPServletRequest object. This object is delivered to a web component, which can interact with JavaBeans components or a database to generate dynamic content. The web component can then generate an HTTPServletResponse or can pass the request to another web component. A web component eventually generates a HTTPServletResponse object. The web server converts this object to an HTTP response and returns it to the client. Getting Started with Web Applications 6-1 Web Application Lifecycle Figure 6–1 Java Web Application Request Handling 1 HTTP Request HttpServlet Request 2 Web Components 5 3 Web Client HTTP Response 6 HttpServlet Response JavaBeans Components 4 4 Database Database Servlets are Java programming language classes that dynamically process requests and construct responses. Java technologies, such as JavaServer Faces and Facelets, are used for building interactive web applications. (Frameworks can also be used for this purpose.) Although servlets and JavaServer Faces and Facelets pages can be used to accomplish similar things, each has its own strengths. Servlets are best suited for service-oriented applications (web service endpoints can be implemented as servlets) and the control functions of a presentation-oriented application, such as dispatching requests and handling nontextual data. JavaServer Faces and Facelets pages are more appropriate for generating text-based markup, such as XHTML, and are generally used for presentation-oriented applications. Web components are supported by the services of a runtime platform called a web container. A web container provides such services as request dispatching, security, concurrency, and lifecycle management. A web container also gives web components access to such APIs as naming, transactions, and email. Certain aspects of web application behavior can be configured when the application is installed, or deployed, to the web container. The configuration information can be specified using Java EE annotations or can be maintained in a text file in XML format called a web application deployment descriptor (DD). A web application DD must conform to the schema described in the Java Servlet specification. This chapter gives a brief overview of the activities involved in developing web applications. First, it summarizes the web application lifecycle and explains how to package and deploy very simple web applications on GlassFish Server. The chapter then moves on to configuring web applications and discusses how to specify the most commonly used configuration parameters. 6.2 Web Application Lifecycle A web application consists of web components; static resource files, such as images and cascading style sheets (CSS); and helper classes and libraries. The web container provides many supporting services that enhance the capabilities of web components and make them easier to develop. However, because a web application must take these services into account, the process for creating and running a web application is different from that of traditional stand-alone Java classes. The process for creating, deploying, and executing a web application can be summarized as follows: 1. Develop the web component code. 2. Develop the web application deployment descriptor, if necessary. 3. Compile the web application components and helper classes referenced by the components. 6-2 Java Platform, Enterprise Edition The Java EE Tutorial A Web Module That Uses JavaServer Faces Technology: The hello1 Example 4. Optionally, package the application into a deployable unit. 5. Deploy the application into a web container. 6. Access a URL that references the web application. Developing web component code is covered in the later chapters. Steps 2 through 4 are expanded on in the following sections and illustrated with a Hello, World–style, presentation-oriented application. This application allows a user to enter a name into an HTML form and then displays a greeting after the name is submitted. The Hello application contains two web components that generate the greeting and the response. This chapter discusses the following simple applications: ■ ■ hello1, a JavaServer Faces technology–based application that uses two XHTML pages and a managed bean hello2, a servlet-based web application in which the components are implemented by two servlet classes The applications are used to illustrate tasks involved in packaging, deploying, configuring, and running an application that contains web components. 6.3 A Web Module That Uses JavaServer Faces Technology: The hello1 Example The hello1 application is a web module that uses JavaServer Faces technology to display a greeting and response. You can use a text editor to view the application files, or you can use NetBeans IDE. The source code for this application is in the tut-install/examples/web/jsf/hello1/ directory. 6.3.1 To View the hello1 Web Module Using NetBeans IDE 1. From the File menu, choose Open Project. 2. In the Open Project dialog box, navigate to: tut-install/examples/web/jsf 3. Select the hello1 folder and click Open Project. 4. Expand the Web Pages node and double-click the index.xhtml file to view it in the editor. The index.xhtml file is the default landing page for a Facelets application. In a typical Facelets application, web pages are created in XHTML. For this application, the page uses simple tag markup to display a form with a graphic image, a header, a field, and two command buttons: Facelets Hello Greeting

Hello, my name is Duke. What's yours?

...
The most complex element on the page is the inputText field. The maxlength attribute specifies the maximum length of the field. The required attribute specifies that the field must be filled out; the requiredMessage attribute provides the error message to be displayed if the field is left empty. The title attribute provides the text to be used by screen readers for the visually disabled. Finally, the value attribute contains an expression that will be provided by the Hello managed bean. The web page connects to the Hello managed bean through the Expression Language (EL) value expression #{hello.name}, which retrieves the value of the name property from the managed bean. Note the use of hello to reference the managed bean Hello. If no name is specified in the @Named annotation of the managed bean, the managed bean is always accessed with the first letter of the class name in lowercase. The Submit commandButton element specifies the action as response, meaning that when the button is clicked, the response.xhtml page is displayed. 5. Double-click the response.xhtml file to view it. The response page appears. Even simpler than the greeting page, the response page contains a graphic image, a header that displays the expression provided by the managed bean, and a single button whose action element transfers you back to the index.xhtml page: Facelets Hello Response

Hello, #{hello.name}!

6-4 Java Platform, Enterprise Edition The Java EE Tutorial A Web Module That Uses JavaServer Faces Technology: The hello1 Example 6. Expand the Source Packages node, then the javaeetutorial.hello1 node. 7. Double-click the Hello.java file to view it. The Hello class, called a managed bean class, provides getter and setter methods for the name property used in the Facelets page expressions. By default, the expression language refers to the class name, with the first letter in lowercase (hello.name). package javaeetutorial.hello1; import javax.enterprise.context.RequestScoped; import javax.inject.Named; @Named @RequestScoped public class Hello { private String name; public Hello() { } public String getName() { return name; } public void setName(String user_name) { this.name = user_name; } } If you use the default name for the bean class, you can specify @Model as the annotation instead of having to specify both @Named and @RequestScoped. The @Model annotation is called a stereotype, a term for an annotation that encapsulates other annotations. It is described later in Using Stereotypes in CDI Applications. Some examples will use @Model where it is appropriate. 8. Under the Web Pages node, expand the WEB-INF node and double-click the web.xml file to view it. The web.xml file contains several elements that are required for a Facelets application. All of the following are created automatically when you use NetBeans IDE to create an application. ■ A context parameter specifying the project stage: javax.faces.PROJECT_STAGE Development A context parameter provides configuration information needed by a web application. An application can define its own context parameters. In addition, JavaServer Faces technology and Java Servlet technology define context parameters that an application can use. ■ A servlet element and its servlet-mapping element specifying the FacesServlet. All files with the .xhtml suffix will be matched: Getting Started with Web Applications 6-5 A Web Module That Uses JavaServer Faces Technology: The hello1 Example Faces Servlet javax.faces.webapp.FacesServlet 1 Faces Servlet *.xhtml ■ A welcome-file-list element specifying the location of the landing page: index.xhtml 6.3.1.1 Introduction to Scopes In the Hello.java class, the annotations javax.inject.Named and javax.enterprise.context.RequestScoped identify the class as a managed bean using request scope. Scope defines how application data persists and is shared. The most commonly used scopes in JavaServer Faces applications are the following: ■ Request (@RequestScoped): Request scope persists during a single HTTP request in a web application. In an application like hello1, in which the application consists of a single request and response, the bean uses request scope. ■ Session (@SessionScoped): Session scope persists across multiple HTTP requests in a web application. When an application consists of multiple requests and responses where data needs to be maintained, beans use session scope. ■ Application (@ApplicationScoped): Application scope persists across all users' interactions with a web application. For more information on scopes in JavaServer Faces technology, see Using Managed Bean Scopes. 6.3.2 Packaging and Deploying the hello1 Web Module A web module must be packaged into a WAR in certain deployment scenarios and whenever you want to distribute the web module. You can package a web module into a WAR file by using Maven or by using the IDE tool of your choice. This tutorial shows you how to use NetBeans IDE or Maven to build, package, and deploy the hello1 sample application. You can deploy a WAR file to GlassFish Server by: ■ Using NetBeans IDE ■ Using the asadmin command ■ Using the Administration Console ■ Copying the WAR file into the domain-dir/autodeploy/ directory Throughout the tutorial, you will use NetBeans IDE or Maven for packaging and deploying. 6.3.2.1 To Build and Package the hello1 Web Module Using NetBeans IDE 1. Start GlassFish Server as described in To Start GlassFish Server Using NetBeans IDE, if you have not already done so. 2. From the File menu, choose Open Project. 6-6 Java Platform, Enterprise Edition The Java EE Tutorial A Web Module That Uses JavaServer Faces Technology: The hello1 Example 3. In the Open Project dialog box, navigate to: tut-install/examples/web/jsf 4. Select the hello1 folder. 5. Click Open Project. 6. In the Projects tab, right-click the hello1 project and select Build. This command deploys the project to the server. 6.3.2.2 To Build and Package the hello1 Web Module Using Maven 1. Start GlassFish Server as described in To Start GlassFish Server Using the Command Line, if you have not already done so. 2. In a terminal window, go to: tut-install/examples/web/jsf/hello1/ 3. Enter the following command: mvn install This command spawns any necessary compilations and creates the WAR file in tut-install/examples/web/jsf/hello1/target/. It then deploys the project to the server. 6.3.3 Viewing Deployed Web Modules GlassFish Server provides two ways to view the deployed web modules: the Administration Console and the asadmin command. You can also use NetBeans IDE to view deployed modules. 6.3.3.1 To View Deployed Web Modules Using the Administration Console 1. Open the URL http://localhost:4848/ in a browser. 2. Select the Applications node. The deployed web modules appear in the Deployed Applications table. 6.3.3.2 To View Deployed Web Modules Using the asadmin Command Enter the following command: asadmin list-applications 6.3.3.3 To View Deployed Web Modules Using NetBeans IDE 1. In the Services tab, expand the Servers node, then expand the GlassFish Server node. 2. Expand the Applications node to view the deployed modules. 6.3.4 Running the Deployed hello1 Web Module Now that the web module is deployed, you can view it by opening the application in a web browser. By default, the application is deployed to host localhost on port 8080. The context root of the web application is hello1. 1. Open a web browser. 2. Enter the following URL: Getting Started with Web Applications 6-7 A Web Module That Uses Java Servlet Technology: The hello2 Example http://localhost:8080/hello1/ 3. In the field, enter your name and click Submit. The response page displays the name you submitted. Click Back to try again. 6.3.4.1 Dynamic Reloading of Deployed Modules If dynamic reloading is enabled, you do not have to redeploy an application or module when you change its code or deployment descriptors. All you have to do is copy the changed pages or class files into the deployment directory for the application or module. The deployment directory for a web module named context-root is domain-dir/applications/context-root. The server checks for changes periodically and redeploys the application, automatically and dynamically, with the changes. This capability is useful in a development environment because it allows code changes to be tested quickly. Dynamic reloading is not recommended for a production environment, however, because it may degrade performance. In addition, whenever a reload takes place, the sessions at that time become invalid, and the client must restart the session. In GlassFish Server, dynamic reloading is enabled by default. 6.3.5 Undeploying the hello1 Web Module You can undeploy web modules and other types of enterprise applications by using either NetBeans IDE or Maven. 6.3.5.1 To Undeploy the hello1 Web Module Using NetBeans IDE 1. In the Services tab, expand the Servers node, then expand the GlassFish Server node. 2. Expand the Applications node. 3. Right-click the hello1 module and select Undeploy. 4. To delete the class files and other build artifacts, go back to the Projects tab, right-click the project, and select Clean. 6.3.5.2 To Undeploy the hello1 Web Module Using Maven 1. In a terminal window, go to: tut-install/examples/web/jsf/hello1/ 2. Enter the following command: mvn cargo:undeploy 3. To delete the class files and other build artifacts, enter the following command: mvn clean 6.4 A Web Module That Uses Java Servlet Technology: The hello2 Example The hello2 application is a web module that uses Java Servlet technology to display a greeting and response. You can use a text editor to view the application files, or you can use NetBeans IDE. 6-8 Java Platform, Enterprise Edition The Java EE Tutorial A Web Module That Uses Java Servlet Technology: The hello2 Example The source code for this application is in the tut-install/examples/web/servlet/hello2/ directory. 6.4.1 Mapping URLs to Web Components When it receives a request, the web container must determine which web component should handle the request. The web container does so by mapping the URL path contained in the request to a web application and a web component. A URL path contains the context root and, optionally, a URL pattern: http://host:port/context-root[/url-pattern] You set the URL pattern for a servlet by using the @WebServlet annotation in the servlet source file. For example, the GreetingServlet.java file in the hello2 application contains the following annotation, specifying the URL pattern as /greeting: @WebServlet("/greeting") public class GreetingServlet extends HttpServlet { ... This annotation indicates that the URL pattern /greeting follows the context root. Therefore, when the servlet is deployed locally, it is accessed with the following URL: http://localhost:8080/hello2/greeting To access the servlet by using only the context root, specify "/" as the URL pattern. 6.4.2 Examining the hello2 Web Module The hello2 application behaves almost identically to the hello1 application, but it is implemented using Java Servlet technology instead of JavaServer Faces technology. You can use a text editor to view the application files, or you can use NetBeans IDE. 6.4.2.1 To View the hello2 Web Module Using NetBeans IDE 1. From the File menu, choose Open Project. 2. In the Open Project dialog box, navigate to: tut-install/examples/web/servlet 3. Select the hello2 folder and click Open Project. 4. Expand the Source Packages node, then expand the javaeetutorial.hello2 node. 5. Double-click the GreetingServlet.java file to view it. This servlet overrides the doGet method, implementing the GET method of HTTP. The servlet displays a simple HTML greeting form whose Submit button, like that of hello1, specifies a response page for its action. The following excerpt begins with the @WebServlet annotation, which specifies the URL pattern relative to the context root: @WebServlet("/greeting") public class GreetingServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Getting Started with Web Applications 6-9 A Web Module That Uses Java Servlet Technology: The hello2 Example response.setContentType("text/html"); response.setBufferSize(8192); try (PrintWriter out = response.getWriter()) { out.println("" + "Servlet Hello"); // then write the data of the response out.println("" + "" + "
" + "

Hello, my name is Duke. What's yours?

" + "" + "

" + "" + "" + "
"); String username = request.getParameter("username"); if (username != null && username.length()> 0) { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/response"); if (dispatcher != null) { dispatcher.include(request, response); } } out.println(""); } } ... 6. Double-click the ResponseServlet.java file to view it. This servlet also overrides the doGet method, displaying only the response. The following excerpt begins with the @WebServlet annotation, which specifies the URL pattern relative to the context root: @WebServlet("/response") public class ResponseServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try (PrintWriter out = response.getWriter()) { // then write the data of the response String username = request.getParameter("username"); if (username != null && username.length()> 0) { out.println("

Hello, " + username + "!

"); } } } ... 6-10 Java Platform, Enterprise Edition The Java EE Tutorial Configuring Web Applications 6.4.3 Running the hello2 Example You can use either NetBeans IDE or Maven to build, package, deploy, and run the hello2 example. 6.4.3.1 To Run the hello2 Example Using NetBeans IDE 1. Start GlassFish Server as described in To Start GlassFish Server Using NetBeans IDE, if you have not already done so. 2. From the File menu, choose Open Project. 3. In the Open Project dialog box, navigate to: tut-install/examples/web/servlet 4. Select the hello2 folder. 5. Click Open Project. 6. In the Projects tab, right-click the hello2 project and select Build to package and deploy the project. 7. In a web browser, open the following URL: http://localhost:8080/hello2/greeting The URL specifies the context root, followed by the URL pattern. The application looks much like the hello1 application. The major difference is that after you click Submit the response appears below the greeting, not on a separate page. 6.4.3.2 To Run the hello2 Example Using Maven 1. Start GlassFish Server as described in To Start GlassFish Server Using the Command Line, if you have not already done so. 2. In a terminal window, go to: tut-install/examples/web/servlet/hello2/ 3. Enter the following command: mvn install This target builds the WAR file, copies it to the tut-install/examples/web/hello2/target/ directory, and deploys it. 4. In a web browser, open the following URL: http://localhost:8080/hello2/greeting The URL specifies the context root, followed by the URL pattern. The application looks much like the hello1 application. The major difference is that after you click Submit the response appears below the greeting, not on a separate page. 6.5 Configuring Web Applications This section describes the following tasks involved with configuring web applications: ■ Setting context parameters Getting Started with Web Applications 6-11 Configuring Web Applications ■ Declaring welcome files ■ Mapping errors to error screens ■ Declaring resource references 6.5.1 Setting Context Parameters The web components in a web module share an object that represents their application context. You can pass context parameters to the context, or you can pass initialization parameters to a servlet. Context parameters are available to the entire application. For information on initialization parameters, see Creating and Initializing a Servlet. 6.5.1.1 To Add a Context Parameter Using NetBeans IDE These steps apply generally to web applications but do not apply specifically to the examples in this chapter. 1. Open the project. 2. Expand the project's node in the Projects tree. 3. Expand the Web Pages node and then the WEB-INF node. 4. Double-click web.xml. If the project does not have a web.xml file, create one by following the steps in To Create a web.xml File Using NetBeans IDE. 5. Click General at the top of the editor window. 6. Expand the Context Parameters node. 7. Click Add. 8. In the Add Context Parameter dialog box, in the Parameter Name field, enter the name that specifies the context object. 9. In the Parameter Value field, enter the parameter to pass to the context object. 10. Click OK. 6.5.1.2 To Create a web.xml File Using NetBeans IDE 1. From the File menu, choose New File. 2. In the New File wizard, select the Web category, then select Standard Deployment Descriptor under File Types. 3. Click Next. 4. Click Finish. A basic web.xml file appears in web/WEB-INF/. 6.5.2 Declaring Welcome Files The welcome files mechanism allows you to specify a list of files that the web container can append to a request for a URL (called a valid partial request) that is not mapped to a web component. For example, suppose that you define a welcome file welcome.html. When a client requests a URL such as host:port/webapp/directory, where directory is not mapped to a servlet or XHTML page, the file host:port/webapp/directory/welcome.html is returned to the client. 6-12 Java Platform, Enterprise Edition The Java EE Tutorial Configuring Web Applications If a web container receives a valid partial request, the web container examines the welcome file list, appends to the partial request each welcome file in the order specified, and checks whether a static resource or servlet in the WAR is mapped to that request URL. The web container then sends the request to the first resource that matches in the WAR. If no welcome file is specified, GlassFish Server will use a file named index.html as the default welcome file. If there is no welcome file and no file named index.html, GlassFish Server returns a directory listing. You specify welcome files in the web.xml file. The welcome file specification for the hello1 example looks like this: index.xhtml A specified welcome file must not have a leading or trailing slash (/). The hello2 example does not specify a welcome file, because the URL request is mapped to the GreetingServlet web component through the URL pattern /greeting. 6.5.3 Mapping Errors to Error Screens When an error occurs during execution of a web application, you can have the application display a specific error screen according to the type of error. In particular, you can specify a mapping between the status code returned in an HTTP response or a Java programming language exception returned by any web component and any type of error screen. You can have multiple error-page elements in your deployment descriptor. Each element identifies a different error that causes an error page to open. This error page can be the same for any number of error-page elements. 6.5.3.1 To Set Up Error Mapping Using NetBeans IDE These steps apply generally to web applications but do not apply specifically to the examples in this chapter. 1. Open the project. 2. Expand the project's node in the Projects tab. 3. Expand the Web Pages node and then the WEB-INF node. 4. Double-click web.xml. If the project does not have a web.xml file, create one by following the steps in To Create a web.xml File Using NetBeans IDE. 5. Click Pages at the top of the editor window. 6. Expand the Error Pages node. 7. Click Add. 8. In the Add Error Page dialog box, click Browse to locate the page that you want to act as the error page. 9. Specify either an error code or an exception type. ■ To specify an error code, in the Error Code field enter the HTTP status code that will cause the error page to be opened, or leave the field blank to include all error codes. Getting Started with Web Applications 6-13 Configuring Web Applications ■ To specify an exception type, in the Exception Type field enter the exception that will cause the error page to load. To specify all throwable errors and exceptions, enter java.lang.Throwable. 10. Click OK. 6.5.4 Declaring Resource References If your web component uses such objects as enterprise beans, data sources, or web services, you use Java EE annotations to inject these resources into your application. Annotations eliminate a lot of the boilerplate lookup code and configuration elements that previous versions of Java EE required. Although resource injection using annotations can be more convenient for the developer, there are some restrictions on using it in web applications. First, you can inject resources only into container-managed objects, because a container must have control over the creation of a component so that it can perform the injection into a component. As a result, you cannot inject resources into such objects as simple JavaBeans components. However, managed beans are managed by the container; therefore, they can accept resource injections. Components that can accept resource injections are listed in Table 6–1. This section explains how to use a couple of the annotations supported by a web container to inject resources. Chapter 38, "Running the Persistence Examples", explains how web applications use annotations supported by the Java Persistence API. Chapter 48, "Getting Started Securing Web Applications", explains how to use annotations to specify information about securing web applications. See Chapter 52, "Resource Adapters and Contracts", for more information on resources. Table 6–1 Web Components That Accept Resource Injections Component Interface/Class Servlets javax.servlet.Servlet Servlet filters javax.servlet.ServletFilter Event listeners javax.servlet.ServletContextListener javax.servlet.ServletContextAttributeListener javax.servlet.ServletRequestListener javax.servlet.ServletRequestAttributeListener javax.servlet.http.HttpSessionListener javax.servlet.http.HttpSessionAttributeListener javax.servlet.http.HttpSessionBindingListener Managed beans Plain Old Java Objects 6.5.4.1 Declaring a Reference to a Resource The @Resource annotation is used to declare a reference to a resource, such as a data source, an enterprise bean, or an environment entry. The @Resource annotation is specified on a class, a method, or a field. The container is responsible for injecting references to resources declared by the @Resource annotation and mapping it to the proper JNDI resources. In the following example, the @Resource annotation is used to inject a data source into a component that needs to make a connection to the data source, as is done when using JDBC technology to access a relational database: 6-14 Java Platform, Enterprise Edition The Java EE Tutorial Further Information about Web Applications @Resource javax.sql.DataSource catalogDS; public getProductsByCategory() { // get a connection and execute the query Connection conn = catalogDS.getConnection(); ... } The container injects this data source prior to the component's being made available to the application. The data source JNDI mapping is inferred from the field name, catalogDS, and the type, javax.sql.DataSource. If you have multiple resources that you need to inject into one component, you need to use the @Resources annotation to contain them, as shown by the following example: @Resources ({ @Resource(name="myDB" type=javax.sql.DataSource.class), @Resource(name="myMQ" type=javax.jms.ConnectionFactory.class) }) The web application examples in this tutorial use the Java Persistence API to access relational databases. This API does not require you to explicitly create a connection to a data source. Therefore, the examples do not use the @Resource annotation to inject a data source. However, this API supports the @PersistenceUnit and @PersistenceContext annotations for injecting EntityManagerFactory and EntityManager instances, respectively. Chapter 38, "Running the Persistence Examples" describes these annotations and the use of the Java Persistence API in web applications. 6.5.4.2 Declaring a Reference to a Web Service The @WebServiceRef annotation provides a reference to a web service. The following example shows uses the @WebServiceRef annotation to declare a reference to a web service. WebServiceRef uses the wsdlLocation element to specify the URI of the deployed service's WSDL file: ... import javax.xml.ws.WebServiceRef; ... public class ResponseServlet extends HTTPServlet { @WebServiceRef(wsdlLocation="http://localhost:8080/helloservice/hello?wsdl") static HelloService service; 6.6 Further Information about Web Applications For more information on web applications, see ■ ■ JavaServer Faces 2.2 specification: http://jcp.org/en/jsr/detail?id=344 Java Servlet 3.1 specification: http://jcp.org/en/jsr/detail?id=340 Getting Started with Web Applications 6-15 Further Information about Web Applications 6-16 Java Platform, Enterprise Edition The Java EE Tutorial 7 7JavaServer Faces Technology [8] JavaServer Faces technology is a server-side component framework for building Java technology–based web applications. JavaServer Faces technology consists of the following: ■ An API for representing components and managing their state; handling events, server-side validation, and data conversion; defining page navigation; supporting internationalization and accessibility; and providing extensibility for all these features ■ Tag libraries for adding components to web pages and for connecting components to server-side objects JavaServer Faces technology provides a well-defined programming model and various tag libraries. The tag libraries contain tag handlers that implement the component tags. These features significantly ease the burden of building and maintaining web applications with server-side user interfaces (UIs). With minimal effort, you can complete the following tasks. ■ Create a web page. ■ Drop components onto a web page by adding component tags. ■ Bind components on a page to server-side data. ■ Wire component-generated events to server-side application code. ■ ■ Save and restore application state beyond the life of server requests. Reuse and extend components through customization. This chapter provides an overview of JavaServer Faces technology. After explaining what a JavaServer Faces application is and reviewing some of the primary benefits of using JavaServer Faces technology, this chapter describes the process of creating a simple JavaServer Faces application. This chapter also introduces the JavaServer Faces lifecycle by describing the example JavaServer Faces application and its progression through the lifecycle stages. The following topics are addressed here: ■ What Is a JavaServer Faces Application? ■ JavaServer Faces Technology Benefits ■ A Simple JavaServer Faces Application ■ User Interface Component Model ■ Navigation Model ■ The Lifecycle of a JavaServer Faces Application JavaServer Faces Technology 7-1 What Is a JavaServer Faces Application? ■ ■ Partial Processing and Partial Rendering Further Information about JavaServer Faces Technology 7.1 What Is a JavaServer Faces Application? The functionality provided by a JavaServer Faces application is similar to that of any other Java web application. A typical JavaServer Faces application includes the following parts. ■ A set of web pages in which components are laid out. ■ A set of tags to add components to the web page. ■ A set of managed beans, which are lightweight, container-managed objects (POJOs). In a JavaServer Faces application, managed beans serve as backing beans, which define properties and functions for UI components on a page. ■ A web deployment descriptor (web.xml file). ■ Optionally, one or more application configuration resource files, such as a faces-config.xml file, which can be used to define page navigation rules and configure beans and other custom objects, such as custom components. ■ Optionally, a set of custom objects, which can include custom components, validators, converters, or listeners, created by the application developer. ■ Optionally, a set of custom tags for representing custom objects on the page. Figure 7–1 shows the interaction between client and server in a typical JavaServer Faces application. In response to a client request, a web page is rendered by the web container that implements JavaServer Faces technology. Figure 7–1 Responding to a Client Request for a JavaServer Faces Page Web Container myfacelet.xhtml Browser Access page (HTTP Request) Generates Component Tree myView Renders HTML (HTTP Response) The web page, myfacelet.xhtml, is built using JavaServer Faces component tags. Component tags are used to add components to the view (represented by myView in the diagram), which is the server-side representation of the page. In addition to components, the web page can also reference objects, such as the following: ■ Any event listeners, validators, and converters that are registered on the components ■ The JavaBeans components that capture the data and process the application-specific functionality of the components 7-2 Java Platform, Enterprise Edition The Java EE Tutorial JavaServer Faces Technology Benefits On request from the client, the view is rendered as a response. Rendering is the process whereby, based on the server-side view, the web container generates output, such as HTML or XHTML, that can be read by the client, such as a browser. 7.2 JavaServer Faces Technology Benefits One of the greatest advantages of JavaServer Faces technology is that it offers a clean separation between behavior and presentation for web applications. A JavaServer Faces application can map HTTP requests to component-specific event handling and manage components as stateful objects on the server. JavaServer Faces technology allows you to build web applications that implement the finer-grained separation of behavior and presentation that is traditionally offered by client-side UI architectures. The separation of logic from presentation also allows each member of a web application development team to focus on a single piece of the development process and provides a simple programming model to link the pieces. For example, page authors with no programming expertise can use JavaServer Faces technology tags in a web page to link to server-side objects without writing any scripts. Another important goal of JavaServer Faces technology is to leverage familiar component and web-tier concepts without limiting you to a particular scripting technology or markup language. JavaServer Faces technology APIs are layered directly on top of the Servlet API, as shown in Figure 7–2. Figure 7–2 Java Web Application Technologies JavaServer Faces JavaServer Pages Standard Tag Library JavaServer Pages Java Servlet This layering of APIs enables several important application use cases, such as using different presentation technologies, creating your own custom components directly from the component classes, and generating output for various client devices. Facelets technology, available as part of JavaServer Faces technology, is the preferred presentation technology for building JavaServer Faces technology–based web applications. For more information on Facelets technology features, see Chapter 8, "Introduction to Facelets". Facelets technology offers several advantages. ■ ■ Code can be reused and extended for components through the templating and composite component features. You can use annotations to automatically register the managed bean as a resource available for JavaServer Faces applications. In addition, implicit navigation rules allow developers to quickly configure page navigation (see Navigation Model for details). These features reduce the manual configuration process for applications. ■ Most important, JavaServer Faces technology provides a rich architecture for managing component state, processing component data, validating user input, and handling events. JavaServer Faces Technology 7-3 A Simple JavaServer Faces Application 7.3 A Simple JavaServer Faces Application JavaServer Faces technology provides an easy and user-friendly process for creating web applications. Developing a simple JavaServer Faces application typically requires the following tasks, which have already been described in A Web Module That Uses JavaServer Faces Technology: The hello1 Example: ■ Creating web pages using component tags ■ Developing managed beans ■ Mapping the FacesServlet instance The hello1 example includes a managed bean and two Facelets web pages. When accessed by a client, the first web page asks the user for his or her name, and the second page responds by providing a greeting. For details on Facelets technology, see Chapter 8, "Introduction to Facelets". For details on using EL expressions, see Chapter 9, "Expression Language". For details on the JavaServer Faces programming model and building web pages using JavaServer Faces technology, see Chapter 10, "Using JavaServer Faces Technology in Web Pages". Every web application has a lifecycle. Common tasks, such as handling incoming requests, decoding parameters, modifying and saving state, and rendering web pages to the browser, are all performed during a web application lifecycle. Some web application frameworks hide the details of the lifecycle from you, whereas others require you to manage them manually. By default, JavaServer Faces automatically handles most of the lifecycle actions for you. However, it also exposes the various stages of the request lifecycle so that you can modify or perform different actions if your application requirements warrant it. The lifecycle of a JavaServer Faces application starts and ends with the following activity: The client makes a request for the web page, and the server responds with the page. The lifecycle consists of two main phases: Execute and Render. During the Execute phase, several actions can take place. ■ ■ ■ The application view is built or restored. The request parameter values are applied. Conversions and validations are performed for component values. ■ Managed beans are updated with component values. ■ Application logic is invoked. For a first (initial) request, only the view is built. For subsequent (postback) requests, some or all of the other actions can take place. In the Render phase, the requested view is rendered as a response to the client. Rendering is typically the process of generating output, such as HTML or XHTML, that can be read by the client, usually a browser. The following short description of the example JavaServer Faces application passing through its lifecycle summarizes the activity that takes place behind the scenes. The hello1 example application goes through the following stages when it is deployed on GlassFish Server. 1. When the hello1 application is built and deployed on GlassFish Server, the application is in an uninitiated state. 7-4 Java Platform, Enterprise Edition The Java EE Tutorial User Interface Component Model 2. When a client makes an initial request for the index.xhtml web page, the hello1 Facelets application is compiled. 3. The compiled Facelets application is executed, and a new component tree is constructed for the hello1 application and placed in a FacesContext. 4. The component tree is populated with the component and the managed bean property associated with it, represented by the EL expression hello.name. 5. A new view is built, based on the component tree. 6. The view is rendered to the requesting client as a response. 7. The component tree is destroyed automatically. 8. On subsequent (postback) requests, the component tree is rebuilt, and the saved state is applied. For full details on the lifecycle, see The Lifecycle of a JavaServer Faces Application. 7.4 User Interface Component Model In addition to the lifecycle description, an overview of JavaServer Faces architecture provides better understanding of the technology. JavaServer Faces components are the building blocks of a JavaServer Faces view. A component can be a user interface (UI) component or a non-UI component. JavaServer Faces UI components are configurable, reusable elements that compose the user interfaces of JavaServer Faces applications. A component can be simple, such as a button, or can be compound, such as a table composed of multiple components. JavaServer Faces technology provides a rich, flexible component architecture that includes the following: ■ A set of javax.faces.component.UIComponent classes for specifying the state and behavior of UI components ■ A rendering model that defines how to render the components in various ways ■ A conversion model that defines how to register data converters onto a component ■ An event and listener model that defines how to handle component events ■ A validation model that defines how to register validators onto a component This section briefly describes each of these pieces of the component architecture. 7.4.1 User Interface Component Classes JavaServer Faces technology provides a set of UI component classes and associated behavioral interfaces that specify all the UI component functionality, such as holding component state, maintaining a reference to objects, and driving event handling and rendering for a set of standard components. The component classes are completely extensible, allowing component writers to create their own custom components. See Chapter 15, "Creating Custom UI Components and Other Custom Objects" for more information. The abstract base class for all components is javax.faces.component.UIComponent. JavaServer Faces UI component classes extend the UIComponentBase class (a subclass of UIComponent), which defines the default state and behavior of a component. The following set of component classes is included with JavaServer Faces technology. JavaServer Faces Technology 7-5 User Interface Component Model ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ 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 is submitted. 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 error message. UIMessages: Displays a set of localized error messages. UIOutcomeTarget: Displays a link 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. UIViewParameter: Represents the query parameters in a request. This class is a subclass of the UIInput class. UIViewRoot: Represents the root of the component tree. In addition to extending UIComponentBase, the component classes also implement one or more behavioral interfaces, each of which defines certain behavior for a set of components whose classes implement the interface. These behavioral interfaces, all defined in the javax.faces.component package unless otherwise 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 Faces technology 1.1_01 and earlier versions. This interface is deprecated in JavaServer Faces 2. ActionSource2: Extends ActionSource and therefore provides the same functionality. However, it allows components to use the Expression Language (EL) when they are referencing methods that handle action events. EditableValueHolder: Extends ValueHolder and specifies additional features for editable components, such as validation and emitting value-change events. NamingContainer: Mandates that each component rooted at this component have a unique ID. StateHolder: Denotes that a component has state that must be saved between requests. 7-6 Java Platform, Enterprise Edition The Java EE Tutorial User Interface Component Model ■ ■ ■ ValueHolder: Indicates that the component maintains a local value as well as the option of accessing data in the model tier. javax.faces.event.SystemEventListenerHolder: Maintains a list of javax.faces.event.SystemEventListener instances for each type of javax.faces.event.SystemEvent defined by that class. javax.faces.component.behavior.ClientBehaviorHolder: Adds the ability to attach javax.faces.component.behavior.ClientBehavior instances, such as a reusable script. UICommand implements ActionSource2 and StateHolder. UIOutput and component classes that extend UIOutput implement StateHolder and ValueHolder. UIInput and component classes that extend UIInput implement EditableValueHolder, StateHolder, and ValueHolder. UIComponentBase implements StateHolder. Only component writers will need to use the component classes and behavioral interfaces directly. Page authors and application developers will use a standard component by including a tag that represents it on a page. Most of the components can be rendered in different ways on a page. For example, a UICommand component can be rendered as a button or a link. The next section explains how the rendering model works and how page authors can choose to render the components by selecting the appropriate tags. 7.4.2 Component Rendering Model The JavaServer Faces component architecture is designed such that the functionality of the components is defined by the component classes, whereas the component rendering 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 component to the same client or to different clients. Page authors and application developers can change the appearance of a component on the page by selecting the tag that represents the appropriate combination of component and renderer. A render kit defines how component classes map to component tags that are appropriate for a particular client. The JavaServer Faces implementation includes a standard HTML render kit for rendering to an HTML client. The render kit defines a set of javax.faces.render.Renderer classes for each component that it supports. Each Renderer class defines a different way to render the particular component to the output defined by the render kit. For example, a UISelectOne component has three different renderers. One of them renders the component as a group of options. Another renders the component as a combo box. The third one renders the component as a list box. Similarly, a UICommand component can be rendered as a button or a link, using the h:commandButton or h: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 each tag corresponds to a separate Renderer class that defines how the component appears on the page. Each custom tag defined in the standard HTML render kit is composed of the component functionality (defined in the UIComponent class) and the rendering attributes (defined by the Renderer class). JavaServer Faces Technology 7-7 User Interface Component Model The section Adding Components to a Page Using HTML Tag Library Tags lists all supported component tags and illustrates how to use the tags in an example. The JavaServer Faces implementation provides a custom tag library for rendering components in HTML. 7.4.3 Conversion Model A JavaServer Faces application can optionally associate a component with server-side object data. This object is a JavaBeans component, such as a managed bean. An application gets and sets the object data for a component by calling the appropriate object properties for that component. When a component is bound to an object, the application has two views of the component's data. ■ ■ The model view, in which data is represented as data types, such as int or long. The presentation view, in which data is represented in a manner that can be read or modified by the user. For example, a java.util.Date might be represented as a text string in the format mm/dd/yy or as a set of three text strings. The JavaServer Faces implementation automatically converts component data between these two views when the bean property associated with the component is of one of the types supported by the component's data. For example, if a UISelectBoolean component is associated with a bean property of type java.lang.Boolean, the JavaServer Faces implementation will automatically convert the component's data from String to Boolean. In addition, some component data must be bound to properties of a particular type. For example, a UISelectBoolean component must be bound to a property of type boolean or java.lang.Boolean. Sometimes you might want to convert a component's data to a type other than a standard type, or you might want to convert the format of the data. To facilitate this, JavaServer Faces technology allows you to register a javax.faces.convert.Converter implementation on UIOutput components and components whose classes subclass UIOutput. If you register the Converter implementation on a component, the Converter implementation converts the component's data between the two views. You can either use the standard converters supplied with the JavaServer Faces implementation or create your own custom converter. Custom converter creation is covered in Chapter 15, "Creating Custom UI Components and Other Custom Objects". 7.4.4 Event and Listener Model The JavaServer Faces event and listener model is similar to the JavaBeans event model in that it has strongly typed event classes and listener interfaces that an application can use to handle events generated by components. The JavaServer Faces specification defines three types of events: application events, system events, and data-model events. Application events are tied to a particular application and are generated by a UIComponent. They represent the standard events available in previous versions of JavaServer Faces technology. An event object identifies the component that generated the event and stores information about the event. To be notified of an event, an application must provide an implementation of the listener class and must register it on the component that generates the event. When the user activates a component, such as by clicking a 7-8 Java Platform, Enterprise Edition The Java EE Tutorial User Interface Component Model button, an event is fired. This causes the JavaServer Faces implementation to invoke the listener method that processes the event. JavaServer Faces supports two kinds of application events: action events and value-change events. An action event (class javax.faces.event.ActionEvent) occurs when the user activates a component that implements ActionSource. These components include buttons and links. A value-change event (class javax.faces.event.ValueChangeEvent) occurs when the user 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 value changing to true. The component types that can generate these types of events are the UIInput, 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) of the component emitting the event, action events can be processed during the Invoke Application phase or the Apply Request Values phase, and value-change events can be processed during the Process Validations phase or the Apply Request Values phase. System events are generated by an Object rather than a UIComponent. They are generated during the execution of an application at predefined times. They are applicable 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-change events 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 an f:actionListener tag inside the component tag. Implement a method of a managed bean to handle the event, and refer to the method with a method expression from the appropriate attribute of the component's tag. See Implementing an Event Listener for information on how to implement an event listener. See Registering Listeners on Components for information on how to register the listener on a component. See Writing a Method to Handle an Action Event and Writing a Method to Handle a Value-Change Event for information on how to implement managed bean methods that handle these events. See Referencing a Managed Bean Method for information on how to refer to the managed bean method from the component tag. When emitting events from custom components, you must implement the appropriate event class and manually queue the event on the component in addition to implementing an event listener class or a managed bean method that handles the event. Handling Events for Custom Components explains how to do this. 7.4.5 Validation Model JavaServer Faces technology supports a mechanism for validating the local data of editable components (such as text fields). This validation occurs before the corresponding model data is updated to match the local value. JavaServer Faces Technology 7-9 Navigation Model Like the conversion model, the validation model defines a set of standard classes for performing common data validation checks. The JavaServer Faces core tag library also defines a set of tags that correspond to the standard javax.faces.validator.Validator implementations. See Using the Standard Validators for a list of all the standard validation classes and corresponding tags. Most of the tags have a set of attributes for configuring the validator's properties, such as the minimum and maximum allowable values for the component's data. The page author registers the validator on a component by nesting the validator's tag within the component's tag. In addition to validators that are registered on the component, you can declare a default validator that is registered on all UIInput components in the application. For more information on default validators, see Using Default Validators. The validation model also allows you to create your own custom validator and corresponding tag to perform custom validation. The validation model provides two ways to implement custom validation. ■ ■ Implement a Validator interface that performs the validation. Implement a managed bean method that performs the validation. If you are implementing a Validator interface, you must also do the following. ■ ■ 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 validation model, the validator is defined for each input component on a page. The Bean Validation model allows the validator to be applied to all fields in a page. See Chapter 21, "Introduction to Bean Validation" and Chapter 22, "Bean Validation: Advanced Topics" for more information on Bean Validation. 7.5 Navigation Model The JavaServer Faces navigation model makes it easy to define page navigation and to handle any additional processing that is needed to choose the sequence in which pages are loaded. In JavaServer Faces technology, navigation is a set of rules for choosing the next page or view to be displayed after an application action, such as when a button or link is clicked. Navigation can be implicit or user-defined. Implicit navigation comes into play when user-defined navigation rules are not configured in the application configuration resource files. When you add a component such as a commandButton to a Facelets page, and assign another page as the value for its action property, the default navigation handler will try to match a suitable page within the application implicitly. In the following example, the default navigation handler will try to locate a page named response.xhtml within the application and navigate to it: User-defined navigation rules are declared in zero or more application configuration resource files, such as faces-config.xml, by using a set of XML elements. The default structure of a navigation rule is as follows: 7-10 Java Platform, Enterprise Edition The Java EE Tutorial Navigation Model 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 link component's action attribute. This outcome String is used by the JavaServer Faces implementation to select the navigation rule. Here is an example navigation rule: /greeting.xhtml success /response.xhtml This rule states that when a command component (such as an h:commandButton or an h:commandLink) on greeting.xhtml is activated, the application will navigate from the greeting.xhtml page to the response.xhtml page if the outcome referenced by the button component's tag is success. Here is an h:commandButton tag from greeting.xhtml that would specify a logical outcome of success: As the example demonstrates, each navigation-rule element defines how to get from one 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-case elements, each of which defines the page to open next (defined by to-view-id) based on a logical outcome (defined by from-outcome). In more complicated applications, the logical outcome can also come from the return value of an action method in a managed bean. This method performs some processing to determine the outcome. For example, the method can check whether the password the user entered on the page matches the one on file. If it does, the method might return success; otherwise, it might return failure. An outcome of failure might result in the logon page being reloaded. An outcome of success might cause the page displaying the user's credit card activity to open. If you want the outcome to be returned by a method on a bean, you must refer to the method using a method expression with the action attribute, as shown by this example: When the user clicks the button represented by this tag, the corresponding component generates an action event. This event is handled by the default javax.faces.event.ActionListener instance, which calls the action method referenced by the component that triggered the event. The action method returns a logical outcome to the action listener. JavaServer Faces Technology 7-11 Navigation Model The listener passes the logical outcome and a reference to the action method that produced the outcome to the default javax.faces.application.NavigationHandler. The NavigationHandler selects the page to display next by matching the outcome or the action method reference against the navigation rules in the application configuration resource file by the following process. 1. The NavigationHandler selects the navigation rule that matches the page currently displayed. 2. 3. It matches the outcome or the action method reference that it received from the default javax.faces.event.ActionListener with those defined by the navigation cases. It tries to match both the method reference and the outcome against the same navigation case. 4. If the previous step fails, the navigation handler attempts to match the outcome. 5. Finally, the navigation handler attempts to match the action method reference if the previous two attempts failed. 6. If no navigation case is matched, it displays the same view again. When the NavigationHandler achieves a match, the Render Response phase begins. During this phase, the page selected by the NavigationHandler will be rendered. The Duke's Tutoring case study example application uses navigation rules in the business methods that handle creating, editing, and deleting the users of the application. For example, the form for creating a student has the following h:commandButton tag: The action event calls the dukestutoring.ejb.AdminBean.createStudent method: public String createStudent(Student student) { em.persist(student); return "createdStudent"; } The return value of createdStudent has a corresponding navigation case in the faces-config.xml configuration file: /admin/student/createStudent.xhtml createdStudent /admin/index.xhtml After the student is created, the user is returned to the Administration index page. For more information on how to define navigation rules, see Configuring Navigation Rules. For more information on how to implement action methods to handle navigation, see Writing a Method to Handle an Action Event. For more information on how to reference outcomes or action methods from component tags, see Referencing a Method That Performs Navigation. 7-12 Java Platform, Enterprise Edition The Java EE Tutorial The Lifecycle of a JavaServer Faces Application 7.6 The Lifecycle of a JavaServer Faces Application The lifecycle of an application refers to the various stages of processing of that application, from its initiation to its conclusion. All applications have lifecycles. During a web application lifecycle, common tasks are performed, including the following. ■ Handling incoming requests ■ Decoding parameters ■ Modifying and saving state ■ Rendering web pages to the browser The JavaServer Faces web application framework manages lifecycle phases automatically for simple applications or allows you to manage them manually for more complex applications as required. JavaServer Faces applications that use advanced features may require interaction with the lifecycle at certain phases. For example, Ajax applications use partial processing features of the lifecycle (see Partial Processing and Partial Rendering). A clearer understanding of the lifecycle phases is key to creating well-designed components. A simplified view of the JavaServer faces lifecycle, consisting of the two main phases of a JavaServer Faces web application, is introduced in A Simple JavaServer Faces Application. This section examines the JavaServer Faces lifecycle in more detail. 7.6.1 Overview of the JavaServer Faces Lifecycle The lifecycle of a JavaServer Faces application begins when the client makes an HTTP request for a page and ends when the server responds with the page, translated to HTML. The lifecycle can be divided into two main phases: Execute and Render. The Execute phase is further divided into subphases to support the sophisticated component tree. This structure requires that component data be converted and validated, component events 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. During the lifecycle, the JavaServer Faces implementation must build the view while considering the state saved from a previous submission of the page. When the client requests a page, the JavaServer Faces implementation performs several tasks, such as validating the data input of components in the view and converting input data to types specified on the server side. The JavaServer Faces implementation performs all these tasks as a series of steps in the JavaServer Faces request-response lifecycle. Figure 7–3 illustrates these steps. JavaServer Faces Technology 7-13 The Lifecycle of a JavaServer Faces Application Figure 7–3 JavaServer Faces Standard Request-Response Lifecycle Faces Request Restore View Apply Requests Render Response Process Events Response Complete Process Validations Validation/ Conversion Errors/ Render Response Process Events Response Complete Update Model Values Conversion Errors/ Render Response Process Events Response Complete Invoke Application Process Events Response Complete Render Response Faces Response The request-response lifecycle handles two kinds of requests: initial requests and postbacks. An initial request occurs when a user makes a request for a page for the first time. A postback request occurs when a user submits the form contained on a page that was 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 and Render 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 result of clicking a link or button component on a JavaServer Faces page. To render a response that is another JavaServer Faces page, the application creates a new view and stores it in the javax.faces.context.FacesContext instance, which represents all of the information associated with processing an incoming request and creating a response. The application then acquires object references needed by the view and calls the FacesContext.renderResponse method, which forces immediate rendering of the view by skipping to the Render Response Phase of the lifecycle, as is shown by the arrows labelled Render Response in Figure 7–3. Sometimes, an application might need to redirect to a different web application resource, such as a web service, or generate a response that does not contain JavaServer Faces components. In these situations, the developer must skip the Render Response phase by calling the FacesContext.responseComplete method. This situation is also shown in Figure 7–3, with the arrows labelled Response Complete. The most common situation is that a JavaServer Faces component submits a request for another JavaServer Faces page. In this case, the JavaServer Faces implementation 7-14 Java Platform, Enterprise Edition The Java EE Tutorial The Lifecycle of a JavaServer Faces Application handles the request and automatically goes through the phases in the lifecycle to perform any necessary conversions, validations, and model updates and to generate the response. There is one exception to the lifecycle described in this section. When a component's immediate attribute is set to true, the validation, conversion, and events associated with these components are processed during the Apply Request Values Phase rather than in a later phase. The details of the lifecycle explained in the following sections are primarily intended for developers who need to know information such as when validations, conversions, and events are usually handled and ways to change how and when they are handled. For more information on each of the lifecycle phases, download the latest JavaServer Faces Specification documentation from http://jcp.org/en/jsr/detail?id=344. The JavaServer Faces application lifecycle Execute phase contains the following subphases: ■ Restore View Phase ■ Apply Request Values Phase ■ Process Validations Phase ■ Update Model Values Phase ■ ■ Invoke Application Phase Render Response Phase 7.6.2 Restore View Phase When a request for a JavaServer Faces page is made, usually by an action, such as when a link or a button component is clicked, the JavaServer Faces implementation begins the 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 in the FacesContext instance, which contains all the information needed to process a single request. All the application's components, event handlers, converters, and validators have access to the FacesContext instance. If the request for the page is an initial request, the JavaServer Faces implementation creates an empty view during this phase and the lifecycle advances to the Render Response phase, during which the empty view is populated with the components referenced by the tags in the page. If the request for the page is a postback, a view corresponding to this page already exists in the FacesContext instance. During this phase, the JavaServer Faces implementation restores the view by using the state information saved on the client or the server. 7.6.3 Apply Request Values Phase After the component tree is restored during a postback request, each component in the tree 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 decode methods or event listeners have called the renderResponse method on the current FacesContext instance, the JavaServer Faces implementation skips to the Render Response phase. JavaServer Faces Technology 7-15 The Lifecycle of a JavaServer Faces Application If any events have been queued during this phase, the JavaServer Faces implementation broadcasts the events to interested listeners. If some components on the page have their immediate attributes (see The immediate Attribute) set to true, then the validations, conversions, and events associated with these components will be processed during this phase. If any conversion fails, an error message associated with the component is generated and queued on FacesContext. This message will be displayed during the Render Response phase, along with any validation errors resulting from the Process Validations phase. At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call the FacesContext.responseComplete method. At the end of this phase, the components are set to their new values, and messages and events have been queued. If the current request is identified as a partial request, the partial context is retrieved from the FacesContext, and the partial processing method is applied. 7.6.4 Process Validations Phase During this phase, the JavaServer Faces implementation processes all validators registered on the components in the tree by using its validate (processValidators) method. It examines the component attributes that specify the rules for the validation and compares these rules to the local value stored for the component. The JavaServer Faces implementation also completes conversions for input components that do not have the immediate attribute set to true. If the local value is invalid, or if any conversion fails, the JavaServer Faces implementation adds an error message to the FacesContext instance, and the lifecycle advances directly to the Render Response phase so that the page is rendered again with the error messages displayed. If there were conversion errors from the Apply Request Values phase, the messages for these errors are also displayed. If any validate methods or event listeners have called the renderResponse method on the current FacesContext, the JavaServer Faces implementation skips to the Render Response phase. At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call the FacesContext.responseComplete method. If events have been queued during this phase, the JavaServer Faces implementation broadcasts them to interested listeners. If the current request is identified as a partial request, the partial context is retrieved from the FacesContext, and the partial processing method is applied. 7.6.5 Update Model Values Phase After the JavaServer Faces implementation determines that the data is valid, it traverses the component tree and sets the corresponding server-side object properties to the components' local values. The JavaServer Faces implementation updates only the bean properties pointed at by an input component's value attribute. If the local data cannot be converted to the types specified by the bean properties, the lifecycle advances directly to the Render Response phase so that the page is re-rendered with errors displayed. This is similar to what happens with validation errors. 7-16 Java Platform, Enterprise Edition The Java EE Tutorial Partial Processing and Partial Rendering If any updateModels methods or any listeners have called the renderResponse method on the current FacesContext instance, the JavaServer Faces implementation skips to the Render Response phase. At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call the FacesContext.responseComplete method. If any events have been queued during this phase, the JavaServer Faces implementation broadcasts them to interested listeners. If the current request is identified as a partial request, the partial context is retrieved from the FacesContext, and the partial processing method is applied. 7.6.6 Invoke Application Phase During this phase, the JavaServer Faces implementation handles any application-level events, such as submitting a form or linking to another page. At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call the FacesContext.responseComplete method. If the view being processed was reconstructed from state information from a previous request and if a component has fired an event, these events are broadcast to interested listeners. Finally, the JavaServer Faces implementation transfers control to the Render Response phase. 7.6.7 Render Response Phase During this phase, JavaServer Faces builds the view and delegates authority to the appropriate resource for rendering the pages. If this is an initial request, the components that are represented on the page will be added to the component tree. If this is not an initial request, the components are already added to the tree and need not be added again. If the request is a postback and errors were encountered during the Apply Request Values phase, Process Validations phase, or Update Model Values phase, the original page is rendered again during this phase. If the pages contain h:message or h:messages tags, any queued error messages are displayed on the page. After the content of the view is rendered, the state of the response is saved so that subsequent requests can access it. The saved state is available to the Restore View phase. 7.7 Partial Processing and Partial Rendering The JavaServer Faces lifecycle spans all of the execute and render processes of an application. It is also possible to process and render only parts of an application, such as a single component. For example, the JavaServer Faces Ajax framework can generate requests containing information on which particular component may be processed and which particular component may be rendered back to the client. Once such a partial request enters the JavaServer Faces lifecycle, the information is identified and processed by a javax.faces.context.PartialViewContext object. The JavaServer Faces lifecycle is still aware of such Ajax requests and modifies the component tree accordingly. JavaServer Faces Technology 7-17 Further Information about JavaServer Faces Technology The execute and render attributes of the f:ajax tag are used to identify which components may be executed and rendered. For more information on these attributes, see Chapter 13, "Using Ajax with JavaServer Faces Technology". 7.8 Further Information about JavaServer Faces Technology For more information on JavaServer Faces technology, see ■ ■ JavaServer Faces 2.2 specification: http://jcp.org/en/jsr/detail?id=344 JavaServer Faces project website: https://javaserverfaces.java.net/ 7-18 Java Platform, Enterprise Edition The Java EE Tutorial 8 8Introduction to Facelets [9] The term Facelets refers to the view declaration language for JavaServer Faces technology. Facelets is a part of the JavaServer Faces specification and also the preferred presentation technology for building JavaServer Faces technology–based applications. JavaServer Pages (JSP) technology, previously used as the presentation technology for JavaServer Faces, does not support all the new features available in JavaServer Faces in the Java EE 7 platform. JSP technology is considered to be a deprecated presentation technology for JavaServer Faces. The following topics are addressed here: ■ What Is Facelets? ■ The Lifecycle of a Facelets Application ■ Developing a Simple Facelets Application: The guessnumber-jsf Example Application ■ Using Facelets Templates ■ Composite Components ■ Web Resources ■ ■ Relocatable Resources Resource Library Contracts ■ HTML5-Friendly Markup 8.1 What Is Facelets? Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views using HTML style templates and to build component trees. Facelets features include the following: ■ Use of XHTML for creating web pages ■ ■ ■ Support for Facelets tag libraries in addition to JavaServer Faces and JSTL tag libraries Support for the Expression Language (EL) Templating for components and pages The advantages of Facelets for large-scale development projects include the following: ■ ■ Support for code reuse through templating and composite components Functional extensibility of components and other server-side objects through customization Introduction to Facelets 8-1 What Is Facelets? ■ ■ Faster compilation time Compile-time EL validation ■ High-performance rendering In short, the use of Facelets reduces the time and effort that needs to be spent on development and deployment. Facelets views are usually created as XHTML pages. JavaServer Faces implementations support XHTML pages created in conformance with the XHTML Transitional Document Type Definition (DTD), as listed at http://www.w3.org/TR/xhtml1/#a_dtd_XHTML-1.0-Transitional. By convention, web pages built with XHTML have an .xhtml extension. JavaServer Faces technology supports various tag libraries to add components to a web page. To support the JavaServer Faces tag library mechanism, Facelets uses XML namespace declarations. Table 8–1 lists the tag libraries supported by Facelets. Table 8–1 Tag Libraries Supported by Facelets Tag Library URI Prefix Example Contents JavaServer Faces Facelets Tag Library JavaServer Faces HTML Tag Library JavaServer Faces Core Tag Library Pass-through Elements Tag Library Pass-through Attributes Tag Library Composite Component Tag Library JSTL Core Tag Library JSTL Functions Tag Library http://xmlns.jcp.org/jsf/facelets ui: ui:component http://xmlns.jcp.org/jsf/html h: ui:insert h:head h:body h:outputText h:inputText http://xmlns.jcp.org/jsf/core f: f:actionListener f:attribute http://xmlns.jcp.org/jsf jsf: jsf:id http://xmlns.jcp.org/jsf/passthrough p: p:type http://xmlns.jcp.org/jsf/composite cc: cc:interface http://xmlns.jcp.org/jsp/jstl/core c: c:forEach c:catch http://xmlns.jcp.org/jsp/jstl/functions fn: fn:toUpperCase fn:toLowerCase Tags for templating JavaServer Faces component tags for all UIComponent objects Tags for JavaServer Faces custom actions that are independent of any particular render kit Tags to support HTML5-friendly markup Tags to support HTML5-friendly markup Tags to support composite components JSTL 1.2 Core Tags JSTL 1.2 Functions Tags Facelets provides two namespaces to support HTML5-friendly markup. For details, see HTML5-Friendly Markup. 8-2 Java Platform, Enterprise Edition The Java EE Tutorial Developing a Simple Facelets Application: The guessnumber-jsf Example Application Facelets supports tags for composite components, for which you can declare custom prefixes. For more information on composite components, see Composite Components. The namespace prefixes shown in the table are conventional, not mandatory. As is always the case when you declare an XML namespace, you can specify any prefix in your Facelets page. For example, you can declare the prefix for the composite component tag library as xmlns:composite="http://java.sun.com/jsf/composite" instead of as xmlns:cc="http://java.sun.com/jsf/composite" Based on the JavaServer Faces support for Expression Language (EL) syntax, Facelets uses EL expressions to reference properties and methods of managed beans. EL expressions can be used to bind component objects or values to methods or properties of managed beans that are used as backing beans. For more information on using EL expressions, see Using the EL to Reference Managed Beans. 8.2 The Lifecycle of a Facelets Application The JavaServer Faces specification defines the lifecycle of a JavaServer Faces application. For more information on this lifecycle, see The Lifecycle of a JavaServer Faces Application. The following steps describe that process as applied to a Facelets-based application. 1. When a client, such as a browser, makes a new request to a page that is created using Facelets, a new component tree or javax.faces.component.UIViewRoot is created and placed in the FacesContext. 2. The UIViewRoot is applied to the Facelets, and the view is populated with components for rendering. 3. The newly built view is rendered back as a response to the client. 4. On rendering, the state of this view is stored for the next request. The state of input components and form data is stored. 5. The client may interact with the view and request another view or change from the JavaServer Faces application. At this time, the saved view is restored from the stored state. 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 if there were no validation problems and no action was triggered. 7. 8. If the same view is requested, the stored view is rendered once again. 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. 8.3 Developing a Simple Facelets Application: The guessnumber-jsf Example Application This section describes the general steps involved in developing a JavaServer Faces application. The following tasks are usually required: ■ Developing the managed beans Introduction to Facelets 8-3 Developing a Simple Facelets Application: The guessnumber-jsf Example Application ■ Creating the pages using the component tags ■ Defining page navigation ■ Mapping the FacesServlet instance ■ Adding managed bean declarations 8.3.1 Creating a Facelets Application The example used in this tutorial is the guessnumber-jsf application. The application presents you with a page that asks you to guess a number from 0 to 10, validates your input against a random number, and responds with another page that informs you whether you guessed the number correctly or incorrectly. The source code for this application is in the tut-install/examples/web/jsf/guessnumber-jsf/ directory. 8.3.1.1 Developing a Managed Bean In a typical JavaServer Faces application, each page of the application connects to a managed bean that serves as a backing bean. The backing bean defines the methods and properties that are associated with the components. In this example, both pages use the same backing bean. The following managed bean class, UserNumberBean.java, generates a random number from 0 to 10 inclusive: package javaeetutorial.guessnumber; import java.io.Serializable; import java.util.Random; import javax.enterprise.context.SessionScoped; import javax.inject.Named; @Named @SessionScoped public class UserNumberBean implements Serializable { private static final long serialVersionUID = 5443351151396868724L; Integer randomInt = null; Integer userNumber = null; String response = null; private int maximum = 10; private int minimum = 0; public UserNumberBean() { Random randomGR = new Random(); randomInt = new Integer(randomGR.nextInt(maximum + 1)); // Print number to server log System.out.println("Duke's number: " + randomInt); } public void setUserNumber(Integer user_number) { userNumber = user_number; } public Integer getUserNumber() { return userNumber; } public String getResponse() { 8-4 Java Platform, Enterprise Edition The Java EE Tutorial Developing a Simple Facelets Application: The guessnumber-jsf Example Application if ((userNumber == null) || (userNumber.compareTo(randomInt) != 0)) { return "Sorry, " + userNumber + " is incorrect."; } else { return "Yay! You got it!"; } } public int getMaximum() { return (this.maximum); } public void setMaximum(int maximum) { this.maximum = maximum; } public int getMinimum() { return (this.minimum); } public void setMinimum(int minimum) { this.minimum = minimum; } } Note the use of the @Named annotation, which makes the managed bean accessible through the EL. The @SessionScoped annotation registers the bean scope as session to enable you to make multiple guesses as you run the application. 8.3.1.2 Creating Facelets Views To create a page or view, you add components to the pages, wire the components to backing bean values and properties, and register converters, validators, or listeners on the components. For the example application, XHTML web pages serve as the front end. The first page of the example application is a page called greeting.xhtml. A closer look at various sections of this web page provides more information. The first section of the web page declares the content type for the page, which is XHTML: The next section specifies the language of the XHTML page and then declares the XML namespace for the tag libraries that are used in the web page: The next section uses various tags to insert components into the web page: Guess Number Facelets Application

Hi, my name is Duke. I am thinking of a number from #{userNumberBean.minimum} to #{userNumberBean.maximum}. Can you guess it?

Note the use of the following tags: ■ ■ Facelets HTML tags (those beginning with h:) to add components The Facelets core tag f:validateLongRange to validate the user input An h:inputText tag accepts user input and sets the value of the managed bean property userNumber through the EL expression #{userNumberBean.userNumber}. The input value is validated for value range by the JavaServer Faces standard validator tag f:validateLongRange. The image file, wave.med.gif, is added to the page as a resource, as is the style sheet. For more details about the resources facility, see Web Resources. An h:commandButton tag with the ID submit starts validation of the input data when a user clicks the button. Using implicit navigation, the tag redirects the client to another page, response.xhtml, which shows the response to your input. The page specifies only response, which by default causes the server to look for response.xhtml. You can now create the second page, response.xhtml, with the following content: Guess Number Facelets Application

8-6 Java Platform, Enterprise Edition The Java EE Tutorial Developing a Simple Facelets Application: The guessnumber-jsf Example Application

This page also uses implicit navigation, setting the action attribute for the Back button to send the user to the greeting.xhtml page. 8.3.2 Configuring the Application Configuring a JavaServer Faces application involves mapping the Faces Servlet in the web deployment descriptor file, such as a web.xml file, and possibly adding managed bean declarations, navigation rules, and resource bundle declarations to the application configuration resource file, faces-config.xml. If you are using NetBeans IDE, a web deployment descriptor file is automatically created for you. In such an IDE-created web.xml file, change the default greeting page, which is index.xhtml, to greeting.xhtml. Here is an example web.xml file, showing this change in bold. javax.faces.PROJECT_STAGE Development Faces Servlet javax.faces.webapp.FacesServlet 1 Faces Servlet *.xhtml 30 greeting.xhtml Note the use of the context parameter PROJECT_STAGE. This parameter identifies the status of a JavaServer Faces application in the software lifecycle. The stage of an application can affect the behavior of the application. For example, if the project stage is defined as Development, debugging information is automatically generated for the user. If not defined by the user, the default project stage is Production. Introduction to Facelets 8-7 Using Facelets Templates 8.3.3 Running the guessnumber-jsf Facelets Example You can use either NetBeans IDE or Maven to build, package, deploy, and run the guessnumber-jsf example. 8.3.3.1 To Build, Package, and Deploy the guessnumber-jsf Example Using NetBeans IDE 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. From the File menu, choose Open Project. 3. In the Open Project dialog box, navigate to: tut-install/examples/web/jsf 4. Select the guessnumber-jsf folder. 5. Click Open Project. 6. In the Projects tab, right-click the guessnumber-jsf project and select Build. This option builds the example application and deploys it to your GlassFish Server instance. 8.3.3.2 To Build, Package, and Deploy the guessnumber-jsf Example Using Maven 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. In a terminal window, go to: tut-install/examples/web/jsf/guessnumber-jsf/ 3. Enter the following command: mvn install This command builds and packages the application into a WAR file, guessnumber-jsf.war, that is located in the target directory. It then deploys it to the server. 8.3.3.3 To Run the guessnumber-jsf Example 1. Open a web browser. 2. Enter the following URL in your web browser: http://localhost:8080/guessnumber-jsf 3. In the field, enter a number from 0 to 10 and click Submit. Another page appears, reporting whether your guess is correct or incorrect. 4. If you guessed incorrectly, click Back to return to the main page. You can continue to guess until you get the correct answer, or you can look in the server log, where the UserNumberBean constructor displays the correct answer. 8.4 Using Facelets Templates JavaServer Faces technology provides the tools to implement user interfaces that are easy to extend and reuse. Templating is a useful Facelets feature that allows you to 8-8 Java Platform, Enterprise Edition The Java EE Tutorial Using Facelets Templates create a page that will act as the base, or template, for the other pages in an application. By using templates, you can reuse code and avoid recreating similarly constructed pages. Templating also helps in maintaining a standard look and feel in an application with a large number of pages. Table 8–2 lists Facelets tags that are used for templating and their respective functionality. Table 8–2 Facelets Templating Tags Tag Function ui:component Defines a component that is created and added to the component tree. ui:composition Defines a page composition that optionally uses a template. Content outside of this tag is ignored. ui:debug ui:decorate ui:define ui:fragment Defines a debug component that is created and added to the component tree. Similar to the composition tag but does not disregard content outside this tag. Defines content that is inserted into a page by a template. Similar to the component tag but does not disregard content outside this tag. ui:include Encapsulates and reuses content for multiple pages. ui:insert ui:param ui:repeat ui:remove Inserts content into a template. Used to pass parameters to an included file. Used as an alternative for loop tags, such as c:forEach or h:dataTable. Removes content from a page. For more information on Facelets templating tags, see the JavaServer Faces Facelets Tag Library documentation. The Facelets tag library includes the main templating tag ui:insert. A template page that is created with this tag allows you to define a default structure for a page. A template page is used as a template for other pages, usually referred to as client pages. Here is an example of a template saved as template.xhtml: Facelets Template
Top Section
Introduction to Facelets 8-9 Composite Components
Left Section
Main Content
The example page defines an XHTML page that is divided into three sections: a top section, a left section, and a main section. The sections have style sheets associated with them. The same structure can be reused for the other pages of the application. The client page invokes the template by using the ui:composition tag. In the following example, a client page named templateclient.xhtml invokes the template page named template.xhtml from the preceding example. A client page allows content to be inserted with the help of the ui:define tag. Welcome to Template Client Page You can use NetBeans IDE to create Facelets template and client pages. For more information on creating these pages, see https://netbeans.org/kb/docs/web/jsf20-intro.html. 8.5 Composite Components JavaServer Faces technology offers the concept of composite components with Facelets. A composite component is a special type of template that acts as a component. Any component is essentially a piece of reusable code that behaves in a particular way. For example, an input component accepts user input. A component can also have validators, converters, and listeners attached to it to perform certain defined actions. A composite component consists of a collection of markup tags and other existing components. This reusable, user-created component has a customized, defined 8-10 Java Platform, Enterprise Edition The Java EE Tutorial Composite Components functionality and can have validators, converters, and listeners attached to it like any other component. With Facelets, any XHTML page that contains markup tags and other components can be converted into a composite component. Using the resources facility, the composite component can be stored in a library that is available to the application from the defined resources location. Table 8–3 lists the most commonly used composite tags and their functions. Table 8–3 Composite Component Tags Tag Function composite:interface composite:implementation composite:attribute composite:insertChildren composite:valueHolder composite:editableValueHolder composite:actionSource Declares the usage contract for a composite component. The composite component can be used as a single component whose feature set is the union of the features declared in the usage contract. Defines the implementation of the composite component. If a composite:interface element appears, there must be a corresponding composite:implementation. Declares an attribute that may be given to an instance of the composite component in which this tag is declared. Any child components or template text within the composite component tag in the using page will be reparented into the composite component at the point indicated by this tag's placement within the composite:implementation section. Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of ValueHolder suitable for use as the target of attached objects in the using page. Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of EditableValueHolder suitable for use as the target of attached objects in the using page. Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of ActionSource2 suitable for use as the target of attached objects in the using page. For more information and a complete list of Facelets composite tags, see the JavaServer Faces Facelets Tag Library documentation. The following example shows a composite component that accepts an email address as input: This content will not be displayed Introduction to Facelets 8-11 Web Resources Note the use of cc.attrs.value when defining the value of the inputText component. The word cc in JavaServer Faces is a reserved word for composite components. The #{cc.attrs.attribute-name} expression is used to access the attributes defined for the composite component's interface, which in this case happens to be value. The preceding example content is stored as a file named email.xhtml in a folder named resources/emcomp, under the application web root directory. This directory is considered a library by JavaServer Faces, and a component can be accessed from such a library. For more information on resources, see Web Resources. The web page that uses this composite component is generally called a using page. The using page includes a reference to the composite component, in the xml namespace declarations: Using a sample composite component The local composite component library is defined in the xmlns namespace with the declaration xmlns:em="http://xmlns.jcp.org/jsf/composite/emcomp". The component itself is accessed through the em:email tag. The preceding example content can be stored as a web page named emuserpage.xhtml under the web root directory. When compiled and deployed on a server, it can be accessed with the following URL: http://localhost:8080/application-name/emuserpage.xhtml See Chapter 14, "Composite Components: Advanced Topics and an Example," for more information and an example. 8.6 Web Resources Web resources are any software artifacts that the web application requires for proper rendering, including images, script files, and any user-created component libraries. Resources must be collected in a standard location, which can be one of the following. 8-12 Java Platform, Enterprise Edition The Java EE Tutorial Relocatable Resources ■ A resource packaged in the web application root must be in a subdirectory of a resources directory at the web application root: resources/resource-identifier. ■ A resource packaged in the web application's classpath must be in a subdirectory of the META-INF/resources directory within a web application: META-INF/resources/resource-identifier. You can use this file structure to package resources in a JAR file bundled in the web application. The JavaServer Faces runtime will look for the resources in the preceding listed locations, in that order. Resource identifiers are unique strings that conform to the following format (all on one line): [locale-prefix/][library-name/][library-version/]resource-name[/resource-version] Elements of the resource identifier in brackets ([]) are optional, indicating that only a resource-name, which is usually a file name, is a required element. For example, the most common way to specify a style sheet, image, or script is to use the library and name attributes, as in the following tag from the guessnumber-jsf example: This tag specifies that the default.css style sheet is in the directory web/resources/css. You can also specify the location of an image using the following syntax, also from the guessnumber-jsf example: This tag specifies that the image named wave.med.gif is in the directory web/resources/images. Resources can be considered as a library location. Any artifact, such as a composite component or a template that is stored in the resources directory, becomes accessible to the other application components, which can use it to create a resource instance. 8.7 Relocatable Resources You can place a resource tag in one part of a page and specify that it be rendered in another part of the page. To do this, you use the target attribute of a tag that specifies a resource. Acceptable values for this attribute are as follows. ■ ■ ■ "head" renders the resource in the head element. "body" renders the resource in the body element. "form" renders the resource in the form element. For example, the following h:outputScript tag is placed within an h:form element, but it renders the JavaScript in the head element: The h:outputStylesheet tag also supports resource relocation, in a similar way. Relocatable resources are essential for composite components that use stylesheets and can also be useful for composite components that use JavaScript. See The compositecomponentexample Example Application for an example. Introduction to Facelets 8-13 Resource Library Contracts 8.8 Resource Library Contracts Resource library contracts allow you to define a different look and feel for different parts of one or more applications, instead of either having to use the same look and feel for all or having to specify a different look on a page-by-page basis. To do this, you create a contracts section of your web application. Within the contracts section, you can specify any number of named areas, each of which is called a contract. Within each contract you can specify resources such as template files, stylesheets, JavaScript files, and images. For example, you could specify two contracts named c1 and c2, each of which uses a template and other files: src/main/webapp WEB-INF/ contracts c1 template.xhtml style.css myImg.gif myJS.js c2 template.xhtml style2.css img2.gif JS2.js index.xhtml ... One part of the application can use c1, while another can use c2. Another way to use contracts is to specify a single contract that contains multiple templates: src/main/webapp contracts myContract template1.xhtml template2.xhtml style.css img.png img2.png You can package a resource library contract in a JAR file for reuse in different applications. If you do so, the contracts must be located under META-INF/contracts. You can then place the JAR file in the WEB-INF/lib directory of an application. This means that the application would be organized as follows: src/main/webapp/ WEB-INF/lib/myContract.jar ... You can specify the contract usage within an application's faces-config.xml file, under the resource-library-contracts element. You need to use this element only if your application uses more than one contract, however. 8-14 Java Platform, Enterprise Edition The Java EE Tutorial Resource Library Contracts 8.8.1 The hello1-rlc Example Application The hello1-rlc example modifies the simple hello1 example from A Web Module That Uses JavaServer Faces Technology: The hello1 Example to use two resource library contracts. Each of the two pages in the application uses a different contract. The managed bean for hello1-rlc, Hello.java, is identical to the one for hello1 (except that it replaces the @Named and @RequestScoped annotations with @Model). The source code for this application is in the tut-install/examples/web/jsf/hello1-rlc/ directory. 8.8.1.1 Configuring the hello1-rlc Example The faces-config.xml file for the hello1-rlc example contains the following elements: /reply/* reply * hello The contract-mapping elements within the resource-library-contracts element map each contract to a different set of pages within the application. One contract, named reply, is used for all pages under the reply area of the application (/reply/*). The other contract, hello, is used for all other pages in the application (*). The application is organized as follows: hello1-rlc pom.xml src/main/java/javaeetutorial/hello1rlc/Hello.java src/main/webapp WEB-INF faces-config.xml web.xml contracts hello default.css duke.handsOnHips.gif template.xhtml reply default.css duke.thumbsup.gif template.xhtml reply response.xhtml greeting.xhtml The web.xml file specifies the welcome-file as greeting.xhtml. Because it is not located under src/main/webapp/reply, this Facelets page uses the hello contract, whereas src/main/webapp/reply/response.xhtml uses the reply contract. Introduction to Facelets 8-15 Resource Library Contracts 8.8.1.2 The Facelets Pages for the hello1-rlc Example The greeting.xhtml and response.xhtml pages have identical code calling in their templates: The template.xhtml files in the hello and reply contracts differ only in two respects: the placeholder text for the title element ("Hello Template" and "Reply Template") and the graphic that each specifies. The default.css stylesheets in the two contracts differ in only one respect: the background color specified for the body element. 8.8.1.3 To Build, Package, and Deploy the hello1-rlc Example Using NetBeans IDE 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. From the File menu, choose Open Project. 3. In the Open Project dialog box, navigate to: tut-install/examples/web/jsf 4. Select the hello1-rlc folder. 5. Click Open Project. 6. In the Projects tab, right-click the hello1-rlc project and select Build. This option builds the example application and deploys it to your GlassFish Server instance. 8.8.1.4 To Build, Package, and Deploy the hello1-rlc Example Using Maven 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. In a terminal window, go to: tut-install/examples/web/jsf/hello1-rlc/ 3. Enter the following command: mvn install This command builds and packages the application into a WAR file, hello1-rlc.war, that is located in the target directory. It then deploys it to your GlassFish Server instance. 8.8.1.5 To Run the hello1-rlc Example 1. Enter the following URL in your web browser: http://localhost:8080/hello1-rlc 2. The greeting.xhtml page looks just like the one from hello1 except for its background color and graphic. 3. In the text field, enter your name and click Submit. 4. The response page also looks just like the one from hello1 except for its background color and graphic. 8-16 Java Platform, Enterprise Edition The Java EE Tutorial The page displays the name you submitted. Click Back to return to the greeting.xhtml page. HTML5-Friendly Markup 8.9 HTML5-Friendly Markup When you want to produce user interface features for which HTML does not have its own elements, you can create a custom JavaServer Faces component and insert it in your Facelets page. This mechanism can cause a simple element to create complex web code. However, creating such a component is a significant task (see Chapter 15, "Creating Custom UI Components and Other Custom Objects"). HTML5 offers new elements and attributes that can make it unnecessary to write your own components. It also provides many new capabilities for existing components. JavaServer Faces technology supports HTML5 not by introducing new UI components that imitate HTML5 ones but by allowing you to use HTML5 markup directly. It also allows you to use JavaServer Faces attributes within HTML5 elements. JavaServer Faces technology support for HTML5 falls into two categories: ■ ■ Pass-through elements Pass-through attributes The effect of the HTML5-friendly markup feature is to offer the Facelets page author almost complete control over the rendered page output, rather than having to pass this control off to component authors. You can mix and match JavaServer Faces and HTML5 components and elements as you see fit. 8.9.1 Using Pass-Through Elements Pass-through elements allow you to use HTML5 tags and attributes but to treat them as equivalent to JavaServer Faces components associated with a server-side UIComponent instance. To make an element that is not a JavaServer Faces element a pass-through element, specify at least one of its attributes using the http://xmlns.jcp.org/jsf namespace. For example, the following code declares the namespace with the short name jsf: Here, the jsf prefix is placed on the id attribute so that the HTML5 input tag's attributes are treated as part of the Facelets page. This means that, for example, you can use EL expressions to retrieve managed bean properties. Table 8–4 shows how pass-through elements are rendered as Facelets tags. The JSF implementation uses the element name and the identifying attribute to determine the corresponding Facelets tag that will be used in the server-side processing. The browser, however, interprets the markup that the page author has written. Table 8–4 How Facelets Renders HTML5 Elements HTML5 Element Name Identifying Attribute Facelets Tag a a a a jsf:action h:commandLink jsf:actionListener h:commandLink jsf:value jsf:outcome h:outputLink h:link Introduction to Facelets 8-17 HTML5-Friendly Markup Table 8–4 (Cont.) How Facelets Renders HTML5 Elements HTML5 Element Name Identifying Attribute Facelets Tag body button button form head img input input input input input input input input input input input input input input input input input input input input label link script select select textarea jsf:outcome type="button" h:body h:commandButton h:button h:form h:head h:graphicImage h:commandButton type="checkbox" h:selectBooleanCheckbox type="color" type="date" type="datetime" h:inputText h:inputText h:inputText type="datetime-local" h:inputText type="email" type="month" type="number" type="range" type="search" type="time" type="url" type="week" type="file" type="hidden" type="password" type="reset" type="submit" type="*" h:inputText h:inputText h:inputText h:inputText h:inputText h:inputText h:inputText h:inputText h:inputFile h:inputHidden h:inputSecret h:commandButton h:commandButton h:inputText h:outputLabel h:outputStylesheet h:outputScript multiple="*" h:selectManyListbox h:selectOneListbox h:inputTextArea 8.9.2 Using Pass-Through Attributes Pass-through attributes are the converse of pass-through elements. They allow you to pass attributes that are not JavaServer Faces attributes through to the browser without interpretation. If you specify a pass-through attribute in a JavaServer Faces UIComponent, the attribute name and value are passed straight through to the browser 8-18 Java Platform, Enterprise Edition The Java EE Tutorial HTML5-Friendly Markup without being interpreted by JavaServer Faces components or renderers. There are several ways to specify pass-through attributes. ■ Use the JavaServer Faces namespace for pass-through attributes to prefix the attribute names within a JavaServer Faces component. For example, the following code declares the namespace with the short name p, then passes the type, min, max, required, and title attributes through to the HTML5 input component: ... This will cause the following markup to be rendered (assuming that bean.nights has a default value set to 1): ■ To pass a single attribute, nest the f:passThroughAttribute tag within a component tag. For example: This code would be rendered similarly to the following: ■ To pass a group of attributes, nest the f:passThroughAttributes tag within a component tag, specifying an EL value that must evaluate to a Map. For example: If the bean used the following Map declaration and initialized the map in the constructor as follows, the markup would be similar to the output of the code that uses the pass-through attribute namespace: private Map nameValuePairs; ... public Bean() { this.nameValuePairs = new HashMap<>(); this.nameValuePairs.put("type", "number"); this.nameValuePairs.put("min", "1"); this.nameValuePairs.put("max", "30"); this.nameValuePairs.put("required", "required"); this.nameValuePairs.put("title", "Enter a number between 1 and 4 inclusive."); } Introduction to Facelets 8-19 HTML5-Friendly Markup 8.9.3 The reservation Example Application The reservation example application provides a set of HTML5 input elements of various types to simulate purchasing tickets for a theatrical event. It consists of two Facelets pages, reservation.xhtml and confirmation.xhtml, and a backing bean, ReservationBean.java. The pages use both pass-through attributes and pass-through elements. The source code for this application is in the tut-install/examples/web/jsf/reservation/ directory. 8.9.3.1 The Facelets Pages for the reservation Application The first important feature of the Facelets pages for the reservation application is the DOCTYPE header. Most Facelets pages in JavaServer Faces applications refer to the XHTML DTD. The facelets pages for this application begin simply with the following DOCTYPE header, which indicates an HTML5 page: The namespace declarations in the html element of the reservation.xhtml page specify both the jsf and the passthrough namespaces: Next, an empty h:head tag followed by an h:outputStylesheet tag within the h:body tag illustrates the use of a relocatable resource (as described in Relocatable Resources): The reservation.xhtml page uses pass-through elements for most of the form fields on the page. This allows it to use some HTML5-specific input element types, such as date and email. For example, the following element renders both a date format and a calendar from which you can choose a date. The jsf prefix on the id attribute makes the element a pass-through one: The field for the number of tickets, however, uses the h:passThroughAttributes tag to pass a Map defined in the managed bean. It also recalculates the total in response to a change in the field: The field for the price specifies the number type as a pass-through attribute of the h:inputText element, offering a range of four ticket prices. Here, the p prefix on the 8-20 Java Platform, Enterprise Edition The Java EE Tutorial HTML5-Friendly Markup HTML5 attributes passes them through to the browser uninterpreted by the JavaServer Faces input component: The output of the calculateTotal method that is specified as the listener for the Ajax event is rendered in the output element whose id and name value is total. See Chapter 13, "Using Ajax with JavaServer Faces Technology", for more information. The second Facelets page, confirmation.xhtml, uses a pass-through output element to display the values entered by the user and provides a Facelets h:commandButton tag to allow the user to return to the reservation.xhtml page. 8.9.3.2 The Managed Bean for the reservation Application The session-scoped managed bean for the reservation application, ReservationBean.java, contains properties for all the elements on the Facelets pages. It also contains two methods, calculateTotal and clear, that act as listeners for Ajax events on the reservation.xhtml page. 8.9.3.3 To Build, Package, and Deploy the reservation Example Using NetBeans IDE 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. From the File menu, choose Open Project. 3. In the Open Project dialog box, navigate to: tut-install/examples/web/jsf 4. Select the reservation folder. 5. Click Open Project. 6. In the Projects tab, right-click the reservation project and select Build. This option builds the example application and deploys it to your GlassFish Server instance. 8.9.3.4 To Build, Package, and Deploy the reservation Example Using Maven 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. In a terminal window, go to: tut-install/examples/web/jsf/reservation/ 3. Enter the following command: mvn install Introduction to Facelets 8-21 HTML5-Friendly Markup This command builds and packages the application into a WAR file, reservation.war, that is located in the target directory. It then deploys the WAR file to your GlassFish Server instance. 8.9.3.5 To Run the reservation Example At the time of the publication of this tutorial, the browser that most fully implements HTML5 is Google Chrome, and it is recommended that you use it to run this example. Other browsers are catching up, however, and may work equally well by the time you read this. 1. Enter the following URL in your web browser: http://localhost:8080/reservation 2. Enter information in the fields of the reservation.xhtml page. The Performance Date field has a date field with up and down arrows that allow you to increment and decrement the month, day, and year as well as a larger down arrow that brings up a date editor in calendar form. The Number of Tickets and Ticket Price fields also have up and down arrows that allow you to increment and decrement the values within the allowed range and steps. The Estimated Total changes when you change either of these two fields. Email addresses and dates are checked for format, but not for validity (you can make a reservation for a past date, for instance). 3. Click Make Reservation to complete the reservation or Clear to restore the fields to their default values. 4. If you click Make Reservation, the confirmation.xhtml page appears, displaying the submitted values. Click Back to return to the reservation.xhtml page. 8-22 Java Platform, Enterprise Edition The Java EE Tutorial 9 9Expression Language [10] This chapter introduces the Expression Language (also referred to as the EL), which provides an important mechanism for enabling the presentation layer (web pages) to communicate with the application logic (managed beans). The EL is used by several JavaEE technologies, such as JavaServer Faces technology, JavaServer Pages (JSP) technology, and Contexts and Dependency Injection for Java EE (CDI). The EL can also be used in stand-alone environments. This chapter only covers the use of the EL in Java EE containers. The following topics are addressed here: ■ Overview of the EL ■ Immediate and Deferred Evaluation Syntax ■ Value and Method Expressions ■ Operations on Collection Objects ■ Operators ■ ■ ■ Reserved Words Examples of EL Expressions Further Information about the Expression Language 9.1 Overview of the EL The EL allows page authors to use simple expressions to dynamically access data from JavaBeans components. For example, the test attribute of the following conditional tag is supplied with an EL expression that compares 0 with the number of items in the session-scoped bean named cart. ... See Using the EL to Reference Managed Beans for more information on how to use the EL in JavaServer Faces applications. To summarize, the EL provides a way to use simple expressions to perform the following tasks: ■ Dynamically read application data stored in JavaBeans components, various data structures, and implicit objects ■ Dynamically write data, such as user input into forms, to JavaBeans components ■ Invoke arbitrary static and public methods Expression Language 9-1 Immediate and Deferred Evaluation Syntax ■ Dynamically perform arithmetic, boolean, and string operations ■ Dynamically construct collection objects and perform operations on collections In a JavaServer Faces page, an EL expression can be used either in static text or in the attribute of a custom tag or standard action. Finally, the EL provides a pluggable API for resolving expressions so that custom resolvers that can handle expressions not already supported by the EL can be implemented. 9.2 Immediate and Deferred Evaluation Syntax The EL supports both immediate and deferred evaluation of expressions. Immediate evaluation means that the expression is evaluated and the result returned as soon as the page is first rendered. Deferred evaluation means that the technology using the expression language can use its own machinery to evaluate the expression sometime later during the page's lifecycle, whenever it is appropriate to do so. Those expressions that are evaluated immediately use the ${} syntax. Expressions whose evaluation is deferred use the #{} syntax. Because of its multiphase lifecycle, JavaServer Faces technology uses mostly deferred evaluation expressions. During the lifecycle, component events are handled, data is validated, and other tasks are performed in a particular order. Therefore, a JavaServer Faces implementation must defer evaluation of expressions until the appropriate point in the lifecycle. Other technologies using the EL might have different reasons for using deferred expressions. 9.2.1 Immediate Evaluation All expressions using the ${} syntax are evaluated immediately. These expressions can appear as part of a template (static) text or as the value of a tag attribute that can accept runtime expressions. The following example shows a tag whose value attribute references an immediate evaluation expression that updates the quantity of books retrieved from the backing bean named catalog: The JavaServer Faces implementation evaluates the expression ${catalog.bookQuantity}, converts it, and passes the returned value to the tag handler. The value is updated on the page. 9.2.2 Deferred Evaluation Deferred evaluation expressions take the form #{expr} and can be evaluated at other phases of a page lifecycle as defined by whatever technology is using the expression. In the case of JavaServer Faces technology, its controller can evaluate the expression at different phases of the lifecycle, depending on how the expression is being used in the page. The following example shows a JavaServer Faces h:inputText tag, which represents a field component into which a user enters a value. The h:inputText tag's value attribute references a deferred evaluation expression that points to the name property of the customer bean: 9-2 Java Platform, Enterprise Edition The Java EE Tutorial Value and Method Expressions For an initial request of the page containing this tag, the JavaServer Faces implementation evaluates the #{customer.name} expression during the render-response phase of the lifecycle. During this phase, the expression merely accesses the value of name from the customer bean, as is done in immediate evaluation. For a postback request, the JavaServer Faces implementation evaluates the expression at different phases of the lifecycle, during which the value is retrieved from the request, validated, and propagated to the customer bean. As shown in this example, deferred evaluation expressions can be ■ Value expressions that can be used to both read and write data ■ Method expressions Value expressions (both immediate and deferred) and method expressions are explained in the next section. 9.3 Value and Method Expressions The EL defines two kinds of expressions: value expressions and method expressions. Value expressions can be evaluated to yield a value, and method expressions are used to reference a method. 9.3.1 Value Expressions Value expressions can be further categorized into rvalue and lvalue expressions. An lvalue expression can specify a target, such as an object, a bean property, or elements of a collection, that can be assigned a value. An rvalue expression cannot specify such a target. All expressions that are evaluated immediately use the ${} delimiters, and although the expression can be an lvalue expression, no assignments will ever happen. Expressions whose evaluation can be deferred use the #{} delimiters and can act as both rvalue and lvalue expressions; if the expression is an lvalue expression, it can be assigned a new value. Consider the following two value expressions: ${customer.name} #{customer.name} The former uses immediate evaluation syntax, whereas the latter uses deferred evaluation syntax. The first expression accesses the name property, gets its value, and passes the value to the tag handler. With the second expression, the tag handler can defer the expression evaluation to a later time in the page lifecycle if the technology using this tag allows. In the case of JavaServer Faces technology, the latter tag's expression is evaluated immediately during an initial request for the page. During a postback request, this expression can be used to set the value of the name property with user input. 9.3.1.1 Referencing Objects A top-level identifier (such as customer in the expression customer.name) can refer to the following objects: ■ ■ Lambda parameters EL variables Expression Language 9-3 Value and Method Expressions ■ Managed beans ■ ■ Implicit objects Classes of static fields and methods To refer to these objects, you write an expression using a variable that is the name of the object. The following expression references a managed bean called customer: ${customer} You can use a custom EL resolver to alter the way variables are resolved. For instance, you can provide an EL resolver that intercepts objects with the name customer, so that ${customer} returns a value in the EL resolver instead. (JavaServer Faces technology uses an EL resolver to handle managed beans.) An enum constant is a special case of a static field, and you can reference such a constant directly. For example, consider this enum class: public enum Suit {hearts, spades, diamonds, clubs} In the following expression, in which mySuit is an instance of Suit, you can compare suit.hearts to the instance: ${mySuit == suit.hearts} 9.3.1.2 Referencing Object Properties or Collection Elements To refer to properties of a bean, static fields or methods of a class, or items of a collection, you use the . or [] notation. The same syntax can be used for attributes of an implicit object, because attributes are placed in a map. To reference the name property of the customer bean, use either the expression ${customer.name} or the expression ${customer["name"]}. Here, the part inside the brackets is a String literal that is the name of the property to reference. The [] syntax is more general than the . syntax, because the part inside the brackets can be any String expression, not just literals. You can use double or single quotes for the String literal. You can also combine the [] and . notations, as shown here: ${customer.address["street"]} You can reference a static field or method using the syntax classname.field, as in the following example: Boolean.FALSE The classname is the name of the class without the package name. By default, all the java.lang packages are imported. You can import other packages, classes, and static fields as needed. If you are accessing an item in an array or list, you must use the [] notation and specify an index in the array or list. The index is an expression that can be converted to int. The following example references the first of the customer orders, assuming that customer.orders is a List: ${customer.orders[1]} If you are accessing an item in a Map, you must specify the key for the Map. If the key is a String literal, the dot (.) notation can be used. Assuming that customer.orders is a Map with a String key, the following examples reference the item with the key "socks": 9-4 Java Platform, Enterprise Edition The Java EE Tutorial Value and Method Expressions ${customer.orders["socks"]} ${customer.orders.socks} 9.3.1.3 Referencing Literals The EL defines the following literals: ■ ■ ■ ■ Boolean: true and false Integer: As in Java Floating-point: As in Java String: With single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\ ■ Null: null Here are some examples: ■ ■ ■ ${"literal"} ${true} ${57} 9.3.1.4 Parameterized Method Calls The EL offers support for parameterized method calls. Both the . and [] operators can be used for invoking method calls with parameters, as shown in the following expression syntax: ■ ■ expr-a[expr-b](parameters) expr-a.identifier-b(parameters) In the first expression syntax, expr-a is evaluated to represent a bean object. The expression expr-b is evaluated and cast to a string that represents a method in the bean represented by expr-a. In the second expression syntax, expr-a is evaluated to represent a bean object, and identifier-b is a string that represents a method in the bean object. The parameters in parentheses are the arguments for the method invocation. Parameters can be zero or more values of expressions, separated by commas. Parameters are supported for both value expressions and method expressions. In the following example, which is a modified tag from the guessnumber application, a random number is provided as an argument rather than from user input to the method call: The preceding example uses a value expression. Consider the following example of a JavaServer Faces component tag that uses a method expression: The EL expression trader.buy calls the trader bean's buy method. You can modify the tag to pass on a parameter. Here is the revised tag in which a parameter is passed: In the preceding example, you are passing the string 'SOMESTOCK' (a stock symbol) as a parameter to the buy method. Expression Language 9-5 Value and Method Expressions 9.3.1.5 Where Value Expressions Can Be Used Value expressions using the ${} delimiters can be used ■ ■ In static text In any standard or custom tag attribute that can accept an expression The value of an expression in static text is computed and inserted into the current output. Here is an example of an expression embedded in static text: some text ${expr} some text A tag attribute can be set in the following ways. ■ With a single expression construct: These expressions are evaluated, and the result is converted to the attribute's expected type. ■ With one or more expressions separated or surrounded by text: These kinds of expression, called composite expressions, are evaluated from left to right. Each expression embedded in the composite expression is converted to a String and then concatenated with any intervening text. The resulting String is then converted to the attribute's expected type. ■ With text only: The attribute's String value is converted to the attribute's expected type. You can use the string concatenation operator += to create a single expression from what would otherwise be a composite expression. For example, you could change the composite expression to All expressions used to set attribute values are evaluated in the context of an expected type. If the result of the expression evaluation does not match the expected type exactly, a type conversion will be performed. For example, the expression ${1.2E4} provided as the value of an attribute of type float will result in the following conversion: Float.valueOf("1.2E4").floatValue() 9-6 Java Platform, Enterprise Edition The Java EE Tutorial 9.3.2 Method Expressions Value and Method Expressions Another feature of the EL is its support of deferred method expressions. A method expression is used to refer to a public method of a bean and has the same syntax as an lvalue expression. In JavaServer Faces technology, a component tag represents a component on a page. The component tag uses method expressions to specify methods that can be invoked to perform some processing for the component. These methods are necessary for handling events that the components generate and for validating component data, as shown in this example: The h:inputText tag displays as a field. The validator attribute of this h:inputText tag references a method, called validateName, in the bean, called customer. Because a method can be invoked during different phases of the lifecycle, method expressions must always use the deferred evaluation syntax. Like lvalue expressions, method expressions can use the . and the [] operators. For example, #{object.method} is equivalent to #{object["method"]}. The literal inside the [] is converted to String and is used to find the name of the method that matches it. Method expressions can be used only in tag attributes and only in the following ways: ■ With a single expression construct, where bean refers to a JavaBeans component and method refers to a method of the JavaBeans component: The expression is evaluated to a method expression, which is passed to the tag handler. The method represented by the method expression can then be invoked later. ■ With text only: Method expressions support literals primarily to support action attributes in JavaServer Faces technology. When the method referenced by this method expression is invoked, the method returns the String literal, which is then converted to the expected return type, as defined in the tag's tag library descriptor. 9.3.3 Lambda Expressions A lambda expression is a value expression with parameters. The syntax is similar to that of the lambda expression in the Java programming language, except that in the EL, the body of the lambda expression is an EL expression. For basic information on lambda expressions, see http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html. Expression Language 9-7 Operations on Collection Objects Note: Lambda expressions are part of Java SE 8, but you can use them in EL expressions with Java SE 7, the Java version associated with the Java EE 7 platform. A lambda expression uses the arrow token (->) operator. The identifiers to the left of the operator are called lambda parameters. The body, to the right of the operator, must be an EL expression. The lambda parameters are enclosed in parentheses; the parentheses can be omitted if there is only one parameter. Here are some examples: x -> x+1 (x, y) -> x + y () -> 64 A lambda expression behaves like a function. It can be invoked immediately. For example, the following invocation evaluates to 7: ((x, y) -> x + y)(3, 4) You can use a lambda expression in conjunction with the assignment and semicolon operators. For example, the following code assigns the previous lambda expression to a variable and then invokes it. The result is again 7: v = (x, y) -> x + y; v(3, 4) A lambda expression can also be passed as an argument to a method and be invoked in the method. It can also be nested in another lambda expression. 9.4 Operations on Collection Objects The EL supports operations on collection objects: sets, lists, and maps. It allows the dynamic creation of collection objects, which can then be operated on using streams and pipelines. Note: Like lambda expressions, operations on collection objects are part of Java SE 8, but you can use them in EL expressions with Java SE 7, the Java version associated with the Java EE 7 platform. For example, you can construct a set as follows: {1,2,3} You can construct a list as follows; a list can contain various types of items: [1,2,3] [1, "two", [three,four]] You can construct a map by using a colon to define the entries, as follows: {"one":1, "two":2, "three":3} You operate on collection objects using method calls to the stream of elements derived from the collection. Some operations return another stream, which allows additional operations. Therefore, you can chain these operations together in a pipeline. A stream pipeline consists of the following: ■ A source (the Stream object) 9-8 Java Platform, Enterprise Edition The Java EE Tutorial Operators ■ Any number of intermediate operations that return a stream (for example, filter and map) ■ A terminal operation that does not return a stream (for example, toList()) The stream method obtains a Stream from a java.util.Collection or a Java array. The stream operations do not modify the original collection object. For example, you might generate a list of titles of history books as follows: books.stream().filter(b->b.category == 'history') .map(b->b.title) .toList() The following simpler example returns a sorted version of the original list: [1,3,5,2].stream().sorted().toList() Streams and stream operations are documented in the Java SE 8 API documentation, available at http://docs.oracle.com/javase/8/docs/api/. The following subset of operations is supported by the EL: allMatch anyMatch average count distinct filter findFirst flatMap forEach iterator limit map max min noneMatch peek reduce sorted substream sum toArray toList See the EL specification at http://www.jcp.org/en/jsr/detail?id=341 for details on these operations. 9.5 Operators In addition to the . and [] operators discussed in Value and Method Expressions, the EL provides the following operators, which can be used in rvalue expressions only. ■ Arithmetic: +, - (binary), *, / and div, % and mod, - (unary). ■ ■ String concatenation: +=. Logical: and, &&, or, ||, not, !. Expression Language 9-9 Reserved Words ■ Relational: ==, eq, !=, ne, <, lt, >, gt, <=, ge, >=, le. Comparisons can be made against other values or against Boolean, string, integer, or floating-point literals. ■ Empty: The empty operator is a prefix operation that can be used to determine whether a value is null or empty. ■ Conditional: A ? B : C. Evaluate B or C, depending on the result of the evaluation of A. ■ Lambda expression: ->, the arrow token. ■ Assignment: =. ■ Semicolon: ;. The precedence of operators, highest to lowest, left to right, is as follows: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ [] . () (used to change the precedence of operators) - (unary) not ! empty * / div % mod + - (binary) += <> <= >= lt gt le ge == != eq ne && and || or ? : -> = ; 9.6 Reserved Words The following words are reserved for the EL and should not be used as identifiers: and or not eq ne lt gt le ge true false null instanceof empty div mod 9-10 Java Platform, Enterprise Edition The Java EE Tutorial Further Information about the Expression Language 9.7 Examples of EL Expressions Table 9–1 contains example EL expressions and the result of evaluating them. Table 9–1 Example Expressions EL Expression ${1> (4/2)} ${4.0>= 3} ${100.0 == 100} ${(10*10) ne 100} ${'a' > 'b'} ${'hip' lt 'hit'} ${4> 3} ${1.2E4 + 1.4} ${3 div 4} ${10 mod 4} ${((x, y) -> x + y)(3, 5.5)} [1,2,3,4].stream().sum() [1,3,5,2].stream().sorted().toList() ${!empty param.Add} Result false true true false false true true 12001.4 0.75 2 8.5 10 [1, 2, 3, 5] False if the request parameter named Add is null or an empty string ${pageContext.request.contextPath} The context path ${sessionScope.cart.numberOfItems} ${param['mycom.productId']} ${header["host"]} ${departments[deptName]} The value of the numberOfItems property of the session-scoped attribute named cart The value of the request parameter named mycom.productId The host The value of the entry named deptName in the departments map ${requestScope['javax.servlet.forward.servlet_path']} The value of the request-scoped attribute named #{customer.lName} #{customer.calcTotal} javax.servlet.forward.servlet_path Gets the value of the property lName from the customer bean during an initial request; sets the value of lName during a postback The return value of the method calcTotal of the customer bean 9.8 Further Information about the Expression Language For more information about the EL, see ■ ■ The Expression Language 3.0 specification: http://www.jcp.org/en/jsr/detail?id=341 The EL specification website: https://java.net/projects/el-spec/ Expression Language 9-11 Further Information about the Expression Language 9-12 Java Platform, Enterprise Edition The Java EE Tutorial 10 10Using JavaServer Faces Technology in Web Pages [11] Web pages (Facelets pages, in most cases) represent the presentation layer for web applications. The process of creating web pages for a JavaServer Faces application includes using component tags to add components to the page and wire them to backing beans, validators, listeners, converters, and other server-side objects that are associated with the page. This chapter explains how to create web pages using various types of component and core tags. In the next chapter, you will learn about adding converters, validators, and listeners to component tags to provide additional functionality to components. Many of the examples in this chapter are taken from Chapter 57, "Duke's Bookstore Case Study Example." The following topics are addressed here: ■ Setting Up a Page ■ Adding Components to a Page Using HTML Tag Library Tags ■ Using Core Tags 10.1 Setting Up a Page A typical JavaServer Faces web page includes the following elements: ■ A set of namespace declarations that declare the JavaServer Faces tag libraries ■ Optionally, the HTML head (h:head) and body (h:body) tags ■ A form tag (h:form) that represents the user input components To add the JavaServer Faces components to your web page, you need to provide the page access to the two standard tag libraries: the JavaServer Faces HTML render kit tag library and the JavaServer Faces core tag library. The JavaServer Faces standard HTML tag library defines tags that represent common HTML user interface components. The JavaServer Faces core tag library defines tags that perform core actions and are independent of a particular render kit. For a complete list of JavaServer Faces Facelets tags and their attributes, refer to the JavaServer Faces Facelets Tag Library documentation. To use any of the JavaServer Faces tags, you need to include appropriate directives at the top of each page specifying the tag libraries. For Facelets applications, the XML namespace directives uniquely identify the tag library URI and the tag prefix. Using JavaServer Faces Technology in Web Pages 10-1 Adding Components to a Page Using HTML Tag Library Tags For example, when you create a Facelets XHTML page, include namespace directives as follows: The XML namespace URI identifies the tag library location, and the prefix value is used to distinguish the tags belonging to that specific tag library. You can also use other prefixes instead of the standard h or f. However, when including the tag in the page you must use the prefix that you have chosen for the tag library. For example, in the following web page the form tag must be referenced using the h prefix because the preceding tag library directive uses the h prefix to distinguish the tags defined in the HTML tag library: The sections Adding Components to a Page Using HTML Tag Library Tags and Using Core Tags describe how to use the component tags from the JavaServer Faces standard HTML tag library and the core tags from the JavaServer Faces core tag library. 10.2 Adding Components to a Page Using HTML Tag Library Tags The tags defined by the JavaServer Faces standard HTML tag library represent HTML form components and other basic HTML elements. These components display data or accept data from the user. This data is collected as part of a form and is submitted to the server, usually when the user clicks a button. This section explains how to use each of the component tags shown in Table 10–1. Table 10–1 The Component Tags Tag h:column Functions Rendered As Appearance Represents a column of data in a data component A column of data in an HTML table A column in a table h:commandButton Submits a form to the application A button An HTML element for which the type value can be "submit", "reset", or "image" h:commandLink h:dataTable h:form Links to another page or location on a page An HTML element A link Represents a data wrapper An HTML element Represents an input form (inner tags of the form receive the data that will be submitted with the form) An HTML element A table that can be updated dynamically No appearance h:graphicImage Displays an image h:inputFile Allows a user to upload a file An HTML element An HTML element An image A field with a Browse... button 10-2 Java Platform, Enterprise Edition The Java EE Tutorial Adding Components to a Page Using HTML Tag Library Tags Table 10–1 (Cont.) The Component Tags Tag Functions Rendered As Appearance h:inputHidden h:inputSecret Allows a page author to include a hidden variable in a page An HTML element Allows a user to input a string without the actual string appearing in the field An HTML element h:inputText Allows a user to input a string An HTML element No appearance A field that displays a row of characters instead of the actual string entered A field h:inputTextarea Allows a user to enter a multiline string An HTML

This page calls the methods of the managed bean to show the log file and submit the batch job. The jobstarted.xhtml page provides a button to check the current status of the batch job and displays the results when the job finishes:

Current Status of the Job: #{jsfBean.jobStatus}

#{jsfBean.showResults()}

55.8.1.7 The Managed Bean The JsfBean managed bean submits the job to the batch runtime, checks on the status of the job, and reads the results from a text file. The startBatchJob method submits the job to the batch runtime: /* Submit the batch job to the batch runtime. * JSF Navigation method (return the name of the next page) */ Batch Processing 55-27 The webserverlog Example Application public String startBatchJob() { jobOperator = BatchRuntime.getJobOperator(); execID = jobOperator.start("webserverlog", null); return "jobstarted"; } The getJobStatus method checks the status of the job: /* Get the status of the job from the batch runtime */ public String getJobStatus() { return jobOperator.getJobExecution(execID).getBatchStatus().toString(); } The showResults method reads the results from a text file. 55.8.2 Running the webserverlog Example Application You can use either NetBeans IDE or Maven to build, package, deploy, and run the webserverlog example application. 55.8.2.1 To Run the webserverlog Example Application Using NetBeans IDE 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. From the File menu, choose Open Project. 3. In the Open Project dialog box, navigate to: tut-install/examples/batch 4. Select the webserverlog folder. 5. Click Open Project. 6. In the Projects tab, right-click the webserverlog project and select Run. This command builds and packages the application into a WAR file, webserverlog.war, located in the target/ directory; deploys it to the server; and launches a web browser window at the following URL: http://localhost:8080/webserverlog/ 55.8.2.2 To Run the webserverlog Example Application Using Maven 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. In a terminal window, go to: tut-install/examples/batch/webserverlog/ 3. Enter the following command to deploy the application: mvn install 4. Open a web browser window at the following URL: http://localhost:8080/webserverlog/ 55-28 Java Platform, Enterprise Edition The Java EE Tutorial The phonebilling Example Application 55.9 The phonebilling Example Application The phonebilling example application, located in the tut-install/examples/batch/phonebilling/ directory, demonstrates how to use the batch framework in Java EE to implement a phone billing system. This example application processes a log file of phone calls and creates a bill for each customer. 55.9.1 Architecture of the phonebilling Example Application The phonebilling example application consists of the following elements. ■ A job definition file (phonebilling.xml) that uses the Job Specification Language (JSL) to define a batch job with two chunk steps. The first step reads call records from a log file and associates them with a bill. The second step computes the amount due and writes each bill to a text file. ■ A Java class (CallRecordLogCreator) that creates the log file for the batch job. This is an auxiliary component that does not demonstrate any key functionality in this example. ■ ■ ■ ■ Two Java Persistence API (JPA) entities (CallRecord and PhoneBill) that represent call records and customer bills. The application uses a JPA entity manager to store instances of these entities in a database. Three batch artifacts (CallRecordReader, CallRecordProcessor, and CallRecordWriter) that implement the first step of the application. This step reads call records from the log file, associates them with a bill, and stores them in a database. Four batch artifacts (BillReader, BillProcessor, BillWriter, and BillPartitionMapper) that implement the second step of the application. This step is a partitioned step that gets each bill from the database, calculates the amount due, and writes it to a text file. Two Facelets pages (index.xhtml and jobstarted.xhtml) that provide the front end of the batch application. The first page shows the log file that will be processed by the batch job, and the second page enables the user to check on the status of the job and shows the resulting bill for each customer. ■ A managed bean (JsfBean) that is accessed from the Facelets pages. The bean submits the job to the batch runtime, checks on the status of the job, and reads the text files for each bill. 55.9.1.1 The Job Definition File The phonebilling.xml job definition file is located in the WEB-INF/classes/META-INF/batch-jobs/ directory. The file specifies three job-level properties and two steps: ... ... Batch Processing 55-29 The phonebilling Example Application The first step is defined as follows: This step is a normal chunk step that specifies the batch artifacts that implement each phase of the step. The batch artifact names are not fully qualified class names, so the batch artifacts are CDI beans annotated with @Named. The second step is defined as follows: This step is a partitioned chunk step. The partition plan is specified through the BillPartitionMapper artifact instead of using the plan element. 55.9.1.2 The CallRecord and PhoneBill Entities The CallRecord entity is defined as follows: @Entity public class CallRecord implements Serializable { @Id @GeneratedValue private Long id; @Temporal(TemporalType.DATE) private Date datetime; private String fromNumber; private String toNumber; private int minutes; private int seconds; private BigDecimal price; public CallRecord() { } public CallRecord(String datetime, String from, String to, int min, int sec) throws ParseException { ... } public CallRecord(String jsonData) throws ParseException { ... } /* ... Getters and setters ... */ } 55-30 Java Platform, Enterprise Edition The Java EE Tutorial The phonebilling Example Application The id field is generated automatically by the JPA implementation to store and retrieve CallRecord objects to and from a database. The second constructor creates a CallRecord object from an entry of JSON data in the log file using the JSON Processing API. Log entries look as follows: {"datetime":"03/01/2013 04:03","from":"555-0101", "to":"555-0114","length":"03:39"} The PhoneBill entity is defined as follows: @Entity public class PhoneBill implements Serializable { @Id private String phoneNumber; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST) @OrderBy("datetime ASC") private List calls; private BigDecimal amountBase; private BigDecimal taxRate; private BigDecimal tax; private BigDecimal amountTotal; public PhoneBill() { } public PhoneBill(String number) { this.phoneNumber = number; calls = new ArrayList<>(); } public void addCall(CallRecord call) { calls.add(call); } public void calculate(BigDecimal taxRate) { ... } /* ... Getters and setters ... * } The OneToMany annotation defines the relationship between a bill and its call records. The FetchType.EAGER attribute specifies that the collection should be retrieved eagerly. The CascadeType.PERSIST attribute indicates that the elements in the call list should be automatically persisted when the phone bill is persisted. The OrderBy annotation defines an order for retrieving the elements of the call list from the database. The batch artifacts use instances of these two entities as items to read, process, and write. For more information on the Java Persistence API, see Chapter 37, "Introduction to the Java Persistence API". For more information on the JSON Processing API, see Chapter 19, "JSON Processing". 55.9.1.3 The Call Records Chunk Step The first step is composed of the CallRecordReader, CallRecordProcessor, and CallRecordWriter batch artifacts. The CallRecordReader artifact reads call records from the log file: @Dependent @Named("CallRecordReader") Batch Processing 55-31 The phonebilling Example Application public class CallRecordReader implements ItemReader { private ItemNumberCheckpoint checkpoint; private String fileName; private BufferedReader breader; @Inject JobContext jobCtx; /* ... Override the open, close, readItem, * and checkpointInfo methods ... */ } The open method reads the log_filename property and opens the log file with a buffered reader: fileName = jobCtx.getProperties().getProperty("log_file_name"); breader = new BufferedReader(new FileReader(fileName)); If a checkpoint object is provided, the open method advances the reader up to the last checkpoint. Otherwise, this method creates a new checkpoint object. The checkpoint object keeps track of the line number from the last committed chunk. The readItem method returns a new CallRecord object or null at the end of the log file: @Override public Object readItem() throws Exception { /* Read a line from the log file and * create a CallRecord from JSON */ String callEntryJson = breader.readLine(); if (callEntryJson != null) { checkpoint.nextItem(); return new CallRecord(callEntryJson); } else return null; } The CallRecordProcessor artifact obtains the airtime price from the job properties, calculates the price of each call, and returns the call object. This artifact overrides only the processItem method. The CallRecordWriter artifact associates each call record with a bill and stores the bill in the database. This artifact overrides the open, close, writeItems, and checkpointInfo methods. The writeItems method looks like this: @Override public void writeItems(List callList) throws Exception { for (Object callObject : callList) { CallRecord call = (CallRecord) callObject; PhoneBill bill = em.find(PhoneBill.class, call.getFromNumber()); if (bill == null) { /* No bill for this customer yet, create one */ bill = new PhoneBill(call.getFromNumber()); bill.addCall(call); em.persist(bill); } else { /* Add call to existing bill */ bill.addCall(call); } } } 55-32 Java Platform, Enterprise Edition The Java EE Tutorial The phonebilling Example Application 55.9.1.4 The Phone Billing Chunk Step The second step is composed of the BillReader, BillProcessor, BillWriter, and BillPartitionMapper batch artifacts. This step gets the phone bills from the database, computes the tax and total amount due, and writes each bill to a text file. Since the processing of each bill is independent of the others, this step can be partitioned and run in more than one thread. The BillPartitionMapper artifact specifies the number of partitions and the parameters for each partition. In this example, the parameters represent the range of items each partition should process. The artifact obtains the number of bills in the database to calculate these ranges. It provides a partition plan object that overrides the getPartitions and getPartitionProperties methods of the PartitionPlan interface. The getPartitions method looks like this: @Override public Properties[] getPartitionProperties() { /* Assign an (approximately) equal number of elements * to each partition. */ long totalItems = getBillCount(); long partItems = (long) totalItems / getPartitions(); long remItems = totalItems % getPartitions(); /* Populate a Properties array. Each Properties element * in the array corresponds to a partition. */ Properties[] props = new Properties[getPartitions()]; for (int i = 0; i < getPartitions(); i++) { props[i] = new Properties(); props[i].setProperty("firstItem", String.valueOf(i * partItems)); /* Last partition gets the remainder elements */ if (i == getPartitions() - 1) { props[i].setProperty("numItems", String.valueOf(partItems + remItems)); } else { props[i].setProperty("numItems", String.valueOf(partItems)); } return props; } The BillReader artifact obtains the partition parameters as follows: @Dependent @Named("BillReader") public class BillReader implements ItemReader { @Inject @BatchProperty(name = "firstItem") private String firstItemValue; @Inject @BatchProperty(name = "numItems") private String numItemsValue; private ItemNumberCheckpoint checkpoint; @PersistenceContext private EntityManager em; private Iterator iterator; @Override Batch Processing 55-33 The phonebilling Example Application public void open(Serializable ckpt) throws Exception { /* Get the range of items to work on in this partition */ long firstItem0 = Long.parseLong(firstItemValue); long numItems0 = Long.parseLong(numItemsValue); if (ckpt == null) { /* Create a checkpoint object for this partition */ checkpoint = new ItemNumberCheckpoint(); checkpoint.setItemNumber(firstItem0); checkpoint.setNumItems(numItems0); } else { checkpoint = (ItemNumberCheckpoint) ckpt; } /* Adjust range for this partition from the checkpoint */ long firstItem = checkpoint.getItemNumber(); long numItems = numItems0 - (firstItem - firstItem0); ... } ... } This artifact also obtains an iterator to read items from the JPA entity manager: /* Obtain an iterator for the bills in this partition */ String query = "SELECT b FROM PhoneBill b ORDER BY b.phoneNumber"; Query q = em.createQuery(query).setFirstResult((int) firstItem) .setMaxResults((int) numItems); iterator = q.getResultList().iterator(); The BillProcessor artifact iterates over the list of call records in a bill and calculates the tax and total amount due for each bill. The BillWriter artifact writes each bill to a plain text file. 55.9.1.5 The JavaServer Faces Pages The index.xhtml page contains a text area that shows the log file of call records. The page provides a button for the user to submit the batch job and navigate to the next page:

The Phone Billing Example Application

Log file

The batch job analyzes the following log file:

This page calls the methods of the managed bean to show the log file and submit the batch job. The jobstarted.xhtml page provides a button to check the current status of the batch job and displays the bills when the job finishes:

Current Status of the Job: #{jsfBean.jobStatus}

55.9.1.6 The Managed Bean The JsfBean managed bean submits the job to the batch runtime, checks on the status of the job, and reads the text files for each bill. The startBatchJob method of the bean submits the job to the batch runtime: /* Submit the batch job to the batch runtime. * JSF Navigation method (return the name of the next page) */ public String startBatchJob() { jobOperator = BatchRuntime.getJobOperator(); execID = jobOperator.start("phonebilling", null); return "jobstarted"; } The getJobStatus method of the bean checks the status of the job: /* Get the status of the job from the batch runtime */ public String getJobStatus() { return jobOperator.getJobExecution(execID).getBatchStatus().toString(); } The getRowList method of the bean creates a list of bills to be displayed on the jobstarted.xhtml JSF page using a table. 55.9.2 Running the phonebilling Example Application You can use either NetBeans IDE or Maven to build, package, deploy, and run the phonebilling example application. 55.9.2.1 To Run the phonebilling Example Application Using NetBeans IDE 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. From the File menu, choose Open Project. 3. In the Open Project dialog box, navigate to: tut-install/examples/batch 4. Select the phonebilling folder. 5. Click Open Project. 6. In the Projects tab, right-click the phonebilling project and select Run. This command builds and packages the application into a WAR file, phonebilling.war, located in the target/ directory; deploys it to the server; and launches a web browser window at the following URL: http://localhost:8080/phonebilling/ Batch Processing 55-35 Further Information about Batch Processing 55.9.2.2 To Run the phonebilling Example Application Using Maven 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. In a terminal window, go to: tut-install/examples/batch/phonebilling/ 3. Enter the following command to deploy the application: mvn install 4. Open a web browser window at the following URL: http://localhost:8080/phonebilling/ 55.10 Further Information about Batch Processing For more information on batch processing in Java EE, see the Batch Applications for the Java Platform specification: http://www.jcp.org/en/jsr/detail?id=352 55-36 Java Platform, Enterprise Edition The Java EE Tutorial 56 56Concurrency Utilities for Java EE [57] This chapter describes Concurrency Utilities for Java EE, which are specified by JSR 236. This chapter covers the following topics: ■ Concurrency Basics ■ Main Components of the Concurrency Utilities ■ ■ ■ ■ ■ Concurrency and Transactions Concurrency and Security The jobs Concurrency Example The taskcreator Concurrency Example Further Information about the Concurrency Utilities 56.1 Concurrency Basics Concurrency is the concept of executing two or more tasks at the same time (in parallel). Tasks may include methods (functions), parts of a program, or even other programs. With current computer architectures, support for multiple cores and multiple processors in a single CPU is very common. The Java Platform has always offered support for concurrent programming, which was the basis for implementing many of the services offered by Java EE containers. At Java SE 5, additional high-level API support for concurrency was provided by the java.util.concurrent package. Prior to Java EE 7, there were no specific APIs that allowed enterprise developers to use concurrency utilities in a safely standard manner. The Java EE web and EJB containers instantiate objects using container-managed thread pools. Therefore, using Java SE concurrent APIs to instantiate Thread objects was strongly discouraged. If a developer creates a new (non-managed) Thread object, the container could not guarantee that other Java EE platform services (for example, transactions and security) would be part of this Thread. 56.1.1 Threads and Processes The two main concurrency concepts are processes and threads. Processes are primarily associated with applications running on the operating system (OS). A process has specific runtime resources to interact with the underlying OS and allocate other resources, such as its own memory, just as the JVM process does. A JVM is in fact a process. Concurrency Utilities for Java EE 56-1 Main Components of the Concurrency Utilities The Java programming language and platform are primarily concerned with threads. Threads share some features with processes, since both consume resources from the OS or the execution environment. But threads are easier to create and consume many fewer resources than a process. Because threads are so lightweight, any modern CPU that has a couple of cores and a few gigabytes of RAM can handle thousands of threads in a single JVM process. The precise number of threads will depend on the combined output of the CPU, OS, and RAM available, as well as on correct configuration (tuning) of the JVM. Although concurrent programming solves many problems and can improve performance for most applications, there are a number of situations where multiple execution lines (threads or processes) can cause major problems. These situations include the following: ■ Deadlocks ■ ■ ■ Thread starvation Concurrent accessing of shared resources Situations when the program generates incorrect data 56.2 Main Components of the Concurrency Utilities Concurrent resources are managed objects that provide concurrency capabilities to Java EE applications. In GlassFish Server, you configure concurrent resources and then make them available for use by application components such as servlets and enterprise beans. Concurrent resources are accessed through JNDI lookup or resource injection. The primary components of the concurrency utilities are as follows. ■ ■ ■ ■ ManagedExecutorService: A managed executor service is used by applications to execute submitted tasks asynchronously. Tasks are executed on threads that are started and managed by the container. The context of the container is propagated to the thread executing the task. For example, by using an ManagedExecutorService.submit() call, a task, such as the GenerateReportTask, could be submitted to execute at a later time and then, by using the Future object callback, retrieve the result when it becomes available. ManagedScheduledExecutorService: A managed scheduled executor service is used by applications to execute submitted tasks asynchronously at specific times. Tasks are executed on threads that are started and managed by the container. The context of the container is propagated to the thread executing the task. The API provides the scheduling functionality that allows users to set a specific date/time for the Task execution programmatically in the application. ContextService: A context service is used to create dynamic proxy objects that capture the context of a container and enable applications to run within that context at a later time or be submitted to a Managed Executor Service. The context of the container is propagated to the thread executing the task. ManagedThreadFactory: A managed thread factory is used by applications to create managed threads. The threads are started and managed by the container. The context of the container is propagated to the thread executing the task. This object can also be used to provide custom factories for specific use cases (with custom Threads) and, for example, set specific/proprietary properties to these objects. 56-2 Java Platform, Enterprise Edition The Java EE Tutorial 56.3 Concurrency and Transactions The jobs Concurrency Example The most basic operations for transactions are commit and rollback, but, in a distributed environment with concurrent processing, it can be difficult to guarantee that commit or rollback operations will be successfully processed, and the transaction can be spread among different threads, CPU cores, physical machines, and networks. Ensuring that a rollback operation will successfully execute in such a scenario is crucial. Concurrency Utilities relies on the Java Transaction API (JTA) to implement and support transactions on its components through javax.transaction.UserTransaction, allowing application developers to explicitly manage transaction boundaries. More information is available in the JTA specification. Optionally, context objects can begin, commit, or roll back transactions, but these objects cannot enlist in parent component transactions. The following code snippet illustrates a Runnable task that obtains a UserTransaction and then starts and commits a transaction while interacting with other transactional components, such as an enterprise bean and a database: public class MyTransactionalTask implements Runnable { UserTransaction ut = ... // obtained through JNDI or injection public void run() { // Start a transaction ut.begin(); // Invoke a Service or an EJB myEJB.businessMethod(); // Update a database entity using an XA JDBC driver myEJB.updateCustomer(customer); // Commit the transaction ut.commit(); } } 56.4 Concurrency and Security Concurrency Utilities for Java EE defers most security decisions to the application server implementation. If, however, the container supports a security context, that context can be propagated to the thread of execution. The ContextService can support several runtime behaviors, and the security attribute, if enabled, will propagate the container security principal. 56.5 The jobs Concurrency Example This section describes a very basic example that shows how to use some of the basic concurrency features in an enterprise application. Specifically, this example uses one of the main components of Concurrency Utilities for Java EE, a Managed Executor Service. The example demonstrates a scenario where a RESTful web service, exposed as a public API, is used to submit generic jobs for execution. These jobs are processed in the background. Each job prints a "Starting" and a "Finished" message at the beginning Concurrency Utilities for Java EE 56-3 The jobs Concurrency Example and end of the execution. Also, to simulate background processing, each job takes 10 seconds to execute. The RESTful service exposes two methods: ■ ■ /token: Exposed as a GET method that registers and returns valid API tokens /process: Exposed as a POST method that receives a jobID query parameter, which is the identifier for the job to be executed, and a custom HTTP header named X-REST-API-Key, which will be used internally to validate requests with tokens The token is used to differentiate the Quality of Service (QoS) offered by the API. Users that provide a token in a service request can process multiple concurrent jobs. However, users that do not provide a token can process only one job at a time. Since every job takes 10 seconds to execute, users that provide no token will be able to execute only one call to the service every 10 seconds. For users that provide a token, processing will be much faster. This differentiation is made possible by the use of two different Managed Executor Services, one for each type of request. 56.5.1 Running the jobs Example After configuring GlassFish Server by adding two Managed Executor Services, you can use either NetBeans IDE or Maven to build, package, deploy, and run the jobs example. 56.5.1.1 To Configure GlassFish Server for the Basic Concurrency Example To configure GlassFish Server, follow these steps. 1. Open the Administration Console at http://localhost:4848. 2. Expand the Resources node. 3. Expand the Concurrent Resources node. 4. Click Managed Executor Services. 5. On the Managed Executor Services page, click New to open the New Managed Executor Services page. 6. In the JNDI Name field, enter MES_High to create the high-priority Managed Executor Service. Use the following settings (keep the default values for other settings): ■ Thread Priority: 10 ■ Core Size: 2 ■ Maximum Pool Size: 5 ■ Task Queue Capacity: 2 7. Click OK. 8. On the On the Managed Executor Services page, click New again. 9. In the JNDI Name field, enter MES_Low to create the low-priority Managed Executor Service. Use the following settings (keep the default values for other settings): ■ Thread Priority: 1 ■ Core Size: 1 56-4 Java Platform, Enterprise Edition The Java EE Tutorial The jobs Concurrency Example ■ Maximum Pool Size: 1 ■ Task Queue Capacity: 0 10. Click OK. 56.5.1.2 To Build, Package, and Deploy the jobs Example Using NetBeans IDE 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. From the File menu, choose Open Project. 3. In the Open Project dialog box, navigate to: tut-install/examples/concurrency 4. Select the jobs folder. 5. Click Open Project. 6. In the Projects tab, right-click the jobs project and select Build. This command builds and deploys the application. 56.5.1.3 To Build, Package, and Deploy the jobs Example Using Maven 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. In a terminal window, go to: tut-install/examples/concurrency/jobs 3. Enter the following command to build and deploy the application: mvn install 56.5.1.4 To Run the jobs Example and Submit Jobs with Low Priority To run the example as a user who submits jobs with low priority, follow these steps: 1. In a web browser, enter the following URL: http://localhost:8080/jobs 2. In the Jobs Client page, enter the value 1 in the Enter a JobID field, enter nothing in the Enter a Token field, then click Submit Job. The following message should be displayed at the bottom of the page: Job 1 successfully submitted The server log includes the following messages: INFO: Invalid or missing token! INFO: Task started LOW-1 INFO: Job 1 successfully submitted INFO: Task finished LOW-1 You submitted a job with low priority. This means that you cannot submit another job for 10 seconds. If you try to do so, the RESTful API will return a service unavailable (HTTP 503) response and the following message will be displayed at the bottom of the page: Job 2 was NOT submitted Concurrency Utilities for Java EE 56-5 The jobs Concurrency Example The server log will include the following messages: INFO: Invalid or missing token! INFO: Job 1 successfully submitted INFO: Task started LOW-1 INFO: Invalid or missing token! INFO: Job 2 was NOT submitted INFO: Task finished LOW-1 56.5.1.5 To Run the jobs Example and Submit Jobs with High Priority To run the example as a user who submits jobs with high priority, follow these steps: 1. In a web browser, enter the following URL: http://localhost:8080/jobs 2. In the Jobs Client page, enter a value of one to ten digits in the Enter a JobID field. 3. Click the here link on the line "Get a token here" to get a token. The page that displays the token will open in a new tab. 4. Copy the token and return to the Jobs Client page. 5. Paste the token in the Enter a Token field, then click Submit Job. A message like the following should be displayed at the bottom of the page: Job 11 successfully submitted The server log includes the following messages: INFO: Token accepted. Execution with high priority. INFO: Task started HIGH-11 INFO: Job 11 successfully submitted INFO: Task finished HIGH-11 You submitted a job with high priority. This means that you can submit multiple jobs, each with a token, and not face the 10 second per job restriction that the low priority submitters face. If you submit 3 jobs with tokens in rapid succession, messages like the following will be displayed at the bottom of the page: Job 1 was submitted Job 2 was submitted Job 3 was submitted The server log will include the following messages: INFO: Token accepted. Execution with high priority. INFO: Task started HIGH-1 INFO: Job 1 successfully submitted INFO: Token accepted. Execution with high priority. INFO: Task started HIGH-2 INFO: Job 2 successfully submitted INFO: Task finished HIGH-1 INFO: Token accepted. Execution with high priority. INFO: Task started HIGH-3 INFO: Job 3 successfully submitted INFO: Task finished HIGH-2 INFO: Task finished HIGH-3 56-6 Java Platform, Enterprise Edition The Java EE Tutorial 56.6 The taskcreator Concurrency Example The taskcreator Concurrency Example The taskcreator example demonstrates how to use Concurrency Utilities for Java EE to run tasks immediately, periodically, or after a fixed delay. This example provides a JavaServer Faces interface that enables users to submit tasks to be executed and displays information messages for each task. The example uses the Managed Executor Service to run tasks immediately and the Managed Scheduled Executor Service to run tasks periodically or after a fixed delay. (See Main Components of the Concurrency Utilities for information about these services.) The taskcreator example consists of the following components. ■ A JavaServer Faces page (index.xhtml) that contains three elements: a form to submit tasks, a task execution log, and a form to cancel periodic tasks. This page submits Ajax requests to create and cancel tasks. This page also receives WebSocket messages, using JavaScript code to update the task execution log. ■ A CDI managed bean (TaskCreatorBean) that processes the requests from the JavaServer Faces page. This bean invokes the methods in TaskEJB to submit new tasks and to cancel periodic tasks. ■ An enterprise bean (TaskEJB) that obtains executor service instances using resource injection and submits tasks for execution. This bean is also a JAX-RS web service endpoint. The tasks send information messages to this endpoint. ■ A WebSocket endpoint (InfoEndpoint) that the enterprise bean uses to send information messages to the clients. ■ A task class (Task) that implements the Runnable interface. The run method in this class sends information messages to the web service endpoint in TaskEJB and sleeps for 1.5 seconds. Figure 56–1 shows the architecture of the taskcreator example. Figure 56–1 Architecture of the taskcreator Example TaskCreatorBean index.xhtml Request new tasks Get execution log updates Request AJAX page updates using a WebSocket message TaskEJB Request updates for parts of the page InfoEndpoint Schedule new tasks Task Send info messages to web service The TaskEJB class obtains the default executor service objects from the application server as follows: @Resource(name="java:comp/DefaultManagedExecutorService") ManagedExecutorService mExecService; Concurrency Utilities for Java EE 56-7 The taskcreator Concurrency Example @Resource(name="java:comp/DefaultManagedScheduledExecutorService") ManagedScheduledExecutorService sExecService; The submitTask method in TaskEJB uses these objects to submit tasks for execution as follows: public void submitTask(Task task, String type) { /* Use the managed executor objects from the app server */ switch (type) { case "IMMEDIATE": mExecService.submit(task); break; case "DELAYED": sExecService.schedule(task, 3, TimeUnit.SECONDS); break; case "PERIODIC": ScheduledFuture fut; fut = sExecService.scheduleAtFixedRate(task, 0, 8, TimeUnit.SECONDS); periodicTasks.put(task.getName(), fut); break; } } For periodic tasks, TaskEJB keeps a reference to the ScheduledFuture object, so that the user can cancel the task at any time. 56.6.1 Running the taskcreator Example This section describes how to build, package, deploy, and run the taskcreator example using NetBeans IDE or Maven. 56.6.1.1 To Build, Package, and Deploy the taskcreator Example Using NetBeans IDE 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. From the File menu, choose Open Project. 3. In the Open Project dialog box, navigate to: tut-install/examples/concurrency 4. Select the taskcreator folder. 5. Click Open Project. 6. In the Projects tab, right-click the taskcreator project and select Build. This command builds and deploys the application. 56.6.1.2 To Build, Package, and Deploy the taskcreator Example Using Maven 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. In a terminal window, go to: tut-install/examples/concurrency/taskcreator 3. Enter the following command to build and deploy the application: 56-8 Java Platform, Enterprise Edition The Java EE Tutorial Further Information about the Concurrency Utilities mvn install 56.6.1.3 To Run the taskcreator Example 1. Open the following URL in a web browser: http://localhost:8080/taskcreator/ The page contains a form to submit tasks, a task execution log, and a form to cancel periodic tasks. 2. Select the Immediate task type, enter a task name, and click the Submit button. Messages like the following appear in the task execution log: 12:40:47 - IMMEDIATE Task TaskA finished 12:40:45 - IMMEDIATE Task TaskA started 3. Select the Delayed (3 sec) task type, enter a task name, and click the Submit button. Messages like the following appear in the task execution log: 12:43:26 - DELAYED Task TaskB finished 12:43:25 - DELAYED Task TaskB started 12:43:22 - DELAYED Task TaskB submitted 4. Select the Periodic (8 sec) task type, enter a task name, and click the Submit button. Messages like the following appear in the task execution log: 12:45:25 - PERIODIC Task TaskC finished run #2 12:45:23 - PERIODIC Task TaskC started run #2 12:45:17 - PERIODIC Task TaskC finished run #1 12:45:15 - PERIODIC Task TaskC started run #1 You can add more than one periodic task. To cancel a periodic task, select it from the form and click Cancel Task. 56.7 Further Information about the Concurrency Utilities For more information about concurrency, see ■ ■ ■ Concurrency Utilities for Java EE specification: http://jcp.org/en/jsr/detail?id=236 Concurrency Utilities specification: http://jcp.org/en/jsr/detail?id=166 Concurrency Lesson in The Java Tutorials: http://docs.oracle.com/javase/tutorial/essential/concurrency/ Concurrency Utilities for Java EE 56-9 Further Information about the Concurrency Utilities 56-10 Java Platform, Enterprise Edition The Java EE Tutorial Part XII Part XII Case Studies Part XII presents case studies that use a variety of Java EE technologies. This part contains the following chapters: ■ ■ ■ Chapter 57, "Duke's Bookstore Case Study Example" Chapter 58, "Duke's Tutoring Case Study Example" Chapter 59, "Duke's Forest Case Study Example" 57 57Duke's Bookstore Case Study Example [58] The Duke's Bookstore example is a simple e-commerce application that illustrates some of the more advanced features of JavaServer Faces technology in combination with Contexts and Dependency Injection for Java EE (CDI), enterprise beans, and the Java Persistence API. Users can select books from an image map, view the bookstore catalog, and purchase books. No security is used in this application. The following topics are addressed here: ■ Design and Architecture of Duke's Bookstore ■ ■ The Duke's Bookstore Interface Running the Duke's Bookstore Case Study Application 57.1 Design and Architecture of Duke's Bookstore Duke's Bookstore is a simple web application that uses many features of JavaServer Faces technology, in addition to other Java EE 7 features: ■ JavaServer Faces technology, as well as Contexts and Dependency Injection for Java EE (CDI) – A set of Facelets pages, along with a template, provides the user interface to the application. – CDI managed beans are associated with each of the Facelets pages. – A custom image map component on the front page allows you to select a book to enter the store. Each area of the map is represented by a JavaServer Faces managed bean. Text hyperlinks are also provided for accessibility. – Action listeners are registered on the image map and the text links. These listeners retrieve the ID value for the selected book and store it in the session map so it can be retrieved by the managed bean for the next page. – The h:dataTable tag is used to render the book catalog and shopping cart contents dynamically. – A custom converter is registered on the credit card field on the checkout page, bookcashier.xhtml, which also uses an f:validateRegEx tag to ensure that the input is correctly formatted. – A value-change listener is registered on the name field on bookcashier.xhtml. This listener saves the name in a parameter so the following page, bookreceipt.xhtml, can access it. ■ Enterprise beans: Local, no-interface-view stateless session bean and singleton bean Duke's Bookstore Case Study Example 57-1 The Duke's Bookstore Interface ■ A Java Persistence API entity The packages of the Duke's Bookstore application, located in the tut-install/examples/case-studies/dukes-bookstore/src/main/java/javaeetutoria l/dukesbookstore/ directory, are as follows: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ components: Includes the custom UI component classes, MapComponent and AreaComponent converters: Includes the custom converter class, CreditCardConverter ejb: Includes two enterprise beans: – A singleton bean, ConfigBean, that initializes the data in the database – A stateless session bean, BookRequestBean, that contains the business logic to manage the entity entity: Includes the Book entity class exceptions: Includes three exception classes listeners: Includes the event handler and event listener classes model: Includes a model JavaBeans class renderers: Includes the custom renderers for the custom UI component classes web.managedbeans: Includes the managed beans for the Facelets pages web.messages: Includes the resource bundle files for localized messages 57.2 The Duke's Bookstore Interface This section provides additional detail regarding the components of the Duke's Bookstore example and how they interact. 57.2.1 The Book Java Persistence API Entity The Book entity, located in the dukesbookstore.entity package, encapsulates the book data stored by Duke's Bookstore. The Book entity defines attributes used in the example: ■ A book ID ■ ■ ■ ■ The author's first name The author's surname The title The price ■ Whether the book is on sale ■ The publication year ■ A description of the book ■ The number of copies in the inventory The Book entity also defines a simple named query, findBooks. 57-2 Java Platform, Enterprise Edition The Java EE Tutorial The Duke's Bookstore Interface 57.2.2 Enterprise Beans Used in Duke's Bookstore Two enterprise beans located in the dukesbookstore.ejb package provide the business logic for Duke's Bookstore. ■ ■ BookRequestBean is a stateful session bean that contains the business methods for the application. The methods create, retrieve, and purchase books, and update the inventory for a book. To retrieve the books, the getBooks method calls the findBooks named query defined in the Book entity. ConfigBean is a singleton session bean used to create the books in the catalog when the application is initially deployed. It calls the createBook method defined in BookRequestBean. 57.2.3 Facelets Pages and Managed Beans Used in Duke's Bookstore The Duke's Bookstore application uses Facelets and its templating features to display the user interface. The Facelets pages interact with a set of CDI managed beans that act as backing beans, providing the underlying properties and methods for the user interface. The front page also interacts with the custom components used by the application. The application uses the following Facelets pages, which are located in the tut-install/examples/case-studies/dukes-bookstore/src/main/webapp/ directory. ■ ■ ■ ■ ■ ■ ■ bookstoreTemplate.xhtml: The template file, which specifies a header used on every page as well as the style sheet used by all the pages. The template also retrieves the language set in the web browser. Uses the LocaleBean managed bean. index.xhtml: Landing page, which lays out the custom map and area components using managed beans configured in the faces-config.xml file and allows the user to select a book and advance to the bookstore.xhtml page. bookstore.xhtml: Page that allows the user to obtain details on the selected book or the featured book, to add either book to the shopping cart, and to advance to the bookcatalog.xhtml page. Uses the BookstoreBean managed bean. bookdetails.xhtml: Page that shows details on a book selected from bookstore.xhtml or other pages and allows the user to add the book to the cart and/or advance to the bookcatalog.xhtml page. Uses the BookDetailsBean managed bean. bookcatalog.xhtml: Page that displays the books in the catalog and allows the user to add books to the shopping cart, view the details for any book, view the shopping cart, empty the shopping cart, or purchase the books in the shopping cart. Uses the BookstoreBean, CatalogBean, and ShoppingCart managed beans. bookshowcart.xhtml: Page that displays the contents of the shopping cart and allows the user to remove items, view the details for an item, empty the shopping cart, purchase the books in the shopping cart, or return to the catalog. Uses the ShowCartBean and ShoppingCart managed beans. bookcashier.xhtml: Page that allows the user to purchase books, specify a shipping option, subscribe to newsletters, or join the Duke Fan Club with a purchase over a certain amount. Duke's Bookstore Case Study Example 57-3 The Duke's Bookstore Interface Uses the CashierBean and ShoppingCart managed beans. bookreceipt.xhtml: Page that confirms the user's purchase and allows the user to return to the catalog page to continue shopping. Uses the CashierBean managed bean. bookordererror.xhtml: Page rendered by CashierBean if the bookstore has no more copies of a book that was ordered. ■ ■ The application uses the following managed beans, which are located in the tut-install/examples/case-studies/dukes-bookstore/src/main/java/javaeetutoria l/dukesbookstore/web/managedbeans/ directory. ■ ■ ■ ■ ■ ■ ■ ■ ■ AbstractBean: Contains utility methods called by other managed beans. BookDetailsBean: Backing bean for the bookdetails.xhtml page. Specifies the name details. BookstoreBean: Backing bean for the bookstore.xhtml page. Specifies the name store. CashierBean: Backing bean for the bookcashier.xhtml and bookreceipt.xhtml pages. CatalogBean: Backing bean for the bookcatalog.xhtml page. Specifies the name catalog. LocaleBean: Managed bean that retrieves the current locale; used on each page. ShoppingCart: Backing bean used by the bookcashier.xhtml, bookcatalog.xhtml, and bookshowcart.xhtml pages. Specifies the name cart. ShoppingCartItem: Contains methods called by ShoppingCart, CatalogBean, and ShowCartBean. ShowCartBean: Backing bean for the bookshowcart.xhtml page. Specifies the name showcart. 57.2.4 Custom Components and Other Custom Objects Used in Duke's Bookstore The map and area custom components for Duke's Bookstore, along with associated renderer, listener, and model classes, are defined in the following packages in the tut-install/examples/case-studies/dukes-bookstore/src/main/java/javaeetutoria l/dukesbookstore/ directory. ■ ■ ■ ■ components: Contains the MapComponent and AreaComponent classes. See Creating Custom Component Classes. listeners: Contains the AreaSelectedEvent class, along with other listener classes. See Handling Events for Custom Components. model: Contains the ImageArea class. See Configuring Model Data for more information. renderers: Contains the MapRenderer and AreaRenderer classes. See Delegating Rendering to a Renderer. The tut-install/examples/case-studies/dukes-bookstore/src/java/dukesbookstore/ directory also contains a custom converter and other custom listeners not specifically tied to the custom components. ■ converters: Contains the CreditCardConverter class. See Creating and Using a Custom Converter. 57-4 Java Platform, Enterprise Edition The Java EE Tutorial The Duke's Bookstore Interface ■ listeners: Contains the LinkBookChangeListener, MapBookChangeListener, and NameChanged classes. See Implementing an Event Listener. 57.2.5 Properties Files Used in Duke's Bookstore The strings used in the Duke's Bookstore application are encapsulated into resource bundles to allow the display of localized strings in multiple locales. The properties files, located in the tut-install/examples/case-studies/dukes-bookstore/src/main/java/javaeetutoria l/dukesbookstore/web/messages/ directory, consist of a default file containing English strings and three additional files for other locales. The files are as follows: ■ ■ ■ ■ Messages.properties: Default file, containing English strings Messages_de.properties: File containing German strings Messages_es.properties: File containing Spanish strings Messages_fr.properties: File containing French strings The language setting in the user's web browser determines which locale is used. The html tag in bookstoreTemplate.xhtml retrieves the language setting from the language property of LocaleBean: javaeetutorial.dukesbookstore.web.messages.Messages bundle en de es fr This configuration means that in the Facelets pages, messages are retrieved using the prefix bundle with the key found in the Messages_locale.properties file, as in the following example from the index.xhtml page: In Messages.properties, the key string is defined as follows: ChooseBook=Choose a Book from our Catalog 57.2.6 Deployment Descriptors Used in Duke's Bookstore The following deployment descriptors are used in Duke's Bookstore: Duke's Bookstore Case Study Example 57-5 Running the Duke's Bookstore Case Study Application ■ ■ ■ ■ src/main/resources/META-INF/persistence.xml: The Java Persistence API configuration file src/main/webapp/WEB-INF/bookstore.taglib.xml: The tag library descriptor file for the custom components src/main/webapp/WEB-INF/faces-config.xml: The JavaServer Faces configuration file, which configures the managed beans for the map component as well as the resource bundles for the application src/main/webapp/WEB-INF/web.xml: The web application configuration file 57.3 Running the Duke's Bookstore Case Study Application You can use either NetBeans IDE or Maven to build, package, deploy, and run the Duke's Bookstore application. 57.3.1 To Build and Deploy Duke's Bookstore Using NetBeans IDE 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. From the File menu, choose Open Project. 3. In the Open Project dialog box, navigate to: tut-install/examples/case-studies 4. Select the dukes-bookstore folder. 5. Click Open Project. 6. In the Projects tab, right-click the dukes-bookstore project and select Build. This will build, package, and deploy Duke's Bookstore to GlassFish Server. 57.3.2 To Build and Deploy Duke's Bookstore Using Maven 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server), as well as the database server (see Starting and Stopping the Java DB Server). 2. In a terminal window, go to: tut-install/examples/case-studies/dukes-bookstore/ 3. Enter the following command: mvn install This command builds the application and packages it in a WAR file in the tut-install/examples/case-studies/dukes-bookstore/target/ directory. It then deploys the application to GlassFish Server. 57.3.3 To Run Duke's Bookstore 1. In a web browser, enter the following URL: http://localhost:8080/dukes-bookstore/ 2. On the Duke's Bookstore main page, click a book in the graphic, or click one of the links at the bottom of the page. 57-6 Java Platform, Enterprise Edition The Java EE Tutorial Running the Duke's Bookstore Case Study Application 3. Use the pages in the application to view and purchase books. Duke's Bookstore Case Study Example 57-7 Running the Duke's Bookstore Case Study Application 57-8 Java Platform, Enterprise Edition The Java EE Tutorial 58 58 Duke's Tutoring Case Study Example [59] The Duke's Tutoring example application is a tracking system for a tutoring center for students. Students can be checked in and out and can visit the park. The tutoring center can track attendance and status updates and can store contact information for guardians and students. Administrators can maintain the tutoring center system. The following topics are addressed here: ■ Design and Architecture of Duke's Tutoring ■ Main Interface ■ Administration Interface ■ Running the Duke's Tutoring Case Study Application 58.1 Design and Architecture of Duke's Tutoring Duke's Tutoring is a web application that incorporates several Java EE technologies. It exposes both a main interface (for students, guardians, and tutoring center staff) and an administration interface (for staff to maintain the system). The business logic for both interfaces is provided by enterprise beans. The enterprise beans use the Java Persistence API to create and store the application's data in the database. Figure 58–1 illustrates the architecture of the application. Duke's Tutoring Case Study Example 58-1 Design and Architecture of Duke's Tutoring Figure 58–1 Architecture of the Duke's Tutoring Example Application Java EE Server Web Container EJB Container Database Server Main Interface (JSF) Admin Interface (JSF) Client Admin Client ConfigBean RequestBean AdminBean Database The Duke's Tutoring application is organized into two main projects: the dukes-tutoring-common library and the dukes-tutoring-war web application. The dukes-tutoring-common library project contains the entity classes and helper classes used by the dukes-tutoring-war web application, and dukes-tutoring-common is packaged and deployed with dukes-tutoring-war. The library JAR file is useful for allowing the entity classes and helper classes to be reused by other applications, such as a JavaFX client application. Duke's Tutoring uses the following Java EE 7 platform features: ■ Java Persistence API entities – A custom Bean Validation annotation, @Email, for validating email addresses – A standard jta-data-source definition that will create the JDBC resource on deployment – A standard property in the persistence.xml deployment descriptor to automatically and portably create and delete the tables in the jta-data-source ■ Enterprise beans – – – Local, no-interface view session and singleton beans JAX-RS resources in a session bean Java EE security constraints on the administrative interface business methods – All enterprise beans packaged within the WAR ■ WebSocket – A WebSocket server endpoint that automatically publishes the status of students to client endpoints ■ Contexts and Dependency Injection – A CDI event that is fired when the status of a student changes 58-2 Java Platform, Enterprise Edition The Java EE Tutorial Main Interface – Handler methods for updating the application once the status event is fired – CDI managed beans for Facelets pages – Bean Validation annotations in the CDI managed beans ■ JavaServer Faces technology, using Facelets for the web front end – Templating – Composite components – A custom formatter, PhoneNumberFormatter – Security constraints on the administrative interface – Ajax-enabled Facelets components The Duke's Tutoring application has two main user interfaces, both packaged within a single WAR file: ■ ■ The main interface, for students, guardians, and staff The administrative interface used by the staff to manage the students and guardians, and to generate attendance reports 58.2 Main Interface The main interface allows students and staff to check students in and out, and record when students are outside at the playground. 58.2.1 Java Persistence API Entities Used in the Main Interface The following entities used in the main interface encapsulate data stored and manipulated by Duke's Tutoring, and are located in the dukestutoring.entity package in the dukes-tutoring-common project. ■ ■ ■ ■ ■ ■ Person: The Person entity defines attributes common to students and guardians tracked by the application. These attributes are the person's name and contact information, including phone numbers and email address. This entity has two subclasses, Student and Guardian. PersonDetails: The PersonDetails entity is used to store additional data common to all people, such as attributes like pictures and the person's birthday, which aren't included in the Person entity for performance reasons. Student and Guardian: The Student entity stores attributes specific to the students who come to tutoring. This includes information like the student's grade level and school. The Guardian entity's attributes are specific to the parents or guardians of a Student. Students and guardians have a many-to-many relationship. That is, a student may have one or more guardians, and a guardian may have one or more students. Address: The Address entity represents a mailing address and is associated with Person entities. Addresses and people have a many-to-one relationship. That is, one person may have many addresses. TutoringSession: The TutoringSession entity represents a particular day at the tutoring center. A particular tutoring session tracks which students attended that day, and which students went to the park. StatusEntry: The StatusEntry entity, which logs when a student's status changes, is associated with the TutoringSession entity. Students' statuses change when Duke's Tutoring Case Study Example 58-3 Main Interface they check in to a tutoring session, when they go to the park, and when they check out. The status entry allows the tutoring center staff to track exactly which students attended a tutoring session, when they checked in and out, which students went to the park while they were at the tutoring center, and when they went to and came back from the park. For information on creating Java Persistence API entities, see Chapter 37, "Introduction to the Java Persistence API." For information on validating entity data, see Validating Persistent Fields and Properties and Chapter 22, "Bean Validation: Advanced Topics." 58.2.2 Enterprise Beans Used in the Main Interface The following enterprise beans used in the main interface provide the business logic for Duke's Tutoring, and are located in the dukestutoring.ejb package in the dukes-tutoring-war project: ■ ■ ConfigBean is a singleton session bean used to create the default students when the application is initially deployed, and to create an automatic EJB timer that creates tutoring session entities every weekday. RequestBean is a stateless session bean containing the business methods for the main interface. The bean also has business methods for retrieving lists of students. These business methods use strongly typed Criteria API queries to retrieve data from the database. RequestBean also injects a CDI event instance, StatusEvent. This event is fired from the business methods when the status of a student changes. For information on creating and using enterprise beans, see Enterprise Beans. For information on creating strongly typed Criteria API queries, see Chapter 40, "Using the Criteria API to Create Queries." For information on CDI events, see Using Events in CDI Applications. 58.2.3 WebSocket Endpoint Used in the Main Interface The javaeetutorial.dukestutoring.web.websocket.StatusEndpoint class is a WebSocket server endpoint that returns students and their status to client endpoints. The StatusEndpoint.updateStatus method is a CDI observer method for the StatusEvent event. When a student's status changes in the main interface, a StatusEvent is fired. The updateStatus observer method is called by the container, and pushes out the status change to all the client endpoints registered with StatusEndpoint. The index.xhtml JavaServer Faces page contains JavaScript code to connect to the WebSocket endpoint. The onMessage method on this page clicks a JavaServer Faces button, which makes an Ajax request to refresh the table that shows the current status of the students. For more information on WebSocket endpoints, see Chapter 18, "Java API for WebSocket." For information on CDI events, see Using Events in CDI Applications. 58.2.4 Facelets Files Used in the Main Interface The Duke's Tutoring application uses Facelets to display the user interface, making extensive use of the templating features of Facelets. Facelets, the default display technology for JavaServer Faces technology, consists of XHTML files located in the tut-install/examples/case-studies/dukes-tutoring-war/src/main/webapp/ directory. The following Facelets files are used in the main interface: 58-4 Java Platform, Enterprise Edition The Java EE Tutorial Main Interface ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ template.xhtml: Template file for the main interface error.xhtml: Error file if something goes wrong index.xhtml: Landing page for the main interface park.xhtml: Page showing who is currently at the park current.xhtml: Page showing who is currently in today's tutoring session statusEntries.xhtml: Page showing the detailed status entry log for today's session resources/components/allStudentsTable.xhtml: A composite component for a table displaying all active students resources/components/allInactiveStudentsTable.xhtml: A composite component for a table displaying all inactive students resources/components/currentSessionTable.xhtml: A composite component for a table displaying all students in today's session resources/components/parkTable.xhtml: A composite component for a table displaying all students currently at the park WEB-INF/includes/mainNav.xhtml: XHTML fragment for the main interface's navigation bar For information on using Facelets, see Chapter 8, "Introduction to Facelets." 58.2.5 Helper Classes Used in the Main Interface The following helper classes, found in the dukes-tutoring-common project's dukestutoring.util package, are used in the main interface. ■ ■ ■ CalendarUtil: A class that provides a method to strip the unnecessary time data from java.util.Calendar instances. Email: A custom Bean Validation annotation class for validating email addresses in the Person entity. StatusType: An enumerated type defining the different statuses that a student can have. Possible values are IN, OUT, and PARK. StatusType is used throughout the application, including in the StatusEntry entity, and throughout the main interface. StatusType also defines a toString method that returns a localized translation of the status based on the locale. 58.2.6 Properties Files The strings used in the main interface are encapsulated into resource bundles to allow the display of localized strings in multiple locales. Each of the properties files has locale-specific files appended with locale codes, containing the translated strings for each locale. For example, Messages_es.properties contains the localized strings for Spanish locales. The dukes-tutoring-common project has the following resource bundle under src/main/resources/. ■ javaeetutorial/dukestutoring/util/StatusMessages.properties: Strings for each of the status types defined in the StatusType enumerated type for the default locale. Each supported locale has a property file of the form StatusMessages_locale prefix.properties containing the localized strings. For example, the strings for Spanish-speaking locales are located in StatusMessages_es.properties. Duke's Tutoring Case Study Example 58-5 Administration Interface The dukes-tutoring-war project has the following resource bundles under src/main/resources/. ■ ■ ValidationMessages.properties: Strings for the default locale used by the Bean Validation runtime to display validation messages. This file must be named ValidationMessages.properties and located in the default package as required by the Bean Validation specification. Each supported locale has a property file of the form ValidationMessages_locale prefix.properties containing the localized strings. For example, the strings for German-speaking locales are located in ValidationMessages_de.properties. javaeetutorial/dukestutoring/web/messages/Messages.properties: Strings for the default locale for the main and administration Facelets interface. Each supported locale has a property file of the form Messages_locale prefix.properties containing the localized strings. For example, the strings for simplified Chinese-speaking locales are located in Messages_zh.properties. For information on localizing web applications, see Registering Application Messages. 58.2.7 Deployment Descriptors Used in Duke's Tutoring Duke's Tutoring uses these deployment descriptors in the src/main/webapp/WEB-INF directory of the dukes-tutoring-war project: ■ ■ ■ faces-config.xml: The JavaServer Faces configuration file glassfish-web.xml: The configuration file specific to GlassFish Server, which defines security role mapping web.xml: The web application configuration file Duke's Tutoring also uses the following deployment descriptor in the src/main/resources/META-INF directory of the dukes-tutoring-common project: ■ persistence.xml: The Java Persistence API configuration file No enterprise bean deployment descriptor is used in Duke's Tutoring. Annotations in the enterprise bean class files are used for the configuration of enterprise beans in this application. 58.3 Administration Interface The administration interface of Duke's Tutoring is used by the tutoring center staff to manage the data employed by the main interface: the students, the students' guardians, and the addresses. The administration interface uses many of the same components as the main interface. Additional components that are only used in the administration interface are described here. 58.3.1 Enterprise Beans Used in the Administration Interface The following enterprise bean, in the dukestutoring.ejb package of the dukes-tutoring-war project, is used in the administration interface. ■ AdminBean: A stateless session bean for all the business logic used in the administration interface. Calls security methods to allow invocation of the business methods only by authorized users. 58-6 Java Platform, Enterprise Edition The Java EE Tutorial 58.3.2 Facelets Files Used in the Administration Interface Administration Interface The following Facelets files, under src/main/webapp/, are used in the administration interface: ■ ■ ■ ■ ■ ■ ■ ■ ■ admin/adminTemplate.xhtml: Template for the administration interface admin/index.xhtml: Landing page for the administration interface login.xhtml: Login page for the security-constrained administration interface loginError.xhtml: Page displayed if there are errors authenticating the administration user admin/address directory: Pages that allow you to create, edit, and delete Address entities admin/guardian directory: Pages that allow you to create, edit, and delete Guardian entities admin/student directory: Pages that allow you to create, edit, and delete Student entities resources/components/formLogin.xhtml: Composite component for a login form using Java EE security WEB-INF/includes/adminNav.xhtml: XHTML fragment for the administration interface's navigation bar 58.3.3 CDI Managed Beans Used in the Administration Interface The CDI managed beans used in the administration interface are located in the dukestutoring.web package in the dukes-tutoring-war project. ■ ■ ■ StudentBean.java: A managed bean for the Facelets pages used to create and edit students. The first and last names have Bean Validation annotations that require the fields to be filled in. The phone numbers have Bean Validation annotations to ensure that the submitted data is well-formed. GuardianBean.java: A managed bean for the Facelets pages used to create guardians for and assign guardians to students. The first and last names have Bean Validation annotations that require the fields to be filled in. The phone numbers have Bean Validation annotations to ensure that the submitted data is well-formed. AddressBean.java: A managed bean for the Facelets pages used to create addresses for students. The street, city, province, and postal code attributes have Bean Validation annotations that require the fields to be filled in, and the postal code attribute has an additional annotation to ensure that the data is properly formed. 58.3.4 Helper Classes Used in the Administration Interface The following helper classes, found in the dukes-tutoring-war project's dukestutoring.web.util package, are used in the administration interface. ■ EntityConverter: A parent class to StudentConverter and GuardianConverter that defines a cache to store the entity classes when converting the entities for use in JavaServer Faces user interface components. The cache helps increase performance. The cache is stored in the JavaServer Faces context. Duke's Tutoring Case Study Example 58-7 Running the Duke's Tutoring Case Study Application ■ ■ StudentConverter: A JavaServer Faces converter for the Student entity class. This class contains methods to convert Student instances to strings and back again, so they can be used in the user interface components of the application. GuardianConverter: Similar to StudentConverter, this class is a converter for the Guardian entity class. 58.4 Running the Duke's Tutoring Case Study Application This section describes how to build, package, deploy, and run the Duke's Tutoring application. 58.4.1 Running Duke's Tutoring You can use either NetBeans IDE or Maven to build, package, deploy, and run Duke's Tutoring. 58.4.1.1 To Build and Deploy Duke's Tutoring Using NetBeans IDE Before You Begin You must have already configured GlassFish Server as a Java EE server in NetBeans IDE, as described in To Add GlassFish Server as a Server Using NetBeans IDE. 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server). 2. If the database server is not already running, start it as described in Starting and Stopping the Java DB Server. 3. From the File menu, choose Open Project. 4. In the Open Project dialog box, navigate to: tut-install/examples/case-studies 5. 6. Select the dukes-tutoring folder. Select the Open Required Projects check box and click Open Project. Note: The first time you open Duke's Tutoring in NetBeans, you will see error glyphs in the Projects tab. This is expected, as the metamodel files used by the enterprise beans for Criteria API queries have not yet been generated. 7. In the Projects tab, right-click the dukes-tutoring project and select Build. This command creates a JDBC security realm named tutoringRealm, builds and packages the dukes-tutoring-common and dukes-tutoring-war projects, and deploys dukes-tutoring-war to GlassFish Server, starting the Java DB database and GlassFish Server if they have not already been started. 58.4.1.2 To Build and Deploy Duke's Tutoring Using Maven 1. Make sure that GlassFish Server has started (see Starting and Stopping GlassFish Server). 2. If the database server is not already running, start it as described in Starting and Stopping the Java DB Server. 58-8 Java Platform, Enterprise Edition The Java EE Tutorial Running the Duke's Tutoring Case Study Application 3. In a terminal window, go to: tut-install/examples/case-studies/dukes-tutoring/ 4. Enter the following command: mvn install This command creates a JDBC security realm named tutoringRealm, builds and packages the dukes-tutoring-common and dukes-tutoring-war projects, and deploys dukes-tutoring-war to GlassFish Server. 58.4.1.3 Using Duke's Tutoring Once Duke's Tutoring is running on GlassFish Server, use the main interface to experiment with checking students in and out or sending them to the park. To Use the Main Interface of Duke's Tutoring 1. In a web browser, open the main interface at the following URL: http://localhost:8080/dukes-tutoring-war/ 2. Use the main interface to check students in and out, and to log when the students go to the park. To Use the Administration Interface of Duke's Tutoring Follow these instructions to log in to the administration interface of Duke's Tutoring and add new students, guardians, and addresses. 1. From the main interface, open the administration interface by clicking Administration main page in the left menu. This redirects you to the login page at the following URL: http://localhost:8080/dukes-tutoring-war/admin/index.xhtml 2. On the login page, enter admin@example.com in the User name field, and enter javaee in the Password field. 3. Use the administration interface to add or modify students, add guardians, or add addresses. ■ ■ ■ ■ To add a new student, click Create new student in the left menu, fill in the fields (two are required) in the form that opens, and click Submit. The Email, Home phone, and Mobile phone fields have formatting requirements enforced by HTML5 pass-through or by Bean Validation constraints. To modify a student, click Edit next to the student's name, modify the fields in the form that opens, and click Submit. To edit another student, choose the student from the drop-down menu at the top of the page and click Change student. To remove a student, click Remove next to the student's name, then click Confirm in the page that appears. This action removes the student from the tutoring session but does not remove the student from the database. To add the student to the tutoring session again, click Activate student in the left menu, then click Activate next to the student's name in the page that appears. To add a guardian for a student, click Add guardian next to the student's name. The page that appears shows the student's name, the available guardians, and the current guardians for the student, if any. To add an existing guardian for that student, select the guardian from the list and click Add Duke's Tutoring Case Study Example 58-9 Running the Duke's Tutoring Case Study Application guardian. To create a new guardian for the student, fill in the fields and click Submit. To remove a guardian from a student, select one of the student's current guardians from the list and click Remove guardian. ■ To add an address for a student, click Add address next to the student's name. In the page that appears, fill in the appropriate fields in the form that appears, and click Submit. Four fields are required. The administration interface is not fully implemented. It is not possible to edit a guardian or to view or edit an address, although Facelets pages exist for these features. The application also makes no use of the properties in the PersonDetails entity. Feel free to modify the application to add these features. 58-10 Java Platform, Enterprise Edition The Java EE Tutorial 59 59Duke's Forest Case Study Example [60] Duke's Forest is a simple e-commerce application that contains several web applications and illustrates the use of multiple Java EE 7 APIs: ■ ■ ■ ■ ■ ■ ■ JavaServer Faces technology, including Ajax Contexts and Dependency Injection for Java EE (CDI) Java API for RESTful Web Services (JAX-RS) Java Persistence API (JPA) Java API for JavaBeans Validation (Bean Validation) Enterprise JavaBeans (EJB) technology Java Message Service (JMS) The application consists of the following projects. ■ Duke's Store: A web application that has a product catalog, customer self-registration, and a shopping cart. It also has an administration interface for product, category, and user management. The project name is dukes-store. ■ Duke's Shipment: A web application that provides an interface for order shipment management. The project name is dukes-shipment. ■ Duke's Payment: A web service application that has a RESTful web service for order payment. The project name is dukes-payment. ■ Duke's Resources: A simple Java archive project that contains all resources used by the web projects. It includes messages, CSS style sheets, images, JavaScript files, and JavaServer Faces composite components. The project name is dukes-resources. ■ ■ Entities: A simple Java archive project that contains all JPA entities. This project is shared among other projects that use the entities. The project name is entities. Events: A simple Java archive project that contains a POJO class that is used as a CDI event. The project name is events. The following topics are addressed here: ■ Design and Architecture of Duke's Forest ■ ■ Building and Deploying the Duke's Forest Case Study Application Running the Duke's Forest Application Duke's Forest Case Study Example 59-1 Design and Architecture of Duke's Forest 59.1 Design and Architecture of Duke's Forest Duke's Forest is a complex application consisting of three main projects and three subprojects. Figure 59–1 shows the architecture of the three main projects that you will deploy: Duke's Store, Duke's Shipment, and Duke's Payment. It also shows how Duke's Store makes use of the Events and Entities projects. Figure 59–1 Architecture of the Duke's Forest Example Application Duke’s Shipment EJB Container ShipmentBean Duke’s Payment Web Services Main Interface (Web Pages) OrderBrowser PaymentService Main Interface (Web Pages) Web Services / REST Duke’s Store Admin Interface (Web Pages) OrderBean EJB Container Events OrderEvent AdministratorBean CategoryBean OrderBean OrderJMSManager UserBean ProductBean ShoppingCart GroupsBean EventDispatchBean OrderStatusBean OrderDetailBean Entities.jar Person Customer Category CustomerOrder OrderDetailPK Administrator Groups Product OrderDetail OrderStatus Duke's Forest uses the following Java EE 7 platform features: ■ Java Persistence API entities – Bean Validation annotations on the entities for verifying data – XML annotations for Java API for XML binding (JAXB) serialization ■ Web services – A JAX-RS web service for payment, with security constraints – A JAX-RS web service that is EJB based ■ Enterprise beans – Local session beans – All enterprise beans packaged within the WAR ■ Contexts and Dependency Injection (CDI) – CDI annotations for JavaServer Faces components – A CDI managed bean used as a shopping cart, with conversation scoping – Qualifiers 59-2 Java Platform, Enterprise Edition The Java EE Tutorial Design and Architecture of Duke's Forest – Events and event handlers Servlets – A servlet for dynamic image presentation JavaServer Faces 2.2 technology, using Facelets for the web front end ■ ■ – Templating – Composite components – File upload – Resources packaged in a JAR file so they can be found in the classpath ■ Security – – – Java EE security constraints on the administrative interface business methods (enterprise beans) Security constraints for customers and administrators (web components) Single Sign-On (SSO) to propagate an authenticated user identity from Duke's Store to Duke's Shipment The Duke's Forest application has two main user interfaces, both packaged within the Duke's Store WAR file: ■ ■ The main interface, for customers and guests The administrative interface used to perform back office operations, such as adding new items to the catalog The Duke's Shipment application also has a user interface, accessible to administrators. Figure 59–2 shows how the web applications and the web service interact. Duke's Forest Case Study Example 59-3 Design and Architecture of Duke's Forest Figure 59–2 Interactions between Duke's Forest Components Duke’s Shipment JMS Client Main Interface (Web Pages) Customer Orders Duke’s Payment Payment Service OrderQueue json json Customer Orders HTTP HTTP Administrator REST/ HTTP REST/ HTTP Duke’s Store Web Services API Admin Interface (Web Pages) HTTP Main Interface (Web Pages) Facade Customer JMS Client Entities JDBC Database As illustrated in Figure 59–2, the customer interacts with the main interface of Duke's Store, while the administrator interacts with the administration interface. Both interfaces access a façade consisting of managed beans and stateless session beans, which in turn interact with the entities that represent database tables. The façade also interacts with web services APIs that access the Duke's Payment web service. When the payment for an order is approved, Duke's Store sends the order to a JMS queue. The administrator also interacts with the interface of Duke's Shipment, which can be accessed either directly through Duke's Shipment or from the administration interface of Duke's Store by means of a web service. When the administrator approves an order for shipping, Duke's Shipment consumes the order from the JMS queue. The most fundamental building blocks of the application are the Events and Entities projects, which are bundled into Duke's Store and Duke's Shipment along with the Duke's Resources project. 59.1.1 The events Project Events are one of the core components of Duke's Forest. The events project, included in all three of the main projects, is the most simple project of the application. It has only one class, OrderEvent, but this class is responsible for most of the messages between objects in the application. 59-4 Java Platform, Enterprise Edition The Java EE Tutorial Design and Architecture of Duke's Forest The application can send messages based on events to different components and react to them based on the qualification of the event. The application supports the following qualifiers: ■ ■ ■ @LoggedIn: For authenticated users @New: When a new order is created by the shopping cart @Paid: When an order is paid for and ready for shipment The following code snippet from the PaymentHandler class of Duke's Store shows how the @Paid event is handled: @Inject @Paid Event eventManager; ... public void onNewOrder(@Observes @New OrderEvent event) { if (processPayment(event)) { orderBean.setOrderStatus(event.getOrderID(), String.valueOf(OrderBean.Status.PENDING_PAYMENT.getStatus())); logger.info("Payment Approved"); eventManager.fire(event); } else { orderBean.setOrderStatus(event.getOrderID(), String.valueOf(OrderBean.Status.CANCELLED_PAYMENT.getStatus())); logger.info("Payment Denied"); } } To enable users to add more events to the project easily or update an event class with more fields for a new client, this component is a separate project within the application. 59.1.2 The entities Project The entities project is a Java Persistence API (JPA) project used by both Duke's Store and Duke's Shipment. It is generated from the database schema shown in Figure 59–3 and is also used as a base for the entities consumed and produced by the web services through JAXB. Each entity has validation rules based on business requirements, specified using Bean Validation. Duke's Forest Case Study Example 59-5 Design and Architecture of Duke's Forest Figure 59–3 Duke's Forest Database Tables and Their Relationships CATEGORY ID INT NAME VARCHAR(45) TAGS VARCHAR(45) GROUPS ID INT NAME VARCHAR(50) DESCRIPTION VARCHAR(300) PERSON_GROUPS GROUPS_ID INT EMAIL VARCHAR(45) PERSON ID INT FIRSTNAME VARCHAR(50) LASTNAME VARCHAR(100) EMAIL VARCHAR(45) ADDRESS VARCHAR(45) CITY VARCHAR(45) PASSWORD VARCHAR(100) DTYPE VARCHAR(31) Primary key Required field Foreign key Field PRODUCT ID INT NAME VARCHAR(45) PRICE DECIMAL(10,2) DESCRIPTION VARCHAR(45) IMG VARCHAR(45) CATEGORY_ID INT IMG_SRC BLOB(1073741823) ORDER_DETAIL ORDER_ID INT PRODUCT_ID INT QTY INT CUSTOMER_ORDER ID INT AMOUNT FLOAT(52) DATE_CREATED TIMESTAMP CUSTOMER_ID INT STATUS_ID INT ORDER_STATUS ID INT STATUS VARCHAR(45) DESCRIPTION VARCHAR(200) The database schema contains eight tables: ■ ■ ■ ■ ■ ■ ■ PERSON, which has a one-to-many relationship with PERSON_GROUPS and CUSTOMER_ ORDER GROUPS, which has a one-to-many relationship with PERSON_GROUPS PERSON_GROUPS, which has a many-to-one relationship with PERSON and GROUPS (it is the join table between those two tables) PRODUCT, which has a many-to-one relationship with CATEGORY and a one-to-many relationship with ORDER_DETAIL CATEGORY, which has a one-to-many relationship with PRODUCT CUSTOMER_ORDER, which has a one-to-many relationship with ORDER_DETAIL and a many-to-one relationship with PERSON and ORDER_STATUS ORDER_DETAIL, which has a many-to-one relationship with PRODUCT and CUSTOMER_ ORDER (it is the join table between those two tables) 59-6 Java Platform, Enterprise Edition The Java EE Tutorial Design and Architecture of Duke's Forest ■ ORDER_STATUS, which has a one-to-many relationship with CUSTOMER_ORDER The entity classes that correspond to these tables are as follows. ■ ■ ■ ■ ■ ■ ■ ■ ■ Person, which defines attributes common to customers and administrators. These attributes are the person's name and contact information, including street and email addresses. The email address has a Bean Validation annotation to ensure that the submitted data is well-formed. The generated table for the Person entity also has a DTYPE field that represents the discriminator column. Its value identifies the subclass (Customer or Administrator) to which the person belongs. Customer, a specialization of Person with a specific field for CustomerOrder objects. Administrator, a specialization of Person with fields for administration privileges. Groups, which represents the group (USERS or ADMINS) to which the user belongs. Product, which defines attributes for products. These attributes include name, price, description, associated image, and category. Category, which defines attributes for product categories. These attributes include a name and a set of tags. CustomerOrder, which defines attributes for orders placed by customers. These attributes include an amount and a date, along with id values for the customer and the order detail. OrderDetail, which defines attributes for the order detail. These attributes include a quantity and id values for the product and the customer. OrderStatus, which defines a status attribute for each order. 59.1.3 The dukes-payment Project The dukes-payment project is a web project that holds a simple Payment web service. Since this is an example application, it does not obtain any real credit information or even customer status to validate the payment. For now, the only rule imposed by the payment system is to deny all orders above $1,000. This application illustrates a common scenario where a third-party payment service is used to validate credit cards or bank payments. The project uses HTTP Basic Authentication and JAAS (Java Authentication and Authorization Service) to authenticate a customer to a JAX-RS web service. The implementation itself exposes a simple method, processPayment, which receives an OrderEvent to evaluate and approve or deny the order payment. The method is called from the checkout process of Duke's Store. 59.1.4 The dukes-resources Project The dukes-resources project contains a number of files used by both Duke's Store and Duke's Shipment, bundled into a JAR file placed in the classpath. The resources are in the src/main/resources directory: ■ ■ ■ ■ META-INF/resources/css: Two style sheets, default.css and jsfcrud.css META-INF/resources/img: Images used by the projects META-INF/resources/js: A JavaScript file, util.js META-INF/resources/util: Composite components used by the projects Duke's Forest Case Study Example 59-7 Design and Architecture of Duke's Forest ■ ■ ■ ■ bundles/Bundle.properties: Application messages in English bundles/Bundle_es.properties: Application messages in Spanish ValidationMessages.properties: Bean Validation messages in English ValidationMessages_es.properties: Bean Validation messages in Spanish 59.1.5 The Duke's Store Project Duke's Store, a web application, is the core application of Duke's Forest. It is responsible for the main store interface for customers as well as the administration interface. The main interface of Duke's Store allows the user to perform the following tasks: ■ ■ Browsing the product catalog Signing up as a new customer ■ Adding products to the shopping cart ■ Checking out ■ Viewing order status The administration interface of Duke's Store allows administrators to perform the following tasks: ■ ■ ■ Product maintenance (create, edit, update, delete) Category maintenance (create, edit, update, delete) Customer maintenance (create, edit, update, delete) ■ Group maintenance (create, edit, update, delete) The project also uses stateless session beans as façades for interactions with the JPA entities described in The entities Project, and CDI managed beans as controllers for interactions with Facelets pages. The project thus follows the MVC (Model-View-Controller) pattern and applies the same pattern to all entities and pages, as in the following example. ■ ■ ■ AbstractFacade is an abstract class that receives a Type and implements the common operations (CRUD) for this type, where is a JPA entity. ProductBean is a stateless session bean that extends AbstractFacade, applying Product as Type, and injects the PersistenceContext for the EntityManager. This bean implements any custom methods needed to interact with the Product entity or to call a custom query. ProductController is a CDI managed bean that interacts with the necessary enterprise beans and Facelets pages to control the way the data will be displayed. ProductBean begins as follows: @Stateless public class ProductBean extends AbstractFacade { private static final Logger logger = Logger.getLogger(ProductBean.class.getCanonicalName()); @PersistenceContext(unitName="forestPU") private EntityManager em; @Override protected EntityManager getEntityManager() { 59-8 Java Platform, Enterprise Edition The Java EE Tutorial Design and Architecture of Duke's Forest return em; } ... 59.1.5.1 Enterprise Beans Used in Duke's Store The enterprise beans used in Duke's Store provide the business logic for the application and are located in the com.forest.ejb package. All are stateless session beans. AbstractFacade is not an enterprise bean but an abstract class that implements common operations for Type, where is a JPA entity. Most of the other beans extend AbstractFacade, inject the PersistenceContext, and implement any needed custom methods: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ AdministratorBean CategoryBean EventDispatcherBean GroupsBean OrderBean OrderDetailBean OrderJMSManager OrderStatusBean ProductBean ShoppingCart UserBean The ShoppingCart class, although it is in the ejb package, is a CDI managed bean with conversation scope, which means that the request information will persist across multiple requests. Also, ShoppingCart is responsible for starting the event chain for customer orders, which invokes the RESTful web service in dukes-payment and publishes an order to the JMS queue for shipping approval if the payment is successful. 59.1.5.2 Facelets Files Used in the Main Interface of Duke's Store Like the other case study examples, Duke's Store uses Facelets to display the user interface. The main interface uses a large number of Facelets pages to display different areas. The pages are grouped into directories based on which module they handle. ■ ■ ■ ■ ■ ■ template.xhtml: Template file, used for both main and administration interfaces. It first performs a browser check to verify that the user's browser supports HTML 5, which is required for Duke's Forest. It divides the screen into several areas and specifies the client page for each area. topbar.xhtml: Page for the login area at the top of the screen. top.xhtml: Page for the title area. left.xhtml: Page for the left sidebar. index.xhtml: Page for the main screen content. login.xhtml: Login page specified in web.xml. The main login interface is provided in topbar.xhtml, but this page appears if there is a login error. Duke's Forest Case Study Example 59-9 Design and Architecture of Duke's Forest ■ ■ ■ ■ ■ admin directory: Pages related to the administration interface, described in Facelets Files Used in the Administration Interface of Duke's Store. customer directory: Pages related to customers (Create.xhtml, Edit.xhtml, List.xhtml, Profile.xhtml, View.xhtml). order directory: Pages related to orders (Create.xhtml, List.xhtml, MyOrders.xhtml, View.xhtml). orderDetail directory: Popup page allowing users to view details of an order (View_popup.xhtml). product directory: Pages related to products (List.xhtml, ListCategory.xhtml, View.xhtml). 59.1.5.3 Facelets Files Used in the Administration Interface of Duke's Store The Facelets pages for the administration interface of Duke's Store are found in the web/admin directory: ■ ■ ■ ■ ■ ■ ■ administrator directory: Pages related to administrator management (Create.xhtml, Edit.xhtml, List.xhtml, View.xhtml) category directory: Pages related to product category management (Create.xhtml, Edit.xhtml, List.xhtml, View.xhtml) customer directory: Pages related to customer management (Create.xhtml, Edit.xhtml, List.xhtml, Profile.xhtml, View.xhtml) groups directory: Pages related to group management (Create.xhtml, Edit.xhtml, List.xhtml, View.xhtml) order directory: Pages related to order management (Create.xhtml, Edit.xhtml, List.xhtml, View.xhtml) orderDetail directory: Popup page allowing the administrator to view details of an order (View_popup.xhtml) product directory: Pages related to product management (Confirm.xhtml, Create.xhtml, Edit.xhtml, List.xhtml, View.xhtml) 59.1.5.4 Managed Beans Used in Duke's Store Duke's Store uses the following CDI managed beans, which correspond to the enterprise beans. The beans are in the com.forest.web package: ■ ■ ■ ■ ■ ■ ■ ■ ■ AdministratorController CategoryController CustomerController CustomerOrderController GroupsController OrderDetailController OrderStatusController ProductController UserController 59-10 Java Platform, Enterprise Edition The Java EE Tutorial Design and Architecture of Duke's Forest 59.1.5.5 Helper Classes Used in Duke's Store The CDI managed beans in the main interface of Duke's Store use the following helper classes, found in the com.forest.web.util package: ■ ■ ■ ■ AbstractPaginationHelper: An abstract class with methods used by the managed beans ImageServlet: A servlet class that retrieves the image content from the database and displays it JsfUtil: Class used for JavaServer Faces operations, such as queuing messages on a FacesContext instance MD5Util: Class used by the CustomerController managed bean to generate an encrypted password for a user 59.1.5.6 Qualifiers Used in Duke's Store Duke's Store defines the following qualifiers in the com.forest.qualifiers package: ■ ■ ■ @LoggedIn: Qualifies a user as having logged in @New: Qualifies an order as new @Paid: Qualifies an order as paid 59.1.5.7 Event Handlers Used in Duke's Store Duke's Store defines event handlers related to the OrderEvent class packaged in the events project (see The events Project). The event handlers are in the com.forest.handlers package. ■ ■ ■ IOrderHandler: The IOrderHandler interface defines a method, onNewOrder, implemented by the two handler classes. PaymentHandler: The ShoppingCart bean fires an OrderEvent qualified as @New. The onNewOrder method of PaymentHandler observes these events and, when it intercepts them, processes the payment using the Duke's Payment web service. After a successful response from the web service, PaymentHandler fires the OrderEvent again, this time qualified as @Paid. DeliveryHandler: The onNewOrder method of DeliveryHandler observes OrderEvent objects qualified as @Paid (orders paid and ready for delivery) and modifies the order status to PENDING_SHIPMENT. When an administrator accesses Duke's Shipment, it will call the Order Service, a RESTful web service, and ask for all orders in the database that are ready for delivery. 59.1.5.8 Deployment Descriptors Used in Duke's Store Duke's Store uses the following deployment descriptors, located in the web/WEB-INF directory: ■ ■ ■ faces-config.xml: The JavaServer Faces configuration file glassfish-web.xml: The configuration file specific to GlassFish Server web.xml: The web application configuration file 59.1.6 The Duke's Shipment Project Duke's Shipment is a web application with a login page, a main Facelets page, and some other objects. This application, which is accessible only to administrators, consumes orders from a JMS queue and calls the RESTful web service exposed by Duke's Forest Case Study Example 59-11 Design and Architecture of Duke's Forest Duke's Store to update the order status. The main page of Duke's Shipment shows a list of orders pending shipping approval and a list of shipped orders. The administrator can approve or deny orders for shipping. If approved, the order is shipped, and it appears under the Shipped heading. If denied, the order disappears from the page, and on the customer's Orders list it appears as cancelled. There is also a gear icon on the Pending list that makes an Ajax call to the Order Service to refresh the list without refreshing the page. The code looks like this: 59.1.6.1 Enterprise Beans Used in Duke's Shipment The UserBean stateless session bean used in Duke's Shipment provides the business logic for the application and is located in the com.forest.shipment.session package. Like Duke's Store, Duke's Shipment uses the AbstractFacade class. This class is not an enterprise bean but an abstract class that implements common operations for Type, where is a JPA entity. The OrderBrowser stateless session bean, located in the com.forest.shipment.ejb package, has one method that browses the JMS order queue and another that consumes an order message after the administrator approves or denies the order for shipment. 59.1.6.2 Facelets Files Used in Duke's Shipment Duke's Shipment has only one page, so it has many fewer Facelets files than Duke's Store. ■ ■ ■ ■ ■ ■ template.xhtml: The template file, like the one in Duke's Store, first performs a browser check to verify that the user's browser supports HTML 5, which is required for Duke's Forest. It divides the screen into areas and specifies the client page for each area. topbar.xhtml: Page for the login area at the top of the screen. top.xhtml: Page for the title area. index.xhtml: Page for the initial main screen content. login.xhtml: Login page specified in web.xml. The main login interface is provided in topbar.xhtml, but this page appears if there is a login error. admin/index.xhtml: Page for the main screen content after authentication. 59.1.6.3 Managed Beans Used in Duke's Shipment Duke's Shipment uses the following CDI managed beans, in the com.forest.shipment package: ■ ■ web.ShippingBean: Managed bean that acts as a client to the Order Service web.UserController: Managed bean that corresponds to the UserBean session bean 59-12 Java Platform, Enterprise Edition The Java EE Tutorial Building and Deploying the Duke's Forest Case Study Application 59.1.6.4 Helper Class Used in Duke's Shipment The Duke's Shipment managed beans use only one helper class, found in the com.forest.shipment.web.util package: ■ JsfUtil: Class used for JavaServer Faces operations, such as queuing messages on a FacesContext instance 59.1.6.5 Qualifier Used in Duke's Shipment Duke's Shipment includes the @LoggedIn qualifier described in Qualifiers Used in Duke's Store. 59.1.6.6 Deployment Descriptors Used in Duke's Shipment Duke's Shipment uses the following deployment descriptors: ■ ■ ■ faces-config.xml: The JavaServer Faces configuration file glassfish-web.xml: The configuration file specific to GlassFish Server web.xml: The web application configuration file 59.2 Building and Deploying the Duke's Forest Case Study Application You can use NetBeans IDE or Maven to build and deploy Duke's Forest. 59.2.1 To Build and Deploy the Duke's Forest Application Using NetBeans IDE 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server), as well as the database server (see Starting and Stopping the Java DB Server). 2. From the File menu, choose Open Project. 3. In the Open Project dialog box, navigate to: tut-install/examples/case-studies 4. 5. Select the dukes-forest folder. Select the Open Required Projects check box and click Open Project. 6. Right-click the dukes-forest folder and select Build. This task configures the server, creates and populates the database, builds all the subprojects, assembles them into JAR and WAR files, and deploys the dukes-payment, dukes-store, and dukes-shipment applications. To configure the server, this task creates a JDBC security realm named jdbcRealm, enables default principal-to-role mapping, and enables single sign-on (SSO) for the HTTP Service. 59.2.2 To Build and Deploy the Duke's Forest Application Using Maven 1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server), as well as the database server (see Starting and Stopping the Java DB Server). 2. In a terminal window, go to: tut-install/examples/case-studies/dukes-forest/ Duke's Forest Case Study Example 59-13 Running the Duke's Forest Application 3. Enter the following command to configure the server, create and populate the database, build all the subprojects, assemble them into JAR and WAR files, and deploy the dukes-payment, dukes-store, and dukes-shipment applications: mvn install To configure the server, this task creates a JDBC security realm named jdbcRealm, enables default principal-to-role mapping, and enables single sign-on (SSO) for the HTTP Service. 59.3 Running the Duke's Forest Application Running the Duke's Forest application involves several tasks: ■ Registering as a customer of Duke's Store ■ As a customer, purchasing products ■ As an administrator, approving or denying shipment of a product ■ As an administrator, creating a new product, customer, group, or category 59.3.1 To Register as a Duke's Store Customer 1. In a web browser, enter the following URL: http://localhost:8080/dukes-store The Duke's Forest - Store page opens. 2. Click Sign Up at the top of the page. 3. Fill in the form fields, then click Save. All fields are required, and the Password value must be at least 7 characters in length. 59.3.2 To Purchase Products 1. To log in as the user you created, or as one of two users already in the database, enter the user name and password and click Log In. The preexisting users have the user names jack@example.com and robert@example.com, and they both have the same password, 1234. 2. Click Products in the left sidebar. 3. On the page that appears, click one of the categories (Plants, Food, Services, or Tools). 4. Choose a product and click Add to Cart. You can order only one of any one product, but you can order multiple different products in multiple categories. The products and a running total appear in the Shopping Cart in the left sidebar. 5. When you have finished choosing products, click Checkout. A message appears: "Your order is being processed. Check the Orders page to see the status of your order." 6. Click Orders in the left sidebar to verify your order. 59-14 Java Platform, Enterprise Edition The Java EE Tutorial Running the Duke's Forest Application If the total of the order exceeds $1,000, the status of the order is "Order cancelled," because the Payment web service denies orders over that limit. Otherwise, the status is "Ready to ship." 7. When you have finished placing orders, click Logout at the top of the page. 59.3.3 To Approve Shipment of a Product 1. Log in to Duke's Store as an administrator. Your user name is admin@example.com, and your password is 1234. The main administration page allows you to view categories, customers, administrators, groups, products, and orders, and to create new objects of all types except orders. 2. At the bottom of the page, click Approve Shipment. This action takes you to Duke's Shipment, retaining your administrator login. 3. On the Pending list, click Approve to approve an order and move it to the Shipped area of the page. If you click Deny, the order disappears from the page. If you log in to Duke's Store again as the customer, it will appear in the Orders list as "Order cancelled." To return to Duke's Store from Duke's Shipment, click Return to Duke's Store. 59.3.4 To Create a New Product You can create other kinds of objects as well as products. Creating products is more complex than the other creation processes, so it is described here. 1. Log in to Duke's Store as an administrator. 2. On the main administration page, click Create New Product. 3. Enter values in the Name, Price, and Description fields. 4. Select a category, then click Next. 5. On the Upload the Product Image page, click Browse to locate an image on your file system using a file chooser. 6. Click Next. 7. On the next page, view the product fields, then click Done. 8. Click Products in the left sidebar, then click the category to verify that the product has been added. 9. Click Administration at the top of the page to return to the main administration page, or click Logout to log out. Duke's Forest Case Study Example 59-15 Running the Duke's Forest Application 59-16 Java Platform, Enterprise Edition The Java EE Tutorial 23-7 34-10 29-3, 29-10 6-6, 16-2, 23-7 Symbols @AccessTimeout annotation, @Alternative annotation, 25-2 @ApplicationScoped annotation, @AroundInvoke annotation, 54-2 @AroundTimeout annotation, 54-2 @Asynchronous annotation, 36-1 @ConcurrencyManagement annotation, 34-8 @Consumes annotation, @Context annotation, 31-1 @ConversationScoped annotation, @CookieParam annotation, 31-1 @DeclareRoles annotation, 49-3, 49-4, 49-10 @Decorator annotation, 25-10 @Delegate annotation, 25-10 @DELETE annotation, 29-3, 29-7 @DenyAll annotation, 49-5 @Dependent annotation, 16-2, 23-7 @DependsOn annotation, 34-7 @DiscriminatorColumn annotation, 37-12 @DiscriminatorValue annotation, 37-12 @Disposes annotation, @Embeddable annotation, 37-10 @EmbeddedId annotation, 37-6 @Entity annotation, 37-1 @FlowScoped annotation, 16-2 @FormParam annotation, 31-1, 31-3 @GET annotation, 29-3, 29-7 @GroupSequence annotation, @HEAD annotation, 29-3 @HeaderParam annotation, 31-1 @HttpConstraint annotation, 48-2, 48-16 @HttpMethodConstraint annotation, 48-2, 48-16 @Id annotation, 37-6 @IdClass annotation, 37-6 @Inject annotation, 23-6, 25-6 @Interceptor annotation, 54-2 @Interceptors annotation, 54-2 @Local annotation, 32-7, 34-2 @Lock annotation, 34-8 @ManagedBean annotation, 8-4, 16-1 @ManyToMany annotation, 37-8 @ManyToOne annotation, 37-8 @MatrixParam annotation, 31-1 @MessageDriven annotation, 46-34 22-3 25-5 Index @MultipartConfig annotation, 17-15 @Named annotation, 23-8 @NamedQuery annotation, 39-2 @Observes annotation, 25-7 @OnClose annotation, 18-5 @OnError annotation, 18-4 @OneToMany annotation, 37-8, 37-9 @OneToOne annotation, 37-7, 37-8, 37-9 @OnMessage annotation, 18-4 @OnOpen annotation, 18-4 @Path annotation, 29-2, 29-5 @PathParam annotation, 29-3, 29-11, 31-1, 31-2 @PermitAll annotation, 49-4 @PersistenceContext annotation, 37-14 @PersistenceUnit annotation, 37-15 @POST annotation, 29-3, 29-7 @PostActivate annotation, @PostConstruct annotation, 32-11, 34-2, 34-4, 54-2 @PreDestroy annotation, 32-11, 34-2, 34-4, 54-2 @PrePassivate annotation, @Produces annotation, 23-10, 25-4, 29-3, 29-9 @Provider annotation, 29-3 @PUT annotation, 29-3, 29-7 @Qualifier annotation, 23-5 @QueryParam annotation, 29-3, 29-11, 31-1, 31-2 @Remote annotation, 32-7, 34-2 @Remove annotation, 32-12, 34-2, 34-5 @RequestScoped annotation, 6-6, 16-2, 23-7 @Resource annotation, 3-1, 4-2, 6-14, 25-6 34-2, 34-4 34-2, 34-4 JMS resources, 45-8, 46-29 49-4, 49-10 @ResourceDependency annotation, 10-27, 13-10 @RolesAllowed annotation, @RunAs annotation, 49-8 @Schedule and @Schedules annotations, 34-20 @ServletSecurity annotation, 48-2, 48-16 @SessionScoped annotation, 6-6, 16-2, 23-7 @Singleton annotation, 34-7 @Startup annotation, 34-7 @Stateful annotation, 34-2 @Timeout annotation, 34-18 @Timeout method, 34-18, 34-20 @Transient annotation, 37-3 @WebFilter annotation, 17-7 @WebInitParam annotation, @WebListener annotation, 17-3 @WebMethod annotation, 34-5 17-5, 17-8 Index-1 @WebService annotation, 28-2 @WebServiceRef annotation, 6-15 @WebServlet annotation, 6-9, 17-4 A 39-1 abstract schemas, access control, 47-5 acknowledge method, 45-20 acknowledging messages. See message acknowledgment action events, 7-8, 7-11, 10-13, 15-18 ActionEvent class, 15-18, 15-20 actionListener attribute, 10-12, 11-10, 11-11, 15-7 ActionListener implementation, 15-19, 15-20 ActionListener interface, 11-7 actionListener tag, processAction(ActionEvent) method, 15-20 referencing methods that handle action 11-11, 12-12 10-27, 11-7, 15-3 events, writing a managed bean method to handle action events, action method, administered objects, 45-7 12-12 7-11 creating and removing, 46-3 definition, 45-4 See also connection factories, destinations Administration Console, 1-23 starting, 2-4 afterBegin method, 51-6 afterCompletion method, 51-6 Ajax 13-10 error handling, 13-6 event attribute of f:ajax tag, 13-5 example, execute attribute of f:ajax tag, 13-5 grouping components, 13-8 immediate attribute of f:ajax tag, 13-5 listener attribute of f:ajax tag, 13-6 loading JavaScript resource library, 13-9 monitoring events, 13-6 onerror attribute of f:ajax tag, 13-6 onevent attribute of f:ajax tag, 13-6 overview, 13-1 receiving responses, 13-7 render attribute of f:ajax tag, 13-7 request lifecycle, 13-7 sending requests, 13-4 using JavaScript API directly, 13-9 using with Facelets, 13-2 using with JavaServer Faces technology, 13-1 alternatives CDI, example, annotations, 25-2 26-1 1-1 interceptor metadata, 54-1 JAX-RS, 29-2, 31-1 security, 47-8, 48-16, 49-1, 49-3 appclient tool, 1-23 Index-2 1-10 applet container, applets, 1-5, 1-6 application client container, 1-10 application clients, 1-5 examples, 46-29 50-13 securing, application clients, JMS building, 46-4 examples, 46-2 running, 46-10 applications 6-8 dynamic reloading, JavaServer Faces, 7-2 packaging, 5-1 security, 47-6 undeploying, 6-8 asadmin tool, 1-23 asynchronous message consumption, 45-6 JMS client example, 46-9 See also message-driven beans asynchronous method invocation 36-2 calling asynchronous business methods, cancelling, 36-3 checking status, 36-3 creating asynchronous business methods, 36-1 example, 36-3 java.util.concurrent.Future interface, retrieving results, 36-2 session beans, 36-1 36-1 asynchronous send mechanism, attributes referencing managed bean methods, 11-10 45-25 action attribute, 11-10, 11-11 actionListener attribute, validator attribute, valueChangeListener attribute, 11-10, 11-12 11-10, 11-11 11-10, 11-11 48-10 47-4, 47-16 audit modules, pluggable, 47-10 auditing, 47-5 auth-constraint element, 48-4 authenticate method, authenticating users, 48-6, 48-8 authentication, basic, 48-6 basic with EJB, 49-6 certificate-based mutual, 50-5, 50-7 client, digest, 48-8 form-based, mutual, server, 50-5 user name/password-based mutual, 50-6 48-7, 48-18 50-5, 50-7 50-5 authorization, 47-4 authorization constraints, authorization providers, pluggable, 47-9 auto commit, 1-17 AUTO_ACKNOWLEDGE mode, 45-20 48-3, 48-4 B basic authentication, 48-6 EJB, 49-6 example, 48-15 Batch Applications for the Java Platform, 1-20, 55-1 batch jobs 55-22 checking status, defining, 55-7 definition, 55-1 55-5 elements, instances and executions, 55-6 properties and parameters, starting, 55-22 status, 55-6 steps, 55-2 submitting to batch runtime, 55-6 55-21 batch processing 55-20 55-17 context objects, 55-21 creating applications, 55-5 creating batch artifacts, definition, 55-1 dependency injection, examples, 55-23, 55-29 implementing chunk steps, 55-7 implementing task steps, introduction, 55-1 Java EE framework, Java EE platform, 55-4 Job Specification Language, 55-7, 55-10 packaging applications, 55-22 status and decision elements, 55-3 55-9 55-4 Bean Validation, 1-18, 21-1 advanced, 22-1 constraint violations, 21-6 constraints, 38-18 constructors, 21-5 custom constraints, 22-1, 58-2 empty strings, 21-4 examples, 38-18 exceptions, 21-6 22-4 inheritance, Java Persistence API, 37-4 JavaServer Faces applications, 21-1, 38-20 localization, 22-3 messages, methods, 21-5, 21-6, 22-4 null strings, 21-4 ordering, parameters, 21-5, 21-6 resource bundles, 22-2 using f:validateBean tag, 11-8 22-3 22-2 bean-managed transactions. See transactions, bean-managed beans, in CDI, 23-4 beans.xml file, 23-10 beforeCompletion method, 51-6 BLOBs. See persistence, BLOBs bookmarkable URLs component tags, 10-23 10-24 example, view parameters, BufferedReader class, bundles. See resource bundles 10-23 17-6 32-1 business logic, business methods, 32-9 client calls, 34-4 exceptions, 34-5 locating, 33-2 requirements, 34-5 transactions, 51-4, 51-6, 51-7, 51-8 BytesMessage interface, 45-17 C CallbackHandler interface, 50-13 capture-schema tool, 1-23 CDI. See Contexts and Dependency Injection for Java EE (CDI) certificate authorities, certificates, 47-6 50-1 50-7 47-7, 50-1, 50-2 client, digital, server, 50-2, 50-4 using for authentication, 50-4 character encodings, 20-5 character sets, 20-4 client certificates, generating, 50-7 client ID, for durable subscriptions, CLIENT_ACKNOWLEDGE mode, 45-20 clients authenticating, 50-5, 50-7 50-13 securing, CLOBs. See persistence, CLOBs collections, persistence, 37-3, 40-9 commit method, 51-6 commit method (JMS), 45-24 commits. See transactions, commits Common Client Interface, Connector architecture, 52-5 45-13 component binding, 12-3, 12-4, 15-31, 15-34 binding attribute, 12-3, 15-31, 15-34 component properties. See managed bean properties component rendering model, 7-5, 7-7 15-4 decode method, 7-15, 15-14, 15-20, 15-24 decoding, 15-4, 15-10 delegated implementation, 15-4 direct implementation, encode method, 15-25 encodeBegin method, 15-12 encodeChildren method, 15-12 encodeEnd method, 15-12, 15-17 encoding, 15-4, 15-10 HTML render kit, 15-21, 16-27 render kit, 7-7 Renderer class, 7-7 Renderer implementation, 16-27 RenderKit class, RenderKit implementation, 16-27 7-7 component tag attributes action attribute, 10-12, 12-11, 15-7 actionListener attribute, 10-12, 11-10, 12-12, 15-7 alt attribute, 15-7 Index-3 10-9, 11-2, 15-26 binding attribute, 10-4, 10-6, 12-3, 15-31, 15-34 columns attribute, 10-15 converter attribute, for attribute, 10-11, 10-22 id attribute, 10-4 immediate attribute, redisplay attribute, rendered attribute, 10-4, 10-6, 15-34 style attribute, styleClass attribute, validator attribute, value attribute, valueChangeListener attribute, var attribute, 20-4 10-4, 10-6, 10-22 10-4, 10-6 10-9, 12-12 10-4, 10-5, 15-7 10-10 10-4, 10-6, 12-3, 15-7, 15-31, 15-32 10-9, 11-12, 12-13 component tags, 7-8, 7-9, 12-3 10-23 attributes. See component tag attributes body tag, 10-7 bookmarkable URLs, button tag, 10-23 column tag, 10-2 commandButton tag, 10-2, 10-12 commandLink tag, 10-2, 10-13 dataTable tag, 10-2, 10-19, 12-5 form tag, 10-2, 10-7 graphicImage tag, 10-2, 10-13, 15-7 head tag, 10-7 inputHidden tag, 10-3, 10-8 inputSecret tag, 10-3, 10-8, 10-10 inputText tag, 10-3, 10-8, 10-10 inputTextarea tag, 10-3, 10-8 link tag, 10-23 message tag, 10-3, 10-22 messages tag, 10-3, 10-22 outputFormat tag, 10-3, 10-9, 10-11 outputLabel tag, 10-3, 10-9, 10-10 outputLink tag, 10-3, 10-9, 10-11 outputScript tag, 10-25 outputStylesheet tag, 10-25 outputText tag, panelGrid tag, 10-3, 10-14 panelGroup tag, 10-3, 10-14 resource relocation, 10-25 selectBooleanCheckbox tag, 10-3, 10-16, 12-6 selectItems tag, 12-8 selectManyCheckbox tag, 10-3, 10-17, 12-7 selectManyListbox tag, 10-3, 10-17 selectManyMenu tag, selectOneListbox tag, 10-4, 10-16 selectOneMenu tag, 10-4, 10-16, 12-7, 12-8 selectOneRadio tag, 10-3, 10-9, 10-10, 10-13, 12-6 10-4, 10-16 10-3, 10-17 component-managed sign-on, 50-14, 50-15 components boxes, 10-3, 10-4 buttons, 10-2, 10-12 check boxes, 10-3, 10-16 data grids, fields, 10-3 hidden fields, 10-3 hyperlinks, images, 10-13 10-13 10-2 Index-4 Java EE, 1-4 labels, 10-3 links, 10-2 menus, 10-3, 10-4, 10-16, 10-17 options, 10-4 password fields, 10-3 radio buttons, 10-4 table columns, 10-2 tables, text areas, 10-3, 10-14, 10-19 10-3 14-1 composite components advanced features, attributes, 14-1 default attribute, 14-1 example, 14-3 f:validateBean tag, 14-2 f:validateRegex tag, 14-2 f:validateRequired tag, Facelets, 8-10 invoking managed beans, method-signature attribute, 14-1 name attribute, required attribute, 14-1 type attribute, validating values, 14-2 14-2 14-2 14-1 14-2 concurrency definition, 56-1 examples, 56-3, 56-7 security and, 56-3 threads and processes, 56-1 transactions and, 56-3 Concurrency Utilities for Java EE, 1-20, 56-1 concurrent access, 51-1 concurrent access to entity data, 42-1 conditional HTTP requests in JAX-RS, confidentiality, 47-16 configuring JavaServer Faces applications 31-9 Application class, 16-3 application configuration resource files, 16-3 configuring managed beans, 16-1, 16-14 error message registration, 15-27 faces-config.xml files, 16-26 including the classes, pages, and other 16-33 resources, javax.faces.application.CONFIG_FILES context parameter, 16-3 registering custom converters, 16-24 16-27 registering custom renderers, registering custom UI components, 16-29 registering custom validators, 16-24 registering messages, 16-21 specifying a path to an application configuration resource file, 16-32 specifying where UI component state is 15-16, 16-32 saved, value binding, 15-32 configuring JavaServer Faces applications. See configuring navigation rules configuring managed beans, 15-7, 16-14 configuring navigation rules, 7-10, 16-25 from-action element, 16-26 from-view-id element, 16-26 navigation-case element, 16-26 navigation-rule element, 16-26 to-view-id element, 16-26 connection factories, 45-8 creating, 46-31, 46-42 injecting resources, 45-8, 46-29 Connection interface, 51-6, 51-9 Connection interface (JMS), 45-9 connection pooling, 3-2 ConnectionFactory interface (JMS), 45-8 connections, JMS introduction, 45-9 managing in enterprise bean applications, 45-29 connections, securing, 47-15 connectors. See Java EE Connector architecture constructors, 54-4 static, 21-5 container-managed sign-on, container-managed transactions. See transactions, 50-14 containers, container-managed 1-8 application client, 1-10 configurable services, 1-9 nonconfigurable services, 1-9 security, 47-1, 47-8 services, trust between, 49-9 See also EJB container, embedded enterprise bean 1-9 specialization, 25-3 stereotypes, 25-12 contexts, JMS, 45-9 ContextService interface, 56-2 conversational state, 32-2 7-5, 7-8 conversion model, 10-9, 11-2, 15-26 converter attribute, Converter implementations, Converter interface, 15-24 converterId attribute, 11-2 converting data between model and 7-8, 11-1, 15-26 presentation, 7-8 javax.faces.convert package, 11-1 model view, presentation view, 15-24 See also converters, converter tags 15-24 Converter implementation classes 11-2 BigDecimalConverter class, 11-1 BigIntegerConverter class, 11-2 BooleanConverter class, 11-2 ByteConverter class, 11-2 CharacterConverter class, DateTimeConverter class, 11-2, 11-3 DoubleConverter class, 11-2 EnumConverter class, FloatConverter class, IntegerConverter class, 11-2 LongConverter class, NumberConverter class, 11-2, 11-3, 11-4 ShortConverter class, 11-2 11-2 11-2 11-2 container, web container converter tags context parameters, 6-5 specifying, 6-12 Contexts and Dependency Injection for Java EE (CDI), 1-18 25-1 25-2 advanced topics, alternatives, basic concepts, 23-1 beans, 23-4 configuring applications, 23-10 converting managed beans to JAX-RS root resource 25-7, 58-2, 58-4 classes, 31-8 decorators, 25-10 disposer methods, 25-5 EL, 23-8 events, examples, 24-1, 26-1 Facelets pages, 23-9 injectable objects, 23-5 injecting beans, integrating with JAX-RS, 31-8 interceptors, 25-9 managed beans, observer methods, 25-7, 58-4 overview, 23-3 producer fields, producer methods, qualifiers, 23-5 scopes, 23-7 setter and getter methods, 23-9 23-10, 25-4 25-4 23-4 23-6 11-3, 15-26 convertDateTime tag, 11-3 convertDateTime tag attributes, 11-4 converter tag, convertNumber tag, convertNumber tag attributes, 7-5, 7-15 custom converters, 7-8, 15-26 See also standard converters 11-3, 11-4 11-5 converters, converting data. See conversion model cookie parameters, JAX-RS, createBrowser method, 46-11 createTimer method, 34-19 credential, 47-12 Criteria API, 40-1 29-13 creating queries, 40-4 examples, 38-15 expressions, 40-6, 40-7 path navigation, 40-6 query execution, 40-9 query results, 40-6, 40-8 criteria queries, string-based, 41-1 cryptography, public-key, custom converters 50-2 binding to managed bean properties, 15-35 creating, 15-23 getAsObject method, 15-24 getAsObject(FacesContext, UIComponent, String) method, 15-24 getAsString method, 15-25 Index-5 getAsString(FacesContext, UIComponent, Object) method, 15-24 registering. See registering custom converters using, 15-26 custom objects custom converters, 15-26 using, 15-22 using custom components, renderers and tags together, 15-4 See also custom tags, custom UI components, custom validators custom renderers creating the Renderer class, 15-17 determining necessity of, performing decoding, 15-14 performing encoding, 15-12 registering with a render kit, 15-4 16-27 custom tags, 7-10, 15-4 getRendererType method, 15-18 identifying the renderer type, 15-17 specifying, tag library descriptor, 15-9 15-29 custom UI components creating, 15-1 creating component classes, 15-9 custom objects, 15-22 delegating rendering, 15-16 determining necessity of, handling events emitted by, 15-20 queueEvent method, 15-14 registering. See registering custom UI components restoreState(FacesContext, Object) 15-2 method, 15-16 saveState(FacesContext) method, saving state, 15-15 specifying where state is saved, steps for creating, custom validators, 15-27 15-9 16-32 15-16 15-29 binding to managed bean properties, 15-35 custom validator tags, implementing the Validator interface, 15-28 registering, 16-24 using, 15-30 validate method, 12-12, 15-28 Validator implementation, 12-11, 15-28, 15-30 Validator interface, 15-27 validator tag, 15-27, 15-30 D data encryption, 50-5 data integrity, 47-5, 51-1, 51-2 data sources, 3-2 databases clients, 32-1 connections, 34-5, 51-7 creating tables, 37-20 data recovery, dropping tables, EIS tier, 37-20 51-1 1-3 Index-6 32-4 37-21 loading data, message-driven beans and, multiple, 51-7, 51-8 See also transactions DataSource interface, 3-2 DDL scripts, 37-20 loading data, 37-21 debugging Java EE applications, 2-7 declarative security, 47-1, 48-1, 49-1 example, 49-9 decorators CDI, 25-10 example, 26-19 delivery delay for messages, 45-23 delivery modes, 45-21 JMSDeliveryMode message header field, 45-16 DeliveryMode interface, 45-21 Dependency Injection for Java (JSR 330), 1-18, 23-1 deployment, 33-3 deployment descriptors, 5-1, 47-1, 47-8 enterprise bean, 5-3, 47-9, 49-1, 49-3 Java EE, 5-2 runtime, 5-2, 5-5 security-role-mapping element, 47-14 security-role-ref element, 48-13 web application, 5-4, 6-2, 16-29, 47-9 Destination interface, destinations, 45-8 45-8 creating, 46-31, 46-42 injecting resources, 45-8, 46-29 JMSDestination message header field, 45-16 temporary, 45-23, 46-38 See also queues, temporary JMS destinations, topics 48-8 17-13 destroy method, digest authentication, digital signatures, 50-2 disposer methods, CDI, 25-5 document roots, 5-4 doFilter method, doGet method, 17-5 domains, 2-3 doPost method, 17-5 downloading GlassFish Server, 2-1 DUPS_OK_ACKNOWLEDGE mode, 45-21 durable subscriptions, 45-13 17-7, 17-8, 17-9 examples, 46-16, 46-24, 46-32 shared, 45-15 E eager attribute, managed beans, 16-4 EAR files, 5-1 EIS tier, 1-8 security, 50-14 EJB container, 1-10 container-managed transactions, 51-2 message-driven beans, onMessage method, invoking, 46-30 services, See also embedded enterprise bean container 32-1, 49-1 45-29 32-11 EJB JAR files, EJBContext interface, 51-6, 51-8 ejb-jar.xml file, 5-3, 47-9, 49-3 EL, 6-4, 9-1 23-8 9-6 CDI managed beans, composite expressions, deferred evaluation expressions, 9-2 expression examples, 9-11 immediate evaluation expressions, 9-2 literals, 9-5 lvalue expressions, 9-3 managed beans, method expressions, 9-7 method-binding expressions, 7-11 operators, 9-9 overview, 9-1 parameterized method calls, 9-5 reserved words, rvalue expressions, 9-3 type conversion during expression 9-10 12-2 evaluation, 9-6 value expressions, 9-3 See also method binding embeddable classes, persistence, 37-10 embedded enterprise bean container creating, 35-2 developing applications, 35-1 examples, 35-4 initializing enterprise bean modules, 35-3 overview, 35-1 running applications, 35-2 session bean references, 35-3 shutting down, 35-3 See also EJB container, enterprise beans end-to-end security, 47-7 enterprise applications, securing, 49-1 1-1 enterprise beans, 1-7, 1-15 32-6 accessing, 32-5 classes, 32-11 compiling, 33-3 contents, 32-10 converting to JAX-RS root resource classes, defined, 32-1 dependency injection, deployment, 32-11 distribution, 32-7 exceptions, 34-24 finding, 35-3 getCallerPrincipal method, 49-6 implementor of business logic, 1-7 integrating with JAX-RS, 31-8 interceptors, 54-1 interfaces, 32-5, 32-11 isCallerInRole method, 49-6 JAX-RS resources, 29-16 JNDI lookup, 32-6 lifecycles, 32-11 local access, local interfaces, 32-8 32-7 32-7 packaging, 5-3, 33-3 performance, programmatic security, 49-6 remote access, 32-9 remote interfaces, 32-9 securing, singletons, testing, 35-4 timer service, 34-16 types, 32-2 32-2, 32-10, 34-13 web services, See also business methods, embedded enterprise 29-16 49-1 bean container, message-driven beans, session beans Enterprise Information Systems. See EIS tier entities 37-16 37-11 37-12 37-12 37-16, 38-10 abstract, abstract schema names, 39-3 application-managed entity managers, 37-15 cascading operations, 37-9 collections, 39-15 container-managed entity managers, 37-14 controlling caching, 44-2 creating, 38-9 discriminator columns, entity manager, 37-14 finding, inheritance, 37-11, 38-13 inheritance mapping, lifecycle, managing, 37-14, 38-9 mapping to multiple tables, 38-7 non-entity superclasses, 37-12 37-1 overview, persistent fields, persistent properties, persisting, primary keys, 37-6 querying, relationships, 38-10 removing, 37-17, 38-11 requirements, 37-1 superclasses, 37-11 synchronizing, validating, 37-4 37-16 37-18 37-17 37-2 37-2 entity data lock modes, 42-2 optimistic locking, pessimistic locking, 42-1, 42-2 42-1, 42-4 entity graphs, 43-1 named, 43-3 entity providers, JAX-RS, 29-8 entity relationships bidirectional, 37-8 many-to-many, 37-8, 38-13 many-to-one, 37-8 multiplicity, 37-7 one-to-many, 37-8 one-to-one, 37-7 query language, 37-9 Index-7 31-8 unidirectional, 37-8 EntityManager interface, 37-14 equals method, 37-6 event and listener model, 7-5, 7-8 binding listeners to managed bean properties, 15-35 7-8 Event class, 7-15, 15-9 event handlers, event listeners, 7-15, 7-16, 7-17 handling events of custom UI components, 15-20 implementing event listeners, 15-18 Listener class, 7-8 listener class, 12-11 queueEvent method, 15-14 ValueChangeEvent class, 11-12 See also action events, value-change events events 25-7 26-13 CDI, example, examples, 2-1 Ajax, 13-10 asynchronous method invocation, session beans, 36-3 2-5 35-4 10-24 24-1, 26-1 basic authentication, 48-15 batch processing, 55-23, 55-29 Bean Validation, 38-18 bookmarkable URLs, building, 2-5 CDI, composite components, 14-3 concurrency, 56-3, 56-7 connectors, 53-1 Criteria API, 38-15 directory structure, Duke's Bookstore case study, 57-1 Duke’s Forest case study, 59-1 Duke’s Tutoring case study, 58-1 embedded enterprise bean container, file upload using servlets, 17-25 HTML5-friendly markup, 8-20 interceptors, 54-9 Java API for WebSocket, 18-11, 18-14 JAX-RS, 29-15, 31-16 JAX-WS, JMS asynchronous message consumption, 46-9 JMS durable subscriptions, JMS in a web application, 46-25 JMS local transactions, JMS message acknowledgment, 46-14 JMS queue browsing, JMS shared durable subscriptions, 46-24 JMS synchronous message consumption, 46-7 JMS with entities, 46-36 JMS with session beans, 46-32 message-driven beans, 46-29, 46-32, 46-36 persistence, primary keys, 37-7 query language, 38-10, 39-4 required software, 2-1 resource adapters, 53-1 46-18 46-11 46-16 28-2 38-1 Index-8 resource library contracts, 8-15 security, 48-18, 49-9, 49-13 sending JMS messages, 46-4 servlets, 6-8, 17-23, 33-2 session beans, 33-1, 34-1 singleton session beans, 34-7 timer service, 34-21 web clients, 33-2 web services, 34-13 exceptions business methods, 34-5 enterprise beans, 34-24 JMS, 45-19 mapping to error screens, 6-13 rolling back transactions, 34-25, 51-6 transactions, 51-4 expiration of JMS messages, 45-22 JMSExpiration message header field, 45-16 Expression Language. See EL F Facelets, 8-1 composite components, 8-10 configuring applications, 8-7 f:ajax tag, 13-3 features, 8-1 resources, templating, using Ajax with, 13-2 XHTML pages, See also EL 8-12 8-8 8-5 Facelets applications developing, 8-3 lifecycle, 8-3 using JavaScript in, 13-9 Faces Flows, using, faces-config.xml file, 16-3 FacesContext class, 7-14, 15-23 16-5 Apply Request Values phase, 7-15 custom converters, 15-24 performing encoding, Process Validations phase, 7-16 Update Model Values phase, 7-17 validation methods, 12-12 Validator interface, 15-28 15-13 FacesServlet class, 16-31 fetch graphs See persistence fetch graphs fetch plans, 43-1 filter chains, 17-7, 17-9 Filter interface, 17-7 filters, 17-7 defining, 17-7 mapping to web components, 17-9 mapping to web resources, overriding request methods, 17-9 overriding response methods, 17-9 response wrappers, 17-9 17-9 foreign keys, 38-3 form parameters, JAX-RS, form-based authentication, 48-7 forward method, 17-11 29-13, 31-3 G 49-6, 49-13 garbage collection, 32-13 GenericServlet interface, 17-1 getBody method, 45-17 getCallerPrincipal method, getConnection method, 3-2 getPart method, 17-16 getParts method, 17-16 getRemoteUser method, getRequestDispatcher method, 17-10 getRollbackOnly method, 45-33, 51-8 getServletContext method, getSession method, 17-12 getStatus method, 51-8 getUserPrincipal method, 48-12 GlassFish Server 17-11 48-12 adding users to, 47-12 downloading, 2-1 enabling debugging, 2-7 installation tips, 2-1 securing, 47-9 server log, 2-7 SSL connectors, starting, 2-3 stopping, 2-4 tools, 47-16 1-22 groups, 47-12 managing, 47-12 H handling events. See event and listener model hashCode method, 37-6 header parameters, JAX-RS, 29-13 helper classes, 32-11 session bean example, 34-5 HTML5-friendly markup, 8-17 8-20 example, pass-through attributes, 8-18 pass-through elements, 8-17 HTTP, 28-1 basic authentication, 48-6 50-5 over SSL, HTTP cookies, HTTP methods, 29-6 HTTP request and response entity bodies, 29-8 30-7 supported types, 29-8 17-6 HTTP request URLs, query strings, 17-6 request paths, 17-6 HTTP requests, 17-6, 29-6 See also requests HTTP responses, status codes, 17-7 6-13 See also responses 47-7, 47-16, 48-4, 50-2 HTTPS, HttpServlet interface, HttpServletRequest interface, 17-6, 48-12 HttpServletResponse interface, 17-7 HttpSession interface, 17-12 17-1 I identification, 47-4 implicit navigation, implicit objects, 15-34 7-3, 7-10 binding component values to, 15-33 include method, 17-11 init method, 17-5 InitialContext interface, 1-21 initialization parameters, 17-5 initializing properties with the managed-property element initializing Array and List properties, 16-19 initializing managed-bean properties, 16-19 initializing Map properties, 16-18 initializing maps and lists, 16-21 referencing a context initialization parameter, 16-17 initParams attribute, 17-5 injectable objects, CDI, integrity, 47-16 47-5 23-5 of data, Interceptors 54-4 around-construct, invoking, 54-8 lifecycle callback events, 54-4 methods, 54-3 54-8 ordering, interceptors, 54-1 CDI, 25-9 example, 54-9 26-13 example (CDI), internationalization, 20-1 internationalizing JavaServer Faces applications FacesContext.getLocale method, loadBundle tag, 20-4 using the FacesMessage class to create a 11-4 message, 16-22 invalidate method, 17-12 isCallerInRole method, 49-6, 49-13 ISO 8859 character encoding, 20-5 isUserInRole method, 48-12 J JAAS, 1-22, 47-5, 50-13 login modules, 50-14 JACC, 1-19, 47-9 JAF, 1-21 JAR files, JAR signatures, 47-6 JASPIC, 1-19 Java API for JavaBean Validation 5-1 Index-9 See Bean Validation Java API for JavaBean Validation. See Bean Validation Java API for JSON Processing, 1-20 Java API for RESTful Web Services. See JAX-RS Java API for WebSocket, 1-19, 18-1 18-10 annotated endpoints, 18-4 configuring endpoints, creating applications, 18-2 endpoints, 18-1, 58-2, 58-4 error handling, 18-10 examples, 18-11, 18-14 introduction, 18-1 maintaining client state, path parameters, 18-9 programmatic endpoints, 18-6 receiving messages, sending messages, 18-5 using decoders, 18-8 18-7 using encoders, 18-6 18-3 Java Naming and Directory Interface API. See JNDI Java Persistence API, 1-17, 37-1 See also persistence Java Persistence API query language. See query language Java Persistence Criteria API. See Criteria API Java Secure Sockets Extension (JSSE), 47-6 Java Servlet technology, 1-15, 17-1 See also servlets Java Transaction API, 1-17, 51-7 JavaBeans Activation Framework (JAF), 1-21 JavaBeans components, JavaMail API, 1-19 example, 53-1 1-6 JavaServer Faces application development bean property, 12-5 Bean Validation, 21-1 managed beans, 12-1 web pages, 10-1 Java API for XML Binding (JAXB), using with JAX-RS, 31-11 1-21 Java API for XML Processing (JAXP), 1-21 Java API for XML Web Services. See JAX-WS Java Authentication and Authorization Service. See JavaServer Faces applications configuring. See configuring JavaServer Faces applications HTML tags, 10-2 queueing messages, 12-13 JAAS JavaServer Faces core tag library, 10-1, 10-27 Java Authentication Service Provider Interface for Containers (JASPIC), 1-19 Java Authorization Contract for Containers. See JACC Java BluePrints, 2-5 Java Cryptography Extension (JCE), 47-6 Java Database Connectivity API. See JDBC API Java DB, 1-23 starting, 2-4 stopping, 2-4 Java EE applications, 1-3 debugging, 2-7 deploying, 33-3 iterative development, tiers, 1-3 Java EE clients, 1-5 33-4 See also application clients, web clients Java EE components, 1-4 Java EE Connector architecture, 53-1 example, Java EE modules, 5-1, 5-2 1-18, 52-1 application client modules, 5-2 EJB modules, 5-2, 32-11 resource adapter modules, 5-2 See also web modules Java EE platform, 1-3 APIs, 1-12 JMS and, 45-3 overview, 1-1 1-9 Java EE security model, Java EE servers, 1-10 Java EE transaction model, 1-9 Java Generic Security Services, Java GSS-API, 47-5 Java Message Service (JMS) API, 1-18, 45-1 47-5 11-5 10-28 10-27, 11-7, 15-3 10-27, 11-3, 15-26 actionListener tag, ajax tag, 13-3 attribute tag, convertDateTime tag, 10-27, 11-3 convertDateTime tag attributes, 11-4 converter tag, converterId attribute, 11-2 convertNumber tag, 10-27, 11-3, 11-4 convertNumber tag attributes, facet tag, 10-20, 10-28 loadBundle tag, 10-28 metadata tag, 10-23, 10-28 param tag, 10-11, 10-28 selectItem tag, 10-17, 10-18, 10-28 selectItems tag, 10-17, 10-18, 10-28 type attribute, 11-6 validateBean tag, 11-8 validateDoubleRange tag, validateLength tag, validateLongRange tag, 10-28, 11-8, 11-9 validateRegEx tag, 11-8 validateRegex tag, 11-10 validateRequired tag, 11-8 validator tag, 7-10, 10-28, 15-27 10-28, 11-8 10-28, 11-8 custom validator tags, 15-30 valueChangeListener tag, viewparam tag, 10-23 JavaServer Faces standard HTML render kit 10-27, 11-6 library, 7-8, 16-27 html_basic TLD, 15-21 See also component tags JavaServer Faces standard UI components, 7-5, 15-1 UIComponent component, 15-25 JavaServer Faces tag libraries, 8-2 See also JMS, message-driven beans JavaServer Faces core tag library, 10-1, 10-27 Index-10 JavaServer Faces HTML render kit tag library, 10-1 namespace directives, 10-1 JavaServer Faces Technology Faces Flows, resource library contracts, JavaServer Faces technology, 16-5 8-14 1-6, 1-16, 7-1 7-3 10-23 advantages, bookmarkable URLs, component tags. See component tags composite components, 14-1 FacesContext class. See FacesContext class FacesServlet class, 16-31 features, 7-2 HTML5-friendly markup, 8-17 partial processing, 7-17 partial rendering, 7-17 relocatable resources, 8-13 using Ajax with, 13-1, 58-3 Validator interface, 12-12 See also component rendering model See also component tags See also conversion model See also event and listener model See also Facelets See also JavaServer Faces standard UI components See also lifecycle of a JavaServer Faces application See also UI component behavioral interfaces See also UI component classes See also validation model JavaServer Pages Standard Tag Library (JSTL), JavaServer Pages technology, javax.servlet package, 17-1 javax.servlet.http package, 17-1 JAXB, 1-21 1-16 using with JAX-RS, 31-11 1-17 JAXP, 1-21 JAX-RS, 1-17, 29-1 31-1 31-11 accessing XML documents, advanced features, annotations, 31-1 application overview, asynchronous invocations, 30-8 clients, 30-1 conditional HTTP requests, 31-9 configuring, 29-14 converting CDI managed beans to root resource 29-4 classes, 31-8 converting enterprise beans to root resource classes, 31-8 cookies, 30-7 entity providers, 29-8 examples, 29-15, 31-16 extracting Java type of request or response, 31-3 filters, 30-7 form parameters, 31-3 HTTP headers, 30-6 integrating with CDI, integrating with EJB technology, introduction, 27-2 31-8 31-8 30-3 invocations, JSON, 31-15 path parameters, 30-2, 31-2 path templates, 29-5 query parameters, 31-2 reference implementation, 29-1 31-1 request headers, request method designators, 29-2, 29-7 resource class methods, 31-6 resource classes, 29-2 resource methods, runtime content negotiation, 31-9 runtime resource resolution, 31-6 static content negotiation, 31-9 subresource locators, 31-7 subresource methods, 31-7 subresources, 31-6 URI, 31-1 using with JAXB, 31-11 29-2 JAX-RS Client API, JAX-RS clients, JAX-WS, 1-22 29-17 29-17, 30-1 defined, 28-1 endpoints, 28-2 examples, 28-2 introduction, 27-1 service endpoint interfaces, 28-2 specification, 28-10 JCE, 47-6 JDBC API, resources, JMS, 1-18 1-20, 3-2 58-2 46-2 achieving reliability and performance, 45-19 45-7 administered objects, application client examples, architecture, 45-4 basic concepts, 45-3 definition, 45-2 examples, 46-1, 46-25, 46-29 introduction, Java EE platform, 45-3, 45-26 messaging domains, programming model, 45-1 45-4 45-6 45-10 JMSConsumer interface, JMSContext interface, 45-9 JMSCorrelationID message header field, 45-16 JMSDeliveryMode message header field, 45-16 JMSDeliveryTime message header field, 45-16 JMSDestination message header field, 45-16 JMSException class, 45-19 JMSExpiration message header field, 45-16 JMSMessageID message header field, 45-16 JMSPriority message header field, JMSProducer interface, JMSRedelivered message header field, 45-17 JMSReplyTo message header field, 45-16 JMSTimestamp message header field, JMSType message header field, 45-16 JNDI, 1-21, 3-1 45-10 45-16 45-16 data source naming subcontexts, 1-21 Index-11 1-21 enterprise bean lookup, 32-6 enterprise bean naming subcontexts, environment naming contexts, 1-21 jms naming subcontext, 45-8 namespace for JMS administered objects, naming contexts, 1-21 naming environments, 1-21 naming subcontexts, 1-21 Job Specification Language, 55-10 45-7 55-12 batchlet element, 55-14 chunk element, decision element, 55-17 flow element, 55-16 job element, 55-10 partition element, split element, step element, 13-9 55-11 55-16 55-14 jsf.js file, JSON JAX-RS, 31-15 JSR 339. See JAX-RS JSR 346. See Contexts and Dependency Injection for Java EE (CDI) JSSE, 47-6 JSTL, 1-17 JTA, 1-17, 51-7 JTS API, 51-7 JUnit, 35-4 K Kerberos, 47-5, 47-6 key pairs, 50-2 keystores, 47-6, 50-1, 50-2 managing, 50-2 keytool utility, 50-2 L lifecycle of a JavaServer Faces application, 7-4, 7-13 7-9 action and value-change event processing, Apply Request Values phase, 7-15, 15-14 custom converters, 15-24, 15-25 getRendererType method (Render Response phase), 15-18 immediate attribute, Invoke Application phase, 7-17 performing encoding (Render Response 15-7 phase), 15-12 7-16 Process Validations phase, Render Response phase, 7-17 renderResponse method, 7-14, 7-15, 7-16, 7-17 responseComplete method, 7-14, 7-16, 7-17 Restore View phase, saving state, 15-16 Update Model Values phase, 7-16 updateModels method, 7-17 Validator interface, 15-29 views, 7-15 7-15 listener classes, 17-2 Index-12 defining, 17-2 listener interfaces, 17-2 listeners HTTP, 47-9 IIOP, 47-9 load graphs See persistence load graphs local interfaces, 32-8 local transactions, 45-24 localization, 20-1 Bean Validation, 22-3 log, server, 2-7 login configuration, 48-6, 48-8 login method, 48-10 login modules, 50-13 logout method, 48-10 M managed bean creation facility, 16-14 managed bean declarations, 15-7 16-18 key-class element, list-entries element, 16-17 managed-bean element, 16-15, 16-20 managed-bean-name element, 16-15 managed-property element, 16-16 map-entries element, 16-17, 16-18 map-entry element, null-value elements, 16-17 value element, 16-17 16-18 managed bean methods attributes. See attributes referencing managed bean methods referencing. See referencing managed bean methods writing. See writing managed bean methods managed bean properties, 11-2, 12-1, 12-3, 15-31 12-5 bound to component instances, 12-9 UIData properties, UIInput and UIOutput properties, 12-5 UISelectBoolean properties, UISelectItem properties, 12-8 UISelectItems properties, 12-8 UISelectMany properties, 12-7 UISelectOne properties, 12-7 writing, 12-3 12-6 managed beans, 7-2 7-8 14-2 composite components, configuring in JavaServer Faces technology, 16-1 conversion model, custom component alternative, 15-3 defined for CDI, 23-4 developing, 8-4 event and listener model, JavaServer Faces technology, loading JavaScript, method binding, 10-9 properties. See managed bean properties See also value binding 13-10 12-1 7-9 Managed Beans specification, 1-17, 23-1 ManagedExecutorService interface, 56-2 ManagedScheduledExecutorService interface, ManagedThreadFactory interface, 56-2 MapMessage interface, 45-17 mapping URLs, 29-14 matrix parameters, JAX-RS, Maven tool, message acknowledgment, 45-20 29-13 2-3 56-2 46-14 bean-managed transactions, 45-33 example, message bodies, message consumers, shared, 45-15 message consumption, 45-17 45-10 45-6 asynchronous, 45-6, 46-9 synchronous, 45-6, 46-7 message headers, 45-16 45-16 message IDs, JMS, Message interface, 45-17 message listeners, 32-4, 45-11 examples, 46-9, 46-38 message producers, 45-10 message properties, 45-17 message security, message selectors, 45-12 message subscriptions durable, 45-13 48-2 MessageBodyReader interface, MessageBodyWriter interface, message-driven beans, 1-15, 32-4 29-8 29-8 accessing, 32-4 coding, 46-30, 46-34, 46-38 defined, 32-4 examples, 46-29, 46-32, 46-36 garbage collection, 32-13 introduction, 45-29 onMessage method, 32-5, 46-30 requirements, 46-30 transactions, 32-5, 51-2, 51-7 MessageListener interface, 45-11 messages 50-5 integrity, MessageFormat pattern, 10-11, 10-28 outputFormat tag, 10-11 param tag, 10-11, 10-28 parameter substitution tags, 10-28 queueing messages, 12-13, 16-21 securing, 47-7 using the FacesMessage class to create a message, 16-22 messages, JMS body formats, 45-17 browsing, 45-18 definition, 45-4 delivery delay, 45-23 delivery modes, expiration, 45-22 headers, 45-16 introduction, 45-16 45-21 persistence, 45-21 priority levels, 45-22 properties, 45-17 messaging domains, point-to-point, publish/subscribe, 45-5 messaging, definition, 45-1 metadata annotations 45-5 45-4 resource adapters, 52-4 security, 47-8 Metamodel API, 40-1 using, 38-15, 40-2 method binding method expressions, 15-14 method-binding expressions, 7-11, 16-26 method expressions, 7-9, 11-10 method permissions, 49-3 annotations, 49-3 methods, static, 21-5 mutual authentication, 50-5, 50-7 N naming contexts, 1-21 naming environments, 1-21 navigation configuring, 7-10, 16-25 implicit, 7-10 navigation model, 7-10 action attribute, 10-12, 11-10, 11-11, 15-7 action methods, 12-11, 16-25 ActionEvent class, 11-11 configuring navigation rules, 16-25 logical outcome, 12-11, 16-25 NavigationHandler class, 7-12 referencing methods that perform navigation, 11-11, 12-11 writing a managed bean method to perform navigation processing, 12-11 NetBeans IDE, NON_PERSISTENT delivery mode, non-repudiation, 47-5 2-2 45-22 O ObjectMessage interface, 45-17 objects, administered, 45-7 creating and removing, 46-3 observer methods, CDI, onMessage method introduction, message-driven beans, 45-11 25-7 32-5, 45-30, 46-30 P package-appclient tool, 1-23 packaging applications, 5-1 path parameters, JAX-RS, path templates, JAX-RS, 29-5 permissions, security policy, 47-10 Persistence 29-13, 31-2 Index-13 schema creation, 58-2 persistence 43-2 43-4 37-3 38-8 38-8 37-10 BLOBs, 38-8 cascade operations, CLOBs, collections, concurrent access to entity data, 42-1 configuration, 37-17 context, 37-14 creating database tables, 37-20 criteria queries, 43-1, 43-4 DDL scripts, 37-20 dropping database tables, 37-20 eager fetching, 43-1 embeddable classes, entities, 37-1 entity graph properties, examples, 38-1 fetch graphs, JMS example, 46-36 JMS messages, 45-21 JPQL, 43-1 lazy fetching, 43-1 load graphs, 43-2 loading data, locking strategies, 42-1 many-to-many, maps, 37-4 named entity graphs, 43-3 one-to-many, 38-3 one-to-one, 38-3 overview, 37-1 persistence units, persistent fields, primary keys, 37-6, 38-4, 38-5 properties, 37-3 queries, 37-1, 37-18, 38-10, 39-2, 43-1 37-17 37-2 37-21 38-13 creating, 40-4 Criteria, 40-1 dynamic, 39-2 executing, 40-9 expressions, 40-6, 40-7 joins, 40-5 parameters, 39-2, 39-3 path navigation, 40-6 results, 40-6, 40-8 static, 39-2 typesafe, 40-1 See also query language 38-2 query hints, 43-4 query language, 37-9 relationships, schema creation, 37-19 scope, 37-17 second-level cache, 44-1 self-referential relationships, 38-2 string-based criteria queries, 41-1 temporal types, 38-9 persistence units, query language, PERSISTENT delivery mode, 45-22 39-1, 39-14 Index-14 pluggable audit modules, pluggable authorization providers, 47-9 point-to-point messaging domain, 45-5 point-to-point messaging style 47-10 See also queues 1-2 POJOs, policy files, 47-6 primary keys, 38-3 38-5 compound, defined, 37-6 examples, 37-7 generated, 38-4 principal, 47-12 PrintWriter class, 17-6 priority levels, for messages, 45-22 JMSPriority message header field, 45-16 producer fields CDI, 25-4 example, 26-8 producer methods CDI, 23-10, 25-4 example, 26-5 programmatic security, 47-2, 47-9, 48-2, 49-2 example, 49-13 45-4 45-6 programming model, JMS, providers, JMS, proxies, 28-1 public key certificates, 50-5 public-key cryptography, 50-2 publish/subscribe messaging domain durable subscriptions, 45-13 introduction, 45-5 publish/subscribe messaging style See also topics Q qualifiers, using in CDI, Quality of Service, 47-5 queries 23-5 43-1 criteria, JPQL, 43-1 persistence, 43-1 query language ABS function, 39-23 abstract schemas, 39-1, 39-3, 39-15 ALL expression, 39-21 ANY expression, 39-21 arithmetic functions, 39-22 ASC keyword, 39-27 AVG function, 39-25 BETWEEN expression, Boolean literals, 39-18 Boolean logic, 39-24 case expressions, 39-23 collection member expressions, 39-15, 39-21 collections, 39-15, 39-20, 39-21 compared to SQL, comparison operators, 39-7, 39-19 CONCAT function, 39-22 39-5, 39-14, 39-16 39-7, 39-19 conditional expressions, 39-6, 39-17, 39-18, 39-24 constructors, 39-26 COUNT function, 39-25 DELETE expression, 39-8 DELETE statement, 39-4 DESC keyword, 39-27 DISTINCT keyword, 39-4 domain of query, 39-1, 39-12, 39-14 duplicate values, 39-4 enum literals, 39-18 equality, 39-24 ESCAPE clause, 39-20 examples, 38-10, 39-4 EXISTS expression, 39-21 FETCH JOIN operator, 39-16 FROM clause, 39-3, 39-12 grammar, 39-8 GROUP BY clause, 39-3, 39-27 HAVING clause, 39-4, 39-27 identification variables, 39-3, 39-12, 39-14 identifiers, 39-12 IN operator, 39-16, 39-19 INNER JOIN operator, 39-16 input parameters, 39-6, 39-18 IS EMPTY expression, 39-7 IS FALSE operator, 39-24 IS NULL expression, 39-7 IS TRUE operator, 39-24 JOIN statement, 39-5, 39-15 LEFT JOIN operator, 39-16 LEFT OUTER JOIN operator, 39-16 LENGTH function, 39-22 LIKE expression, 39-6, 39-20 literals, 39-17 LOCATE function, 39-22 LOWER function, 39-22 MAX function, 39-25 MEMBER expression, 39-21 MIN function, 39-25 MOD function, 39-23 multiple declarations, 39-14 multiple relationships, 39-6 named parameters, 39-5, 39-18 navigation, 39-5, 39-6, 39-15, 39-17 negation, NOT operator, null values, 39-20, 39-24 numeric comparisons, numeric literals, 39-18 operator precedence, 39-18 operators, 39-18 ORDER BY clause, 39-4, 39-27 parameters, 39-4 parentheses, path expressions, positional parameters, 39-15 range variables, relationship fields, relationships, return types, 39-25 39-2 39-1, 39-5, 39-6 39-2, 39-16 39-18 39-24 39-18 39-24 39-24 39-5 39-3, 39-25 root, 39-15 scope, 39-1 SELECT clause, setNamedParameter method, SIZE function, 39-23 SQRT function, 39-23 state fields, 39-2 string comparison, 39-24 string functions, 39-22 string literals, 39-18 subqueries, 39-21 SUBSTRING function, 39-22 SUM function, syntax, 39-3, 39-8 TRIM function, 39-22 39-17, 39-24 types, UPDATE expression, UPPER function, 39-22 WHERE clause, 39-3, 39-17 wildcards, 39-20 39-26 39-4, 39-8 query parameters, JAX-RS, 29-11, 31-2 query roots, 40-5 Queue interface, 45-8 QueueBrowser interface, 45-18 JMS client example, 46-11 45-18, 46-11 queues, 45-8 browsing, creating, 45-8, 46-42 injecting resources, 46-29 temporary, 45-23, 46-38 R RAR files, packaging, realms, 47-10, 47-11 admin-realm, certificate, configuring, 47-9 file, 47-11 5-5 47-11 47-11, 50-4 receiveBody method, 45-18 recover method, 45-21 redelivery of messages, 45-20, 45-21 JMSRedelivered message header field, 45-17 referencing managed bean methods, 11-10 for handling action events, 11-11, 12-12 for handling value-change events, 11-12 for performing navigation, 11-11, 12-11 11-11, 12-12 for performing validation, registering custom converters, 16-24 converter element, 16-24 registering custom renderers, 16-27 renderer element, render-kit element, 16-27 16-27 registering custom UI components, 15-9, 16-29 component element, 16-29 registering custom validators, 16-24 validator element, 16-24 registering messages, 16-21 resource-bundle element, 16-21 relationship fields, query language, 39-2 Index-15 relationships direction, 37-8 unidirectional, 38-4 reliability, JMS 45-21 basic mechanisms, durable subscriptions, 45-13 local transactions, 45-24 message acknowledgment, 45-20 message delivery delay, 45-23 message expiration, 45-22 message persistence, 45-21 message priority levels, 45-22 temporary destinations, 45-23 relocatable resources, remote interfaces, 32-9 Remote Method Invocation (RMI), and 8-13 messaging, 45-1 request headers, JAX-RS, 31-1 request method designators, JAX-RS, 29-2, 29-7 Request objects, JAX-RS, 31-10 request parameters, JAX-RS, 29-11 RequestDispatcher interface, request/reply mechanism 17-10 JMSCorrelationID message header field, 45-16 JMSReplyTo message header field, 45-16 temporary destinations and, 45-23 requests, 17-5 customizing, 17-8 getting information from, 17-5 retrieving a locale, 20-2 See also HTTP requests Required transaction attribute, 45-33 resource adapters, 1-18, 52-1 53-1 example, metadata annotations, 52-4 packaging, 5-5 security, 50-15 resource bundles, 20-1 Bean Validation, 22-2 resource classes, JAX-RS, resource library contracts, 29-2 8-14 example, 8-15 resource methods, JAX-RS, 29-2 resources, 52-1 JMS, 45-29 relocatable, See also data sources ResponseBuilder class, responses, 17-6 8-13 29-8 17-6 buffering output, customizing, 17-8 setting headers, 17-5 See also HTTP responses RESTful web services, 1-17, 29-1 defined, 29-1 roles, 47-12 application, 47-14 declaring, 48-9 mapping to groups, 47-14 mapping to users, 47-14 Index-16 referencing, 49-3 security, 47-13, 48-9, 49-3 51-6, 51-7, 51-8 rollback method, rollback method (JMS), 45-24 rollbacks. See transactions, rollbacks root resource classes, 29-2 run-as identity, 49-8 S SAAJ, 1-22 SASL, 47-6 schemagen tool, schemas 1-23 creating, 37-19 deployment descriptors, 47-8 scopes 6-6 CDI, 23-7 introduction, JavaServer Faces technology, servlets, 17-4 secure connections, Secure Sockets Layer (SSL), 47-15 security 47-15 16-2 56-3 49-1 50-14 47-1, 47-8 50-13 50-13 annotations, 47-8, 48-16, 49-1 application, 47-4, 47-6 application clients, callback handlers, component-managed sign-on, 50-15 concurrency and, constraints, 48-2 container trust, 49-9 container-managed sign-on, containers, context for enterprise beans, 49-6 declarative, 47-1, 47-8, 48-1, 49-1 deploying enterprise beans, 49-9 EIS applications, 50-14 47-7 end-to-end, enterprise applications, 49-1 enterprise beans, examples, 48-18, 49-9, 49-13 groups, 47-12 introduction, JAAS login modules, 50-14 Java SE, 47-5 login forms, login modules, 50-13 mechanism features, 47-4 mechanisms, 47-5, 47-6 message, 48-2 message-layer, 47-7 method permissions, 49-3 overview, 47-1 policy domain, programmatic, 47-2, 47-9, 48-2, 48-10, 49-2 programmatic login, 50-14 propagating identity, 49-8 realms, 47-11 resource adapters, 50-15 47-12 50-13 47-1 role names, 48-9, 49-3 roles, 47-12, 47-13, 48-9, 49-3 run-as identity, 49-8 simple walkthrough, transport-layer, 47-7, 47-15 users, 47-11 48-1 web applications, web components, 48-1 48-2 47-2 security constraints, multiple, 48-5 security domain, 47-12 security identity 49-8 propagating, 49-8 specific identity, security role references, security roles, 47-13, 49-3 security-role-mapping element, 47-14 security-role-ref element, 48-13 send method, 45-10 sending messages 48-13 45-25 Java EE components, 45-28 JMS client example, 46-4 sending messages asynchronously, server authentication, 50-5 server certificates, 50-1 server log, 2-7 service methods, servlets, 17-5 Servlet interface, ServletContext interface, 17-11 ServletInputStream class, 17-6 ServletOutputStream class, 17-6 ServletRequest interface, 17-5 ServletResponse interface, 17-6 servlets, 1-6, 17-1 17-1 17-6 asynchronous processing, 17-16 binary data, 17-6 character data, compiling, 33-3 creating, 17-4 examples, 6-8, 17-23, 33-2 finalizing, 17-13 initializing, 17-5 17-2 lifecycle, lifecycle events, nonblocking I/O, packaging, 33-3 scope objects, 17-4 service methods, 17-5, 17-14, 17-15 specifying initialization parameters, 17-5 tracking service requests, 17-14 uploading files with, 17-15, 19-1 17-19 17-2 session beans, 1-15, 32-2 activation, 32-12 bean-managed concurrency, 34-8, 34-10 business interfaces, 32-5 clients, 32-2 concurrent access, container-managed concurrency, databases, eager initialization, 34-7 34-8 34-8 51-6 32-5 examples, 33-1, 34-1, 34-7, 34-13, 46-32 34-11 handling errors, no-interface views, passivation, 32-12 requirements, 34-2 singleton, 32-3, 34-7 stateful, 32-2, 32-3 stateless, 32-3, 32-4 transactions, 51-2, 51-6, 51-7 web services, 32-10, 34-14 See also asynchronous method invocation Session interface, 45-9 sessions, 17-12 associating attributes, 17-12 associating with user, 17-13 invalidating, 17-12 notifying objects associated with, 17-12 sessions, JMS, 45-9 managing in enterprise bean applications, 45-29 SessionSynchronization interface, 51-6 setRollbackOnly method, 45-33, 51-6, 51-8 shared durable subscriptions, shared message consumers, 45-15 sign-on 45-15 component-managed, 50-14, 50-15 container-managed, 50-14 Simple Authentication and Security Layer (SASL), 47-6 SingleThreadModel interface, 17-4 SOAP, 27-1, 28-1, 28-10 SOAP messages, securing, 1-11, 1-22 47-7 SOAP with Attachments API for Java (SAAJ), 1-22 specialization, CDI, 25-3 SQL, 1-20, 39-5, 39-14, 39-16 loading data, 37-21 SQL92, 39-24 SSL, 47-7, 47-15, 48-4, 50-5 connectors, GlassFish Server, 47-16 handshake, verifying support, 47-16 47-16 standard converters, 7-8 converter tags, 11-3 NumberConverter class, 11-2 using, 11-1 standard validators, using, 11-8 7-10 state fields, query language, 39-2 stereotypes, CDI, 25-12 StreamMessage interface, 45-17 string-based criteria queries, subresources, JAX-RS, 31-6 subscription names, for durable subscribers, substitution parameters, defining. See messages, 41-1 45-13 param tag synchronous message consumption, Java EE components, 45-28 JMS client example, 46-7 45-6 Index-17 T templating Facelets, 8-8 temporary JMS destinations, 45-23 examples, 46-38 testing enterprise beans, 35-4 unit, 35-4 34-20 34-16, 34-20 TextMessage interface, 45-17 timer service, 34-16 automatic timers, calendar-based timer expressions, cancelling timers, creating timers, 34-19 examples, 34-21 exceptions, 34-21 getInfo method, 34-21 getNextTimeout method, 34-21 getTimeRemaining method, 34-21 getting information, 34-21 programmatic timers, 34-16, 34-18 saving timers, 34-20 transactions, 34-21 34-16 timestamps for JMS messages, Topic interface, 45-8 topics, 45-8 45-16 creating, 45-8, 46-42 durable subscriptions, 45-13 temporary, 45-23 transactions, 51-1 37-15 application-managed, attributes, 51-3, 51-5 bean-managed, 45-32, 51-7, 51-8 boundaries, 51-2, 51-6, 51-7 business methods. See business methods, 56-3 45-32 45-32, 51-2 transactions commits, 51-2, 51-6 concurrency and, container-managed, container-managed transaction demarcation, 51-2 defined, 51-2 distributed, examples, 46-18 exceptions. See exceptions, transactions JDBC, JMS and enterprise bean applications, JTA, 51-7 local, 45-24 managers, 51-4, 51-7, 51-8 message-driven beans. See message-driven beans, 45-29 51-8 transactions 51-3 nested, 51-2, 51-7 Required attribute, 45-33 rollbacks, 51-2, 51-6, 51-7 scope, session beans. See session beans, transactions timeouts, 51-8 timer service, 34-21 web components, 51-9 48-4 transport guarantees, Index-18 transport-guarantee element, 48-4 47-7, 47-15 transport-layer security, truststores, 50-1, 50-2 managing, 50-2 U UI component behavioral interfaces, 7-6 ActionSource interface, 7-6, 7-9, 15-10, 15-18 ActionSource2 interface, 7-6, 15-10 ClientBehaviorHolder interface, ConvertibleValueHolder interface, 7-6 EditableValueHolder interface, 7-6, 15-10 NamingContainer interface, 7-6, 15-10 StateHolder interface, SystemEventListenerHolder interface, ValueHolder interface, 7-6, 15-10, 15-16 7-7 7-7 7-7, 15-10 UI component classes, 7-5, 7-7, 15-2 7-6 12-5 7-6, 7-7 javax.faces.component package, 15-10 UIColumn class, 7-6 UICommand class, UIComponent class, 7-5, 7-7 UIComponentBase class, 7-5, 15-10, 15-12 UIData class, 7-6, 12-5 UIForm class, 7-6 UIGraphic class, UIInput and UIOutput classes, UIInput class, 7-6, 7-9 UIMessage class, 7-6 UIMessages class, 7-6 UIOutcomeTarget class, 7-6 UIOutput class, 7-6, 7-8 UIPanel class, 7-6 UIParameter class, 7-6 UISelectBoolean class, 7-6, 12-6 UISelectItem class, 7-6, 12-8 UISelectItems class, 7-6, 12-8 UISelectMany class, 7-6, 12-7 UISelectOne class, 7-6, 7-7, 12-7 UIViewRoot class, 7-6 See also custom UI components UnavailableException class, 17-5 undeploying modules and applications, 6-8 Unicode character set, 20-4 unified expression language. See EL Uniform Resource Identifiers (URIs), URI path parameters, JAX-RS, 29-13 URI path templates, JAX-RS, 29-4, 29-5 URL paths, 6-9 URLs, mapping, 29-14 US-ASCII character set, user data constraints, 48-3, 48-4 user-data-constraint element, 48-4 users, 47-11 20-4 29-1 adding to GlassFish Server, managing, 47-12 47-12 UserTransaction interface, 37-15, 51-6, 51-7, 51-8, 51-9 message-driven beans, 45-32 using pages, 8-12 UTF-8 character encoding, 20-5 utility classes, 32-11 ValueExpression class, 12-3 value-change events, 7-9, 15-19 V validating input. See Bean Validation, validation model validation, 21-1 customizing, 22-1 entities, 37-4 groups, 22-3 localization, 22-3 messages, ordering, 22-2 22-3 processValueChange(ValueChangeEvent) method, 15-19 processValueChangeEvent method, 12-13 referencing methods that handle value-change events, 11-12 type attribute, 11-6 ValueChangeEvent class, 11-6, 15-19 valueChangeListener attribute, 10-9, 11-10, 12-13 ValueChangeListener class, 11-6, 12-13, 15-19 ValueChangeListener implementation, 15-19 valueChangeListener tag, writing a managed bean method to handle 10-27, 11-6, 15-3 validation model, 7-5, 7-9 referencing a method that performs value-change events, 12-13 Variant class, JAX-RS, 31-10 11-11 validation, validator attribute, Validator implementation, 7-10, 15-30 Validator interface, 7-10, 12-11, 12-12 10-9, 11-10, 11-11, 12-12 custom validator tags, implementing, 15-28 15-29 writing a managed bean method to perform validation, See also validators 12-12 7-10, 11-8 Validator implementation classes, BeanValidator class, 11-8 DoubleRangeValidator class, 10-28, 11-8 LengthValidator class, LongRangeValidator class, 10-28, 11-8, 11-9 RegexValidator class, RequiredValidator class, 11-8 11-8, 11-10 10-28, 11-8 validator tags 11-8 composite components, 14-2 validateBean tag, 11-8 validateDoubleRange tag, validateLength tag, 11-8 validateLongRange tag, 11-8, 11-9 validateRegex tag, 11-8, 11-10 validateRequired tag, 11-8 validator tag, 7-10, 15-30 7-5, 7-15 validators, custom validators, 10-28, 15-30 default, 16-23 registering, 11-9 standard, value binding 11-8 12-4 acceptable types of component values, component instances to bean properties. See component binding component values and instances to managed bean properties, 15-31 component values to implicit objects, 15-33 component values to managed bean properties, 15-32 12-4 properties, value attribute, value expressions, 12-5, 15-14, 15-34 value-binding expressions, 15-32 12-3, 15-7, 15-31, 15-32 W W3C, 1-21, 28-1, 28-10 WAR files, 5-1 web applications, 5-4, 6-1 configuring, 6-2 deployment descriptors, 6-2 document roots, 5-4 establishing the locale, 20-2 internationalizing and localizing, JMS example, maintaining state across requests, 17-12 parsing and formatting localized dates and 46-25 20-1 numbers, 20-4 20-2 20-3 presentation-oriented, 6-1 providing localized messages, retrieving localized messages, securing, service-oriented, setting the resource bundle, specifying context parameters, 6-12 specifying welcome files, 20-3 6-12 48-1 6-1 web clients, 1-5, 6-1 examples, 33-2 web components, 1-6, 6-1 applets bundled with, 1-6 concurrent access to shared resources, 17-4 forwarding to other web components, 17-11 including other web resources, 17-11 invoking other web resources, 17-10 mapping exceptions to error screens, mapping filters to, 17-9 scope objects, securing, sharing information, transactions, 51-9 types, 1-6 utility classes bundled with, 1-6 web context, 17-11 web container, 1-10, 6-2 6-13 17-4 48-1 17-3 loading and initializing servlets, mapping URLs to web components, 6-9 17-2 value expressions, 12-3 web modules, 5-2, 5-4 Index-19 6-6 packaging and deploying, 6-8 undeploying, viewing deployed, web pages, XHTML, 8-2 web resource collections, 48-3 web resources, 5-4 6-7 Facelets, 8-12 mapping filters to, 17-9 unprotected, 48-3 web services, 1-10 6-15 declaring references to, endpoint implementation classes, examples, 28-2, 34-13 introduction, 27-1 JAX-RS compared to JAX-WS, See also enterprise beans 27-1 34-14 48-3 web-resource-collection element, WebSocket. See Java API for WebSocket web.xml file, 5-4, 16-29, 47-9, 49-3 welcome files, 6-12 work flows, 32-4 writing managed bean methods, 12-10 for handling action events, 12-12 for handling value-change events, 12-13 for performing navigation, 12-11 for performing validation, 12-12 writing managed bean properties converters, 12-10 listeners, 12-10 validators, 12-10 WSDL, 1-11, 27-1, 28-1, 28-10 wsgen tool, 1-23 wsimport tool, 1-23 X xjc tool, 1-23 XML, 1-11, 28-1 XML schema mappings of Java classes to XML data types, mappings to Java data types, 28-9 28-9 Index-20