Tải bản đầy đủ (.pdf) (1,124 trang)

Tài liệu The Java EE Tutorial For Sun Java System Application Server 9.1 pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (9.66 MB, 1,124 trang )

The Java EE Tutorial
For Sun Java System Application Server 9.1
Sun Microsystems, Inc.
4150 Network Circle
Santa Clara, CA 95054
U.S.A.
Part No: 819–3669–10
September 2007
Copyright 2007 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, CA 95054 U.S.A. All rights reserved.
Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without
limitation, these intellectual property rights may include one or more U.S. patents or pending patent applications in the U.S. and in other countries.
U.S. Government Rights – Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions
of the FAR and its supplements.
This distribution may include materials developed by third parties.
Parts of the product may be derived from Berkeley BSD systems, licensed from the University of California. UNIX is a registered trademark in the U.S. and other
countries, exclusively licensed through X/Open Company, Ltd.
Sun, Sun Microsystems, the Sun logo, the Solaris logo, the Java Coee Cup logo, docs.sun.com, Java, and Solaris are trademarks or registered trademarks of Sun
Microsystems, Inc. in the U.S. and other countries. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC
International, Inc. in the U.S. and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc.
The OPEN LOOK and Sun
TM
Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges the pioneering eorts
of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to
the Xerox Graphical User Interface, which license also covers Sun's licensees who implement OPEN LOOK GUIs and otherwise comply with Sun's written license
agreements.
Products covered by and information contained in this publication are controlled by U.S. Export Control laws and may be subject to the export or import laws in
other countries. Nuclear, missile, chemical or biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly prohibited. Export
or reexport to countries subject to U.S. embargo or to entities identied on U.S. export exclusion lists, including, but not limited to, the denied persons and specially
designated nationals lists is strictly prohibited.
DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO


THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.
Copyright 2007 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, CA 95054 U.S.A. Tous droits réservés.
Sun Microsystems, Inc. détient les droits de propriété intellectuelle relatifs à la technologie incorporée dans le produit qui est décrit dans ce document. En particulier,
et ce sans limitation, ces droits de propriété intellectuelle peuvent inclure un ou plusieurs brevets américains ou des applications de brevet en attente aux Etats-Unis
et dans d'autres pays.
Cette distribution peut comprendre des composants développés par des tierces personnes.
Certaines composants de ce produit peuvent être dérivées du logiciel Berkeley BSD, licenciés par l'Université de Californie. UNIX est une marque déposée aux
Etats-Unis et dans d'autres pays; elle est licenciée exclusivement par X/Open Company, Ltd.
Sun, Sun Microsystems, le logo Sun, le logo Solaris, le logo Java Coee Cup, docs.sun.com, Java et Solaris sont des marques de fabrique ou des marques déposées de
Sun Microsystems, Inc. aux Etats-Unis et dans d'autres pays. Toutes les marques SPARC sont utilisées sous licence et sont des marques de fabrique ou des marques
déposées de SPARCInternational, Inc. aux Etats-Unis et dans d'autres pays. Les produits portant les marques SPARC sont basés sur une architecture développée par
Sun Microsystems, Inc.
L'interface d'utilisation graphique OPEN LOOK et Sun a été développée par Sun Microsystems, Inc. pour ses utilisateurs et licenciés. Sun reconnaît les eorts de
pionniers de Xerox pour la recherche et le développement du concept des interfaces d'utilisation visuelle ou graphique pour l'industrie de l'informatique. Sun détient
une licence non exclusive de Xerox sur l'interface d'utilisation graphique Xerox, cette licence couvrant également les licenciés de Sun qui mettent en place l'interface
d'utilisation graphique OPEN LOOK et qui, en outre, se conforment aux licences écrites de Sun.
Les produits qui font l'objet de cette publication et les informations qu'il contient sont régis par la legislation américaine en matière de contrôle des exportations et
peuvent être soumis au droit d'autres pays dans le domaine des exportations et importations. Les utilisations nales, ou utilisateurs naux, pour des armes nucléaires,
des missiles, des armes chimiques ou biologiques ou pour le nucléaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ou
réexportations vers des pays sous embargo des Etats-Unis, ou vers des entités gurant sur les listes d'exclusion d'exportation américaines, y compris, mais de manière
non exclusive, la liste de personnes qui font objet d'un ordre de ne pas participer, d'une façon directe ou indirecte, aux exportations des produits ou des services qui
sont régis par la legislation américaine en matière de contrôle des exportations et la liste de ressortissants spéciquement designés, sont rigoureusement interdites.
LA DOCUMENTATION EST FOURNIE "EN L'ETAT" ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRESSES OU TACITES
SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE
IMPLICITE RELATIVE A LA QUALITE MARCHANDE, A L'APTITUDE A UNE UTILISATION PARTICULIERE OU A L'ABSENCE DE CONTREFACON.
070913@18741
Contents
Preface 29
Part I Introduction 39
1 Overview 41

