[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:
Hello, my name is Duke. What's yours?
Hello, #{hello.name}!