Java EE Application Model 42
Distributed Multitiered Applications 42
Security 43
Java EE Components 44
Java EE Clients 44
Web Components 46
Business Components 47
Enterprise Information System Tier 48
Java EE Containers 48
Container Services 49
Container Types 49
Web Services Support 51
XML 51
SOAP Transport Protocol 52
WSDL Standard Format 52
UDDI and ebXML Standard Formats 52
Java EE Application Assembly and Deployment 52
Packaging Applications 53
Development Roles 54
Java EE Product Provider 55
Tool Provider 55
Application Component Provider 55
3
Application Assembler 56
Application Deployer and Administrator 56
Java EE 5 APIs 57
Enterprise JavaBeans Technology 57
Java Servlet Technology 58
JavaServer Pages Technology 58
JavaServer Pages Standard Tag Library 58

JavaServer Faces 58
Java Message Service API 59
Java Transaction API 59
JavaMail API 59
JavaBeans Activation Framework 59
Java API for XML Processing 60
Java API for XML Web Services (JAX-WS) 60
Java Architecture for XML Binding (JAXB) 60
SOAP with Attachments API for Java 60
Java API for XML Registries 61
J2EE Connector Architecture 61
Java Database Connectivity API 61
Java Persistence API 62
Java Naming and Directory Interface 62
Java Authentication and Authorization Service 62
Simplied Systems Integration 63
Sun Java System Application Server Platform Edition 9 63
Tools 63
2 Using theTutorial Examples 65
Required Software 65
Tutorial Bundle 65
Java Platform, Standard Edition 66
Sun Java System Application Server 9.1 66
NetBeans IDE 67
Apache Ant 68
Starting and Stopping the Application Server 68
Starting the Admin Console 69
Contents
The Java EE Tutorial • September 20074
Starting and Stopping the Java DB Database Server 69

Building the Examples 70
Building the Examples Using NetBeans IDE 70
Building the Examples on the Command-Line Using Ant 70
Tutorial Example Directory Structure 71
Debugging Java EE Applications 72
Using the Server Log 72
Using a Debugger 73
Part II TheWeb Tier 75
3 Getting Started withWeb Applications 77
Web Applications 77
Web Application Life Cycle 80
Web Modules 81
Packaging Web Modules 83
Deploying a WAR File 84
Testing Deployed Web Modules 85
Listing Deployed Web Modules 86
Updating Web Modules 86
Undeploying Web Modules 88
Conguring Web Applications 89
Mapping URLs to Web Components 89
Declaring Welcome Files 91
Setting Initialization Parameters 92
Mapping Errors to Error Screens 93
Declaring Resource References 94
Duke’s Bookstore Examples 96
Accessing Databases from Web Applications 97
Populating the Example Database 97
Creating a Data Source in the Application Server 98
Further Information about Web Applications 98
Contents

5
4 Java Servlet Technology 99
What Is a Servlet? 99
The Example Servlets 100
Troubleshooting Duke's Bookstore Database Problems 102
Servlet Life Cycle 102
Handling Servlet Life-Cycle Events 103
Handling Servlet Errors 105
Sharing Information 105
Using Scope Objects 105
Controlling Concurrent Access to Shared Resources 106
Accessing Databases 107
Initializing a Servlet 109
Writing Service Methods 110
Getting Information from Requests 110
Constructing Responses 112
Filtering Requests and Responses 114
Programming Filters 115
Programming Customized Requests and Responses 117
Specifying Filter Mappings 119
Invoking Other Web Resources 122
Including Other Resources in the Response 122
Transferring Control to Another Web Component 124
Accessing the Web Context 124
Maintaining Client State 125
Accessing a Session 125
Associating Objects with a Session 126
Session Management 126
Session Tracking 127
Finalizing a Servlet 128

Tracking Service Requests 129
Notifying Methods to Shut Down 129
Creating Polite Long-Running Methods 130
Further Information about Java Servlet Technology 131
Contents
The Java EE Tutorial • September 20076
5 JavaServer PagesTechnology 133
What Is a JSP Page? 133
A Simple JSP Page Example 134
The Example JSP Pages 136
The Life Cycle of a JSP Page 142
Translation and Compilation 142
Execution 143
Creating Static Content 144
Response and Page Encoding 145
Creating Dynamic Content 145
Using Objects within JSP Pages 145
Unied Expression Language 146
Immediate and Deferred Evaluation Syntax 148
Value and Method Expressions 150
Dening a Tag Attribute Type 156
Deactivating Expression Evaluation 157
Literal Expressions 158
Resolving Expressions 160
Implicit Objects 162
Operators 163
Reserved Words 163
Examples of EL Expressions 164
Functions 165
JavaBeans Components 167

JavaBeans Component Design Conventions 167
Creating and Using a JavaBeans Component 168
Setting JavaBeans Component Properties 169
Retrieving JavaBeans Component Properties 171
Using Custom Tags 172
Declaring Tag Libraries 172
Including the Tag Library Implementation 174
Reusing Content in JSP Pages 175
Transferring Control to Another Web Component 176
jsp:param Element 176
Including an Applet 176
Setting Properties for Groups of JSP Pages 179
Contents
7
Deactivating EL Expression Evaluation 180
Further Information about JavaServer Pages Technology 183
6 JavaServer Pages Documents 185
The Example JSP Document 185
Creating a JSP Document 188
Declaring Tag Libraries 190
Including Directives in a JSP Document 191
Creating Static and Dynamic Content 193
Using the jsp:root Element 196
Using the jsp:output Element 196
Identifying the JSP Document to the Container 200
7 JavaServer Pages Standard Tag Library 201
The Example JSP Pages 201
Using JSTL 203
Tag Collaboration 204
Core Tag Library 205

Variable Support Tags 205
Flow Control Tags 206
URL Tags 210
Miscellaneous Tags 211
XML Tag Library 211
Core Tags 213
Flow Control Tags 214
Transformation Tags 215
Internationalization Tag Library 215
Setting the Locale 216
Messaging Tags 216
Formatting Tags 217
SQL Tag Library 218
query Tag Result Interface 220
JSTL Functions 222
Further Information about JSTL 223
Contents
The Java EE Tutorial • September 20078
8 CustomTags in JSP Pages 225
What Is a Custom Tag? 226
The Example JSP Pages 226
Types of Tags 229
Tags with Attributes 229
Tags with Bodies 232
Tags That Dene Variables 232
Communication between Tags 233
Encapsulating Reusable Content Using Tag Files 233
Tag File Location 235
Tag File Directives 235
Evaluating Fragments Passed to Tag Files 242

Custom Tag Examples 243
Tag Library Descriptors 247
Top-Level Tag Library Descriptor Elements 248
Declaring Tag Files 249
Declaring Tag Handlers 251
Declaring Tag Attributes for Tag Handlers 252
Declaring Tag Variables for Tag Handlers 254
Programming Simple Tag Handlers 256
Including Tag Handlers in Web Applications 256
How Is a Simple Tag Handler Invoked? 256
Tag Handlers for Basic Tags 257
Tag Handlers for Tags with Attributes 257
Tag Handlers for Tags with Bodies 260
Tag Handlers for Tags That Dene Variables 261
Cooperating Tags 263
Tag Handler Examples 265
9 Scripting in JSP Pages 273
The Example JSP Pages 273
Using Scripting 275
Disabling Scripting 275
JSP Declarations 276
Initializing and Finalizing a JSP Page 276
Contents
9
JSP Scriptlets 277
JSP Expressions 277
Programming Tags That Accept Scripting Elements 278
TLD Elements 278
Tag Handlers 278
Tags with Bodies 280

Cooperating Tags 282
Tags That Dene Variables 284
10 JavaServer FacesTechnology 285
JavaServer Faces Technology User Interface 285
JavaServer Faces Technology Benets 286
What Is a JavaServer Faces Application? 287
A Simple JavaServer Faces Application 287
Steps in the Development Process 288
Mapping the FacesServlet Instance 289
Creating the Pages 290
Dening Page Navigation 296
Conguring Error Messages 297
Developing the Beans 298
Adding Managed Bean Declarations 298
User Interface Component Model 299
User Interface Component Classes 300
Component Rendering Model 301
Conversion Model 304
Event and Listener Model 305
Validation Model 307
Navigation Model 307
Backing Beans 309
Creating a Backing Bean Class 309
The Life Cycle of a JavaServer Faces Page 313
Restore View Phase 315
Further Information about JavaServer Faces Technology 318
Contents
The Java EE Tutorial • September 200710
11 Using JavaServer FacesTechnology in JSP Pages 319
The Example JavaServer Faces Application 319

Setting Up a Page 322
Using the Core Tags 325
Adding UI Components to a Page Using the HTML Component Tags 327
UI Component Tag Attributes 327
Adding a Form Component 329
Using Text Components 330
Using Command Components for Performing Actions and Navigation 335
Using Data-Bound Table Components 337
Adding Graphics and Images with the graphicImage Tag 340
Laying Out Components with the UIPanel Component 341
Rendering Components for Selecting One Value 343
Rendering Components for Selecting Multiple Values 345
The UISelectItem, UISelectItems, and UISelectItemGroup Components 346
Displaying Error Messages with the message and messages Tags 349
Using Localized Data 350
Loading a Resource Bundle 351
Referencing Localized Static Data 352
Referencing Error Messages 352
Using the Standard Converters 354
Converting a Component’s Value 355
Using DateTimeConverter 356
Using NumberConverter 357
Registering Listeners on Components 359
Registering a Value-Change Listener on a Component 359
Registering an Action Listener on a Component 360
Using the Standard Validators 361
Validating a Component’s Value 362
Using the LongRangeValidator 363
Binding Component Values and Instances to External Data Sources 364
Binding a Component Value to a Property 365

Binding a Component Value to an Implicit Object 366
Binding a Component Instance to a Bean Property 368
Binding Converters, Listeners, and Validators to Backing Bean Properties 369
Referencing a Backing Bean Method 370
Contents
11
Referencing a Method That Performs Navigation 371
Referencing a Method That Handles an Action Event 371
Referencing a Method That Performs Validation 372
Referencing a Method That Handles a Value-change Event 372
Using Custom Objects 373
Using a Custom Converter 374
Using a Custom Validator 375
Using a Custom Component 376
12 Developing with JavaServer FacesTechnology 379
Writing Bean Properties 379
Writing Properties Bound to Component Values 380
Writing Properties Bound to Component Instances 388
Writing Properties Bound to Converters, Listeners, or Validators 389
Performing Localization 390
Creating a Resource Bundle 390
Localizing Dynamic Data 390
Localizing Messages 391
Creating a Custom Converter 393
Implementing an Event Listener 395
Implementing Value-Change Listeners 396
Implementing Action Listeners 397
Creating a Custom Validator 398
Implementing the Validator Interface 399
Creating a Custom Tag 402

Writing Backing Bean Methods 404
Writing a Method to Handle Navigation 404
Writing a Method to Handle an Action Event 406
Writing a Method to Perform Validation 406
Writing a Method to Handle a Value-Change Event 407
13 Creating Custom UI Components 409
Determining Whether You Need a Custom Component or Renderer 410
When to Use a Custom Component 410
When to Use a Custom Renderer 411
Contents
The Java EE Tutorial • September 200712
Component, Renderer, and Tag Combinations 412
Understanding the Image Map Example 413
Why Use JavaServer Faces Technology to Implement an Image Map? 413
Understanding the Rendered HTML 413
Understanding the JSP Page 414
Conguring Model Data 416
Summary of the Application Classes 417
Steps for Creating a Custom Component 418
Creating Custom Component Classes 419
Specifying the Component Family 421
Performing Encoding 422
Performing Decoding 424
Enabling Component Properties to Accept Expressions 424
Saving and Restoring State 426
Delegating Rendering to a Renderer 427
Creating the Renderer Class 427
Identifying the Renderer Type 429
Handling Events for Custom Components 429
Creating the Component Tag Handler 430

Retrieving the Component Type 431
Setting Component Property Values 431
Providing the Renderer Type 433
Releasing Resources 434
Dening the Custom Component Tag in a Tag Library Descriptor 434
14 Conguring JavaServer Faces Applications 437
Application Conguration Resource File 437
Conguring Beans 439
Using the managed-bean Element 439
Initializing Properties Using the managed-property Element 441
Initializing Maps and Lists 447
Registering Custom Error Messages 448
Registering Custom Localized Static Text 449
Registering a Custom Validator 450
Registering a Custom Converter 451
Contents
13
Conguring Navigation Rules 451
Registering a Custom Renderer with a Render Kit 455
Registering a Custom Component 457
Basic Requirements of a JavaServer Faces Application 458
Conguring an Application with a Deployment Descriptor 459
Including the Required JAR Files 466
Including the Classes, Pages, and Other Resources 466
15 Internationalizing and Localizing Web Applications 467
Java Platform Localization Classes 467
Providing Localized Messages and Labels 468
Establishing the Locale 468
Setting the Resource Bundle 469
Retrieving Localized Messages 470

Date and Number Formatting 471
Character Sets and Encodings 472
Character Sets 472
Character Encoding 473
Further Information about Internationalizing Web Applications 475
Part III Web Services 477
16 Building Web Services with JAX-WS 479
Setting the Port 480
Creating a Simple Web Service and Client with JAX-WS 480
Requirements of a JAX-WS Endpoint 481
Coding the Service Endpoint Implementation Class 482
Building, Packaging, and Deploying the Service 482
Testing the Service without a Client 484
A Simple JAX-WS Client 484
Types Supported by JAX-WS 486
Web Services Interoperability and JAX-WS 487
Further Information about JAX-WS 487
Contents
The Java EE Tutorial • September 200714
17 Binding between XML Schema and Java Classes 489
JAXB Architecture 489
Architectural Overview 489
The JAXB Binding Process 490
More about Unmarshalling 492
More about Marshalling 492
More about Validation 492
Representing XML Content 492
Java Representation of XML Schema 492
Binding XML Schemas 493
Simple Type Denitions 493

Default Data Type Bindings 493
Customizing Generated Classes and Java Program Elements 495
Schema-to-Java 495
Java-to-Schema 496
JAXB Examples 501
JAXB Compiler Options 503
JAXB Schema Generator Option 505
About the Schema-to-Java Bindings 505
Schema-Derived JAXB Classes 508
Basic JAXB Examples 511
Modify Marshal Example 511
Unmarshal Validate Example 512
Customizing JAXB Bindings 514
Why Customize? 515
Customization Overview 515
Customize Inline Example 526
Datatype Converter Example 531
Binding Declaration Files 533
External Customize Example 536
Java-to-Schema Examples 536
Create Marshal Example 537
XmlAccessorOrder Example 538
XmlAdapter Field Example 540
XmlAttribute Field Example 543
XmlRootElement Example 544
Contents
15
XmlSchemaType Class Example 545
XmlType Example 546
Further Information about JAXB 548

18 Streaming API for XML 549
Why StAX? 549
Streaming versus DOM 549
Pull Parsing versus Push Parsing 550
StAX Use Cases 551
Comparing StAX to Other JAXP APIs 551
StAX API 552
Cursor API 553
Iterator API 553
Choosing between Cursor and Iterator APIs 557
Using StAX 559
StAX Factory Classes 559
Resources, Namespaces, and Errors 561
Reading XML Streams 561
Writing XML Streams 564
Sun’s Streaming XML Parser Implementation 566
Reporting CDATA Events 566
Streaming XML Parser Factories Implementation 566
Example Code 567
Example Code Organization 567
Example XML Document 568
Cursor Example 568
Cursor-to-Event Example 571
Event Example 573
Filter Example 575
Read-and-Write Example 578
Writer Example 580
Further Information about StAX 583
19 SOAP with Attachments API for Java 585
Overview of SAAJ 586

Contents
The Java EE Tutorial • September 200716
SAAJ Messages 586
SAAJ Connections 589
SAAJ Tutorial 590
Creating and Sending a Simple Message 591
Adding Content to the Header 598
Adding Content to the SOAPPart Object 599
Adding a Document to the SOAP Body 600
Manipulating Message Content Using SAAJ or DOM APIs 601
Adding Attachments 601
Adding Attributes 603
Using SOAP Faults 608
Code Examples 613
Request Example 613
Header Example 614
DOM and DOMSource Examples 617
Attachments Example 622
SOAP Fault Example 624
Further Information about SAAJ 627
Part IV Enterprise Beans 629
20 Enterprise Beans 631
What Is an Enterprise Bean? 631
Benets of Enterprise Beans 631
When to Use Enterprise Beans 632
Types of Enterprise Beans 632
What Is a Session Bean? 633
State Management Modes 633
When to Use Session Beans 634
What Is a Message-Driven Bean? 634

What Makes Message-Driven Beans Dierent from Session Beans? 635
When to Use Message-Driven Beans 636
Dening Client Access with Interfaces 636
Remote Clients 636
Local Clients 637
Contents
17
Deciding on Remote or Local Access 638
Web Service Clients 639
Method Parameters and Access 639
The Contents of an Enterprise Bean 640
Naming Conventions for Enterprise Beans 641
The Life Cycles of Enterprise Beans 641
The Life Cycle of a Stateful Session Bean 642
The Life Cycle of a Stateless Session Bean 642
The Life Cycle of a Message-Driven Bean 643
Further Information about Enterprise Beans 644
21 Getting Started with Enterprise Beans 645
Creating the Enterprise Bean 645
Coding the Enterprise Bean 646
Compiling and Packaging the converter Example 647
Creating the converter Application Client 648
Coding the converter Application Client 648
Compiling the converter Application Client 650
Creating the converter Web Client 650
Coding the converter Web Client 650
Compiling the converter Web Client 652
Deploying the converter Java EE Application 652
Deploying the converter Example Using NetBeans IDE 652
Deploying the converter Example Using Ant 652

Running the converter Application Client 653
Running the converter Application Client Using NetBeans IDE 653
Running the converter Application Client Using Ant 653
Running the converter Web Client 654
Modifying the Java EE Application 654
Modifying a Class File 654
22 Session Bean Examples 657
The cart Example 657
The Business Interface 658
Session Bean Class 658
Contents
The Java EE Tutorial • September 200718
The Remove Method 662
Helper Classes 662
Building, Packaging, Deploying, and Running the cart Example 662
Undeploying the cart Example 665
A Web Service Example: helloservice 665
The Web Service Endpoint Implementation Class 666
Stateless Session Bean Implementation Class 666
Building, Packaging, Deploying, and Testing the helloservice Example 667
Using the Timer Service 669
The Timeout Method 669
Creating Timers 669
Canceling and Saving Timers 670
Getting Timer Information 670
Transactions and Timers 670
The timersession Example 671
Building, Packaging, Deploying, and Running the timersession Example 672
Handling Exceptions 674
23 A Message-Driven Bean Example 675

simplemessage Example Application Overview 675
The simplemessage Application Client 676
The Message-Driven Bean Class 677
The onMessage Method 677
Packaging, Deploying, and Running the simplemessage Example 678
Creating the Administered Objects for the simplemessage Example 679
Building, Deploying, and Running the simplemessage Application Using NetBeans
IDE 679
Building, Deploying, and Running the simplemessage Application Using Ant 680
Removing the Administered Objects for the simplemessage Example 681
Creating Deployment Descriptors for Message-Driven Beans 682
Part V Persistence 683
24 Introduction to the Java Persistence API 685
Entities 685
Contents
19
Requirements for Entity Classes 685
Persistent Fields and Properties in Entity Classes 686
Primary Keys in Entities 688
Multiplicity in Entity Relationships 689
Direction in Entity Relationships 690
Entity Inheritance 691
Managing Entities 696
The Persistence Context 696
The EntityManager Interface 696
Persistence Units 701
25 Persistence in theWebTier 703
Accessing Databases from Web Applications 703
Dening the Persistence Unit 704
Creating an Entity Class 705

Obtaining Access to an Entity Manager 706
Accessing Data from the Database 708
Updating Data in the Database 708
26 Persistence in the EJB Tier 711
The order Application 711
Entity Relationships in the order Application 711
Primary Keys in the order Application 714
Entity Mapped to More Than One Database Table 717
Cascade Operations in the order Application 718
BLOB and CLOB Database Types in the order Application 718
Temporal Types in the order Application 719
Managing the order Application’s Entities 719
Building and Running the order Application 721
The roster Application 726
Relationships in the roster Application 726
Entity Inheritance in the roster Application 727
Automatic Table Generation in the roster Application 729
Building and Running the roster Application 729
Contents
The Java EE Tutorial • September 200720
27 The Java Persistence Query Language 733
Query Language Terminology 733
Simplied Query Language Syntax 734
Select Statements 734
Update and Delete Statements 734
Example Queries 735
Simple Queries 735
Queries That Navigate to Related Entities 736
Queries with Other Conditional Expressions 738
Bulk Updates and Deletes 740

Full Query Language Syntax 740
BNF Symbols 740
BNF Grammar of the Java Persistence Query Language 741
FROM Clause 745
Path Expressions 749
WHERE Clause 751
SELECT Clause 759
ORDER BY Clause 761
The GROUP BY Clause 762
Part VI Services 763
28 Introduction to Security in the Java EE Platform 765
Overview of Java EE Security 766
A Simple Security Example 766
Security Functions 769
Characteristics of Application Security 770
Security Implementation Mechanisms 771
Java SE Security Implementation Mechanisms 771
Java EE Security Implementation Mechanisms 772
Securing Containers 774
Using Deployment Descriptors for Declarative Security 774
Using Annotations 775
Using Programmatic Security 776
Securing the Application Server 777
Contents
21
Working with Realms, Users, Groups, and Roles 777
What Are Realms, Users, Groups, and Roles? 778
Managing Users and Groups on the Application Server 781
Setting Up Security Roles 782
Mapping Roles to Users and Groups 784

Establishing a Secure Connection Using SSL 785
Installing and Conguring SSL Support 785
Specifying a Secure Connection in Your Application Deployment Descriptor 786
Verifying SSL Support 787
Working with Digital Certicates 788
Enabling Mutual Authentication over SSL 793
Further Information about Security 795
29 Securing Java EE Applications 797
Securing Enterprise Beans 798
Accessing an Enterprise Bean Caller’s Security Context 799
Declaring Security Role Names Referenced from Enterprise Bean Code 801
Dening a Security View of Enterprise Beans 804
Using Enterprise Bean Security Annotations 815
Using Enterprise Bean Security Deployment Descriptor Elements 816
Conguring IOR Security 817
Deploying Secure Enterprise Beans 819
Enterprise Bean Example Applications 820
Example: Securing an Enterprise Bean 820
Example: Using the isCallerInRole and getCallerPrincipal Methods 826
Discussion: Securing the Duke’s Bank Example 831
Securing Application Clients 832
Using Login Modules 832
Using Programmatic Login 833
Securing EIS Applications 834
Container-Managed Sign-On 834
Component-Managed Sign-On 834
Conguring Resource Adapter Security 835
Mapping an Application Principal to EIS Principals 837
Contents
The Java EE Tutorial • September 200722

30 Securing Web Applications 839
Overview of Web Application Security 840
Working with Security Roles 841
Declaring Security Roles 841
Mapping Security Roles to Application Server Groups 844
Checking Caller Identity Programmatically 845
Declaring and Linking Role References 846
Dening Security Requirements for Web Applications 848
Declaring Security Requirements Using Annotations 849
Declaring Security Requirements in a Deployment Descriptor 851
Specifying a Secure Connection 857
Specifying an Authentication Mechanism 858
Examples: Securing Web Applications 867
Example: Using Form-Based Authentication with a JSP Page 868
Example: Basic Authentication with a Servlet 877
Example: Basic Authentication with JAX-WS 885
31 The Java Message Service API 893
Overview of the JMS API 893
What Is Messaging? 893
What Is the JMS API? 894
When Can You Use the JMS API? 894
How Does the JMS API Work with the Java EE Platform? 896
Basic JMS API Concepts 896
JMS API Architecture 897
Messaging Domains 898
Message Consumption 900
The JMS API Programming Model 900
JMS Administered Objects 901
JMS Connections 903
JMS Sessions 904

JMS Message Producers 904
JMS Message Consumers 905
JMS Messages 907
JMS Queue Browsers 909
Contents
23
JMS Exception Handling 910
Writing Simple JMS Client Applications 911
A Simple Example of Synchronous Message Receives 911
A Simple Example of Asynchronous Message Consumption 920
A Simple Example of Browsing Messages in a Queue 926
Running JMS Client Programs on Multiple Systems 931
Creating Robust JMS Applications 935
Using Basic Reliability Mechanisms 936
Using Advanced Reliability Mechanisms 942
Using the JMS API in a Java EE Application 954
Using @Resource Annotations in Java EE Components 954
Using Session Beans to Produce and to Synchronously Receive Messages 955
Using Message-Driven Beans to Receive Messages Asynchronously 956
Managing Distributed Transactions 958
Using the JMS API with Application Clients and Web Components 960
Further Information about JMS 961
32 Java EE Examples Using the JMS API 963
A Java EE Application That Uses the JMS API with a Session Bean 964
Writing the Application Components for the clientsessionmdb Example 964
Creating Resources for the clientsessionmdb Example 967
Building, Deploying, and Running the clientsessionmdb Example Using NetBeans
IDE 967
Building, Deploying, and Running the clientsessionmdb Example Using Ant 969
A Java EE Application That Uses the JMS API with an Entity 970

Overview of the clientmdbentity Example Application 970
Writing the Application Components for the clientmdbentity Example 972
Creating Resources for the clientmdbentity Example 974
Building, Deploying, and Running the clientmdbentity Example Using NetBeans
IDE 975
Building, Deploying, and Running the clientmdbentity Example Using Ant 977
An Application Example That Consumes Messages from a Remote Server 979
Overview of the consumeremote Example Modules 979
Writing the Module Components for the consumeremote Example 980
Creating Resources for the consumeremote Example 981
Using Two Application Servers for the consumeremote Example 981
Contents
The Java EE Tutorial • September 200724
Building, Deploying, and Running the consumeremoteModules Using NetBeans IDE 982
Building, Deploying, and Running the consumeremote Modules Using Ant 983
An Application Example That Deploys a Message-Driven Bean on Two Servers 985
Overview of the sendremote Example Modules 986
Writing the Module Components for the sendremote Example 987
Creating Resources for the sendremote Example 988
Using Two Application Servers for the sendremote Example 989
Building, Deploying, and Running the sendremote Modules Using NetBeans IDE 989
Building, Deploying, and Running the sendremote Modules Using Ant 992
33 Transactions 997
What Is a Transaction? 997
Container-Managed Transactions 998
Transaction Attributes 998
Rolling Back a Container-Managed Transaction 1002
Synchronizing a Session Bean’s Instance Variables 1002
Methods Not Allowed in Container-Managed Transactions 1003
Bean-Managed Transactions 1003

JTA Transactions 1004
Returning without Committing 1004
Methods Not Allowed in Bean-Managed Transactions 1005
Transaction Timeouts 1005
Updating Multiple Databases 1005
Transactions in Web Components 1007
34 Resource Connections 1009
Resources and JNDI Naming 1009
DataSource Objects and Connection Pools 1010
Resource Injection 1011
Field-Based Injection 1012
Method-Based Injection 1013
Class-Based Injection 1014
The confirmer Example Application 1014
Running the confirmer Example Application 1015
Further Information about Resources 1018
Contents
25

×