javaeetutorial

1300
The Java™ EE 5 Tutorial For Sun Java System Application Server Platform Edition 9 Jennifer Ball Debbie Carson Ian Evans Scott Fordin Kim Haase Eric Jendrock June 16, 2006

Upload: api-3828064

Post on 14-Nov-2014

10 views

Category:

Documents


2 download

TRANSCRIPT

The Java EE 5 TutorialFor Sun Java System Application Server Platform Edition 9

Jennifer Ball Debbie Carson Ian Evans Scott Fordin Kim Haase Eric Jendrock

June 16, 2006

Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.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. Sun, Sun Microsystems, the Sun logo, Java, JavaBeans, JavaServer, JavaServer Pages, Enterprise JavaBeans, Java Naming and Directory Interface, JavaMail, JDBC, EJB, JSP, J2EE, J2SE, Write Once, Run Anywhere, and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. Unless otherwise licensed, software code in all technical materials herein (including articles, FAQs, samples) is provided under this License. Products covered by and information contained in this service manual are controlled by U.S. Export Control laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities identified 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 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, tatsUnis. Tous droits rservs. Droits du gouvernement amricain, utlisateurs gouvernmentaux - logiciel commercial. Les utilisateurs gouvernmentaux sont soumis au contrat de licence standard de Sun Microsystems, Inc., ainsi qu aux dispositions en vigueur de la FAR [ (Federal Acquisition Regulations) et des supplments celles-ci. Cette distribution peut comprendre des composants dvelopps pardes tierces parties. Sun, Sun Microsystems, le logo Sun, Java, JavaBeans, JavaServer, JavaServer Pages, Enterprise JavaBeans, Java Naming and Directory Interface, JavaMail, JDBC, EJB, JSP, J2EE, J2SE, Write Once, Run Anywhere, et le logo Java Coffee Cup sont des marques de fabrique ou des marques dposes de Sun Microsystems, Inc. aux tats-Unis et dans dautres pays. A moins quautrement autoris, le code de logiciel en tous les matriaux techniques dans le prsent (articles y compris, FAQs, chantillons) est fourni sous ce permis. Les produits qui font lobjet de ce manuel dentretien et les informations quil contient sont rgis par la lgislation amricaine en matire de contrle des exportations et peuvent tre soumis au droit dautres pays dans le domaine des exportations et importations. Les utilisations finales, ou utilisateurs finaux, pour des armes nuclaires, des missiles, des armes biologiques et chimiques ou du nuclaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ou rexportations vers des pays sous embargo des tats-Unis, ou vers des entits figurant sur les listes dexclusion dexportation amricaines, y compris, mais de manire non exclusive, la liste de personnes qui font objet dun ordre de ne pas participer, dune faon directe ou indirecte, aux exportations des produits ou des services qui sont rgi par la lgislation amricaine en matire de contrle des exportations ("U .S. Commerce Departments Table of Denial Orders "et la liste de ressortissants spcifiquement dsigns ("U.S. Treasury Department of Specially Designated Nationals and Blocked Persons "),, sont rigoureusement interdites. LA DOCUMENTATION EST FOURNIE "EN LTAT" 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 LAPTITUDE A UNE UTILISATION PARTICULIERE OU A LABSENCE DE CONTREFAON.

ContentsAbout This Tutorial. . . . . . . . . . . . . . . . . . . . . . . . . xxviiWho Should Use This Tutorial Prerequisites How to Read This Tutorial About the Examples Further Information How to Print This Tutorial Typographical Conventions Feedback xxvii xxvii xxviii xxx xxxiv xxxiv xxxiv xxxv

Chapter 1:

Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Java EE Application Model Distributed Multitiered Applications Security Java EE Components Java EE Clients Web Components Business Components Enterprise Information System Tier Java EE Containers Container Services Container Types Web Services Support XML SOAP Transport Protocol WSDL Standard Format UDDI and ebXML Standard Formats Java EE Application Assembly and Deployment Packaging Applications 2 3 4 4 4 7 7 9 9 9 10 11 12 13 13 13 14 14 iii

iv

CONTENTS

Development Roles Java EE Product Provider Tool Provider Application Component Provider Application Assembler Application Deployer and Administrator Java EE 5 APIs Enterprise JavaBeans Technology Java Servlet Technology JavaServer Pages Technology JavaServer Pages Standard Tag Library JavaServer Faces Java Message Service API Java Transaction API JavaMail API JavaBeans Activation Framework Java API for XML Processing Java API for XML Web Services (JAX-WS) Java Architecture for XML Binding (JAXB) SOAP with Attachments API for Java Java API for XML Registries J2EE Connector Architecture Java Database Connectivity API Java Persistence API Java Naming and Directory Interface Java Authentication and Authorization Service Simplified Systems Integration Sun Java System Application Server Platform Edition 9 Tools Starting and Stopping the Application Server Starting the Admin Console Starting and Stopping the Java DB Database Server Debugging Java EE Applications

16 16 16 17 17 18 19 19 20 20 20 20 21 21 21 22 22 22 23 23 23 24 24 24 25 26 26 26 27 28 29 30 30

Part One: The Web Tier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33 Chapter 2: Getting Started with Web Applications. . . . . . . . . .35Web Application Life Cycle Web Modules Packaging Web Modules Deploying a WAR File 38 40 42 43

CONTENTS

v 44 44 45 47 48 48 49 50 50 51 54 54 55 55 56

Testing Deployed Web Modules Listing Deployed Web Modules Updating Web Modules Undeploying Web Modules Configuring Web Applications Mapping URLs to Web Components Declaring Welcome Files Setting Initialization Parameters Mapping Errors to Error Screens Declaring Resource References Dukes Bookstore Examples Accessing Databases from Web Applications Populating the Example Database Creating a Data Source in the Application Server Further Information

Chapter 3:

Java Servlet Technology . . . . . . . . . . . . . . . . . . . . . 57What Is a Servlet? The Example Servlets Troubleshooting Servlet Life Cycle Handling Servlet Life-Cycle Events Handling Errors Sharing Information Using Scope Objects Controlling Concurrent Access to Shared Resources Accessing Databases Initializing a Servlet Writing Service Methods Getting Information from Requests Constructing Responses Filtering Requests and Responses Programming Filters Programming Customized Requests and Responses Specifying Filter Mappings Invoking Other Web Resources Including Other Resources in the Response Transferring Control to Another Web Component Accessing the Web Context Maintaining Client State 57 58 60 61 61 64 64 64 65 67 68 69 70 72 75 75 77 80 82 82 84 85 86

vi

CONTENTS

Accessing a Session Associating Objects with a Session Session Management Session Tracking Finalizing a Servlet Tracking Service Requests Notifying Methods to Shut Down Creating Polite Long-Running Methods Further Information

86 86 87 88 89 89 90 91 92

Chapter 4:

JavaServer Pages Technology . . . . . . . . . . . . . . . .93What Is a JSP Page? Example The Example JSP Pages The Life Cycle of a JSP Page Translation and Compilation Execution Creating Static Content Response and Page Encoding Creating Dynamic Content Using Objects within JSP Pages Unified Expression Language Immediate and Deferred Evaluation Syntax Value and Method Expressions Defining a Tag Attribute Type Deactivating Expression Evaluation Literal Expressions Resolving Expressions Implicit Objects Operators Reserved Words Examples Functions JavaBeans Components JavaBeans Component Design Conventions Creating and Using a JavaBeans Component Setting JavaBeans Component Properties Retrieving JavaBeans Component Properties Using Custom Tags Declaring Tag Libraries 93 94 97 102 102 103 105 106 106 106 108 110 112 119 120 121 122 125 126 127 128 129 131 131 133 134 136 137 137

CONTENTS

vii 139 140 141 141 142 144 147

Including the Tag Library Implementation Reusing Content in JSP Pages Transferring Control to Another Web Component jsp:param Element Including an Applet Setting Properties for Groups of JSP Pages Further Information

Chapter 5:

JavaServer Pages Documents . . . . . . . . . . . . . . . 149The Example JSP Document Creating a JSP Document Declaring Tag Libraries Including Directives in a JSP Document Creating Static and Dynamic Content Using the jsp:root Element Using the jsp:output Element Identifying the JSP Document to the Container 150 152 154 156 158 161 162 166

Chapter 6:

JavaServer Pages Standard Tag Library . . . . . . . 167The Example JSP Pages Using JSTL Tag Collaboration Core Tag Library Variable Support Tags Flow Control Tags URL Tags Miscellaneous Tags XML Tag Library Core Tags Flow Control Tags Transformation Tags Internationalization Tag Library Setting the Locale Messaging Tags Formatting Tags SQL Tag Library query Tag Result Interface Functions Further Information 168 169 170 172 172 174 177 178 180 181 182 183 184 185 185 186 187 189 191 192

viii

CONTENTS

Chapter 7:

Custom Tags in JSP Pages . . . . . . . . . . . . . . . . . . .195What Is a Custom Tag? The Example JSP Pages Types of Tags Tags with Attributes Tags with Bodies Tags That Define Variables Communication between Tags Encapsulating Reusable Content Using Tag Files Tag File Location Tag File Directives Evaluating Fragments Passed to Tag Files Examples Tag Library Descriptors Top-Level Tag Library Descriptor Elements Declaring Tag Files Declaring Tag Handlers Declaring Tag Attributes for Tag Handlers Declaring Tag Variables for Tag Handlers Programming Simple Tag Handlers Including Tag Handlers in Web Applications How Is a Simple Tag Handler Invoked? Tag Handlers for Basic Tags Tag Handlers for Tags with Attributes Tag Handlers for Tags with Bodies Tag Handlers for Tags That Define Variables Cooperating Tags Examples 196 196 198 199 202 203 203 204 205 206 215 215 220 222 222 225 227 229 231 231 232 232 232 236 237 240 242

Chapter 8:

Scripting in JSP Pages . . . . . . . . . . . . . . . . . . . . . .251The Example JSP Pages Using Scripting Disabling Scripting Declarations Initializing and Finalizing a JSP Page Scriptlets Expressions Programming Tags That Accept Scripting Elements TLD Elements Tag Handlers 252 253 253 254 254 255 256 257 257 257

CONTENTS

ix 260 261 263

Tags with Bodies Cooperating Tags Tags That Define Variables

Chapter 9:

JavaServer Faces Technology . . . . . . . . . . . . . . . 265JavaServer Faces Technology Benefits What is a JavaServer Faces Application? A Simple JavaServer Faces Application Steps in the Development Process Mapping the FacesServlet Instance Creating the Pages Defining Page Navigation Configuring Error Messages Developing the Beans Adding Managed Bean Declarations User Interface Component Model User Interface Component Classes Component Rendering Model Conversion Model Event and Listener Model Validation Model Navigation Model Backing Beans The Life Cycle of a JavaServer Faces Page Further Information 266 268 268 269 270 271 278 279 279 280 281 282 284 289 290 291 292 295 300 306

Chapter 10: Using JavaServer Faces Technology in JSP Pages . . 307The Example JavaServer Faces Application 308 Setting Up a Page 310 Using the Core Tags 314 Adding UI Components to a Page Using the HTML Component Tags 316 UI Component Tag Attributes 317 Adding a Form Component 320 Using Text Components 321 Using Command Components for Performing Actions and Navigation 327 Using Data-Bound Table Components 329

x

CONTENTS

Adding Graphics and Images With the graphicImage Tag 333 Laying Out Components with the UIPanel Component 334 Rendering Components for Selecting One Value 337 Rendering Components for Selecting Multiple Values 339 The UISelectItem, UISelectItems, and UISelectItemGroup Components 340 Displaying Error Messages with the message and messages Tags 344 Using Localized Data 345 Loading a Resource Bundle 346 Referencing Localized Static Data 347 Referencing Error Messages 348 Using the Standard Converters 349 Converting a Components Value 351 Using DateTimeConverter 352 Using NumberConverter 354 Registering Listeners on Components 356 Registering a Value-Change Listener on a Component 356 Registering an Action Listener on a Component 357 Using the Standard Validators 359 Validating a Components Value 360 Using the LongRangeValidator 361 Binding Component Values and Instances to External Data Sources 361 Binding a Component Value to a Property 363 Binding a Component Value to an Implicit Object 365 Binding a Component Instance to a Bean Property 366 Binding Converters, Listeners, and Validators to Backing Bean Properties 367 Referencing a Backing Bean Method 369 Referencing a Method That Performs Navigation 370 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

Chapter 11: Developing with JavaServer Faces Technology .379Writing Bean Properties 380

CONTENTS

xi 381 390 391 392 393 393 394 396 398 399 400 401 403 406 409 409 411 412 413

Writing Properties Bound to Component Values Writing Properties Bound to Component Instances Writing Properties Bound to Converters, Listeners, or Validators Performing Localization Creating a Resource Bundle Localizing Dynamic Data Localizing Messages Creating a Custom Converter Implementing an Event Listener Implementing Value-Change Listeners Implementing Action Listeners Creating a Custom Validator Implementing the Validator Interface Creating a Custom Tag Writing Backing Bean Methods Writing a Method to Handle Navigation Writing a Method to Handle an Action Event Writing a Method to Perform Validation Writing a Method to Handle a Value-Change Event

Chapter 12: Creating Custom UI Components . . . . . . . . . . . . 415Determining Whether You Need a Custom Component or Renderer 416 When to Use a Custom Component 416 When to Use a Custom Renderer 417 Component, Renderer, and Tag Combinations 418 Understanding the Image Map Example 419 Why Use JavaServer Faces Technology to Implement an Image Map? 420 Understanding the Rendered HTML 420 Understanding the JSP Page 421 Configuring Model Data 423 Summary of the Application Classes 424 Steps for Creating a Custom Component 426 Creating Custom Component Classes 427 Specifying the Component Family 430 Performing Encoding 430 Performing Decoding 432 Enabling Component Properties to Accept Expressions 433 Saving and Restoring State 435

xii

CONTENTS

Delegating Rendering to a Renderer Creating the Renderer Class Identifying the Renderer Type Handling Events for Custom Components Creating the Component Tag Handler Retrieving the Component Type Setting Component Property Values Providing the Renderer Type Releasing Resources Defining the Custom Component Tag in a Tag Library Descriptor

436 437 438 439 440 441 441 444 445 445

Chapter 13: Configuring JavaServer Faces Applications . . . .449Application Configuration Resource File Configuring Beans Using the managed-bean Element Initializing Properties using the managed-property Element Initializing Maps and Lists Registering Custom Error Messages Registering Custom Localized Static Text Registering a Custom Validator Registering a Custom Converter Configuring Navigation Rules Registering a Custom Renderer with a Render Kit Registering a Custom Component Basic Requirements of a JavaServer Faces Application Configuring an Application with a Deployment Descriptor Including the Required JAR Files Including the Classes, Pages, and Other Resources 450 451 452 453 460 461 462 463 464 465 468 471 472 473 480 480

Chapter 14: Internationalizing and Localizing Web Applications . 483Java Platform Localization Classes Providing Localized Messages and Labels Establishing the Locale Setting the Resource Bundle Retrieving Localized Messages Date and Number Formatting Character Sets and Encodings Character Sets 483 484 485 486 487 488 489 489

CONTENTS

xiii 490 493

Character Encoding Further Information

Part Two: Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 Chapter 15: Building Web Services with JAX-WS . . . . . . . . . . . 497Setting the Port Creating a Simple Web Service and Client with JAX-WS Requirements of a JAX-WS Endpoint Coding the Service Endpoint Implementation Class Building and Packaging the Service Deploying the Service A Simple JAX-WS Client Types Supported by JAX-WS Web Services Interoperability and JAX-WS Further Information 498 498 500 500 501 501 503 505 505 505

Chapter 16: Binding between XML Schema and Java Classes . . 507JAXB Architecture Architectural Overview The JAXB Binding Process More About Unmarshalling More About Marshalling More About Validation Representing XML Content Java Representation of XML Schema Binding XML Schemas Simple Type Definitions Default Data Type Bindings Customizing JAXB Bindings Schema-to-Java Java-to-Schema Examples General Usage Instructions Description Using the Examples Configuring and Running the Samples JAXB Compiler Options JAXB Schema Generator Options 508 508 509 510 510 510 510 511 511 511 512 514 514 515 522 523 523 526 526 527 529

xiv

CONTENTS

About the Schema-to-Java Bindings Schema-Derived JAXB Classes Basic Examples Modify Marshal Example Unmarshal Validate Example Customizing JAXB Bindings Why Customize? Customization Overview Customize Inline Example Datatype Converter Example External Customize Example Java-toSchema Examples j2s-create-marshal Example j2s-xmlAccessorOrder Example j2s-xmlAdapter-field Example j2s-xmlAttribute-field Example j2s-xmlRootElement Example j2s-xmlSchemaType-class Example j2s-xmlType Example

530 533 540 540 542 543 544 545 558 563 564 568 568 568 571 574 575 575 576

Chapter 17: Streaming API for XML . . . . . . . . . . . . . . . . . . . . . .579Why StAX? Streaming Versus DOM Pull Parsing Versus Push Parsing StAX Use Cases Comparing StAX to Other JAXP APIs StAX API Cursor API Iterator API Choosing Between Cursor and Iterator APIs Using StAX StAX Factory Classes Resources, Namespaces, and Errors Reading XML Streams Writing XML Streams Suns Streaming Parser Implementation Reporting CDATA Events SJSXP Factories Implementation Sample Code Sample Code Organization 579 580 581 581 582 583 583 584 589 591 591 593 594 597 599 599 600 601 601

CONTENTS

xv 602 603 604 604 607 608 610 613 615 617

Configuring Your Environment for Running the Samples Running the Samples Sample XML Document cursor Sample CursorParse.java cursor2event Sample CursorApproachEventObject.java event Sample EventParse.java filter Sample MyStreamFilter.java readnwrite Sample EventProducerConsumer.java writer Sample CursorWriter.java Further Information

Chapter 18: SOAP with Attachments API for Java . . . . . . . . . . 619Overview of SAAJ Messages Connections Tutorial Creating and Sending a Simple Message Adding Content to the Header Adding Content to the SOAPPart Object Adding a Document to the SOAP Body Manipulating Message Content Using SAAJ or DOM APIs Adding Attachments Adding Attributes Using SOAP Faults Code Examples Request.java MyUddiPing.java HeaderExample.java DOMExample.java and DOMSrcExample.java Attachments.java SOAPFaultTest.java Further Information 620 620 624 625 626 635 636 638 638 639 641 647 653 654 655 662 664 668 670 672

Chapter 19: Java API for XML Registries . . . . . . . . . . . . . . . . . . 675Overview of JAXR What Is a Registry? What Is JAXR? JAXR Architecture Implementing a JAXR Client 675 675 676 677 678

xvi

CONTENTS

Establishing a Connection Querying a Registry Managing Registry Data Using Taxonomies in JAXR Clients Running the Client Examples Before You Compile the Examples Compiling the Examples Running the Examples Using JAXR Clients in Java EE Applications Coding the Application Client: MyAppClient.java Coding the PubQuery Session Bean Editing the Properties File Starting the Application Server Creating JAXR Resources Compiling the Source Files and Packaging the Application Deploying the Application Running the Application Client Further Information

679 685 690 698 703 704 705 706 711 711 712 712 712 713 714 714 714 715

Part Three: Enterprise Beans. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .717 Chapter 20: Enterprise Beans . . . . . . . . . . . . . . . . . . . . . . . . . . .719What Is an Enterprise Bean? Benefits of Enterprise Beans When to Use Enterprise Beans Types of Enterprise Beans What Is a Session Bean? State Management Modes When to Use Session Beans What Is a Message-Driven Bean? What Makes Message-Driven Beans Different from Session Beans? When to Use Message-Driven Beans Defining Client Access with Interfaces Remote Clients Local Clients Deciding on Remote or Local Access Web Service Clients Method Parameters and Access The Contents of an Enterprise Bean Naming Conventions for Enterprise Beans The Life Cycles of Enterprise Beans 719 719 720 721 721 721 722 723 723 725 725 726 726 727 728 728 729 730 731

CONTENTS

xvii 731 732 732 733

The Life Cycle of a Stateful Session Bean The Life Cycle of a Stateless Session Bean The Life Cycle of a Message-Driven Bean Further Information

Chapter 21: Getting Started with Enterprise Beans . . . . . . . . . 735Creating the Enterprise Bean Coding the Enterprise Bean Compiling and Packaging converter Creating the Application Client Coding the Application Client Compiling the Application Client Creating the Web Client Coding the Web Client Compiling the Web Client Deploying the Java EE Application Running the Application Client Running the Web Client Modifying the Java EE Application Modifying a Class File 736 736 737 738 739 740 741 741 742 743 743 743 744 744

Chapter 22: Session Bean Examples . . . . . . . . . . . . . . . . . . . . . 747The cart Example Session Bean Class The Remove Method Helper Classes Building and Packaging the CartBean Example Undeploying cart A Web Service Example: HelloServiceBean The Web Service Endpoint Implementation Class Stateless Session Bean Implementation Class Building and Packaging helloservice Deploying helloservice Using the Timer Service The Timeout Method Creating Timers Canceling and Saving Timers Getting Timer Information Transactions and Timers 747 749 752 753 753 754 754 755 756 756 757 757 758 758 759 759 760

xviii

CONTENTS

The timersession Example Building and Packaging timersession Deploying timersession Handling Exceptions

760 761 761 762

Chapter 23: A Message-Driven Bean Example . . . . . . . . . . . .765Example Application Overview The Application Client The Message-Driven Bean Class The onMessage Method Packaging, Deploying, and Running SimpleMessage Creating the Administered Objects Creating and Packaging the Application Deploying the Application Running the Client Removing the Administered Objects Creating Deployment Descriptors for Message-Driven Beans 765 766 767 768 769 769 770 770 771 771 772

Part Four: Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .773 Chapter 24: Introduction to the Java Persistence API . . . . . . .775Entities Requirements for Entity Classes Persistent Fields and Properties in Entity Classes Primary Keys in Entities Multiplicity in Entity Relationships Direction in Entity Relationships Managing Entities The Persistence Context The EntityManager Persistence Units 775 776 776 778 780 781 783 783 783 789

Chapter 25: Persistence in the Web Tier . . . . . . . . . . . . . . . . . .791Accessing Databases from Web Applications Populating the Example Database Creating a Data Source in the Application Server Defining the Persistence Unit Creating an Entity Class Obtaining Access to an Entity Manager 791 793 793 794 794 796

CONTENTS

xix 798 799

Accessing Data From the Database Updating Data in the Database

Chapter 26: Persistence in the EJB Tier . . . . . . . . . . . . . . . . . . . 801Overview of the order Application Entity Relationships in order Primary Keys in order Entity Mapped to More Than One Database Table Cascade Operations in order BLOB and CLOB Database Types in order Temporal Types in order Managing orders Entities Building and Running order Creating the Database Tables Building and Packaging the Application Deploying the Application Running the Application Undeploying order The roster Application Relationships in the roster Application Automatic Table Generation in roster Building and Running roster Building and Packaging the roster Application Deploying the Application Running the Application Undeploying order 801 802 804 808 809 809 810 811 814 814 814 814 815 816 816 817 818 818 819 819 819 820

Chapter 27: The Java Persistence Query Language . . . . . . . . 821Terminology Simplified Syntax Select Statements Update and Delete Statements Example Queries Simple Queries Queries That Navigate to Related Entities Queries with Other Conditional Expressions Bulk Updates and Deletes Full Syntax BNF Symbols 821 822 822 823 823 824 825 827 829 830 830

xx

CONTENTS

BNF Grammar of the Java Persistence Query Language FROM Clause Path Expressions WHERE Clause SELECT Clause ORDER BY Clause The GROUP BY Clause

831 836 840 841 852 855 855

Part Five: Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .857 Chapter 28: Introduction to Security in Java EE . . . . . . . . . . . .859Overview 860 A Simple Example 861 Security Functions 864 Characteristics of Application Security 865 Security Implementation Mechanisms 866 Java SE Security Implementation Mechanisms 866 Java EE Security Implementation Mechanisms 867 Securing Containers 870 Using Deployment Descriptors for Declarative Security 871 Using Annotations 872 Using Programmatic Security 873 Securing the Application Server 873 Working with Realms, Users, Groups, and Roles 875 What is a Realm, User, Group, and Role? 875 Managing Users and Groups on the Application Server 879 Setting Up Security Roles 880 Mapping Roles to Users and Groups 882 Establishing a Secure Connection Using SSL 883 Installing and Configuring SSL Support 884 Specifying a Secure Connection in Your Application Deployment Descriptor 884 Verifying SSL Support 885 Working with Digital Certificates 887 Enabling Mutual Authentication over SSL 892 Further Information 895

Chapter 29: Securing Java EE Applications . . . . . . . . . . . . . . .897Securing Enterprise Beans Accessing an Enterprise Bean Callers Security Context 898 900

CONTENTS

xxi

Declaring Security Role Names Referenced from Enterprise Bean Code 902 Defining a Security View of Enterprise Beans 905 Using Enterprise Bean Security Annotations 917 Using Enterprise Bean Security Deployment Descriptor Elements 918 Configuring IOR Security 919 Deploying Secure Enterprise Beans 922 Enterprise Bean Example Applications 923 Example: Securing an Enterprise Bean 923 Example: Using isCallerInRole and getCallerPrincipal 929 Discussion: Securing the Dukes Bank Example 935 Securing Application Clients 935 Using Login Modules 936 Using Programmatic Login 937 Securing EIS Applications 937 Container-Managed Sign-On 938 Component-Managed Sign-On 938 Configuring Resource Adapter Security 939 Mapping an Application Principal to EIS Principals 941 Example Applications in the Application Server 942 Further Information 942

Chapter 30: Securing Web Applications. . . . . . . . . . . . . . . . . . 945Overview Working with Security Roles Declaring Security Roles Mapping Security Roles to Application Server Groups Checking Caller Identity Programmatically Declaring and Linking Role References Defining Security Requirements for Web Applications Declaring Security Requirements Using Annotations Declaring Security Requirements in a Deployment Descriptor Specifying a Secure Connection Specifying an Authentication Mechanism Examples: Securing Web Applications Example: Using Form-Based Authentication with a JSP page Example: Basic Authentication with a Servlet Example: Basic Authentication with JAX-WS Further Information 946 947 948 951 952 954 956 957 959 966 968 976 978 988 997 1002

xxii

CONTENTS

Chapter 31: Securing Web Services . . . . . . . . . . . . . . . . . . . . .1005Securing Web Service Endpoints Overview of Message Security Advantages of Message Security Message Security Mechanisms Web Services Security Initiatives and Organizations W3C Specifications OASIS Specifications JCP Specifications WS-I Specifications Using Message Security with Java EE Using the Application Server Message Security Implementation Using the Java WSDP XWSS Security Implementation Further Information 1006 1006 1007 1009 1010 1010 1011 1012 1013 1015 1016 1021 1025

Chapter 32: The Java Message Service API . . . . . . . . . . . . . .1027Overview What Is Messaging? What Is the JMS API? When Can You Use the JMS API? How Does the JMS API Work with the Java EE Platform? Basic JMS API Concepts JMS API Architecture Messaging Domains Message Consumption The JMS API Programming Model Administered Objects Connections Sessions Message Producers Message Consumers Messages Queue Browsers Exception Handling Writing Simple JMS Client Applications A Simple Example of Synchronous Message Receives A Simple Example of Asynchronous Message Consumption A Simple Example of Browsing Messages in a Queue Running JMS Client Programs on Multiple Systems Creating Robust JMS Applications 1027 1028 1028 1029 1030 1031 1032 1033 1035 1035 1036 1038 1039 1040 1041 1043 1046 1047 1047 1048 1055 1059 1062 1067

CONTENTS

xxiii

Using Basic Reliability Mechanisms 1068 Using Advanced Reliability Mechanisms 1075 Using the JMS API in a Java EE Application 1086 Using @Resource Annotations in Java EE Components 1087 Using Session Beans to Produce and to Synchronously Receive Messages 1087 Using Message-Driven Beans 1088 Managing Distributed Transactions 1091 Using the JMS API with Application Clients and Web Components1093 Further Information 1094

Chapter 33: Java EE Examples Using the JMS API . . . . . . . . . 1095A Java EE Application That Uses the JMS API with a Session Bean 1096 Writing the Application Components 1096 Creating and Packaging the Application 1099 Deploying the Application 1100 Running the Application Client 1101 A Java EE Application That Uses the JMS API with an Entity 1101 Overview of the Human Resources Application 1102 Writing the Application Components 1104 Creating and Packaging the Application 1106 Deploying the Application 1107 Running the Application Client 1108 An Application Example That Consumes Messages from a Remote Java EE Server 1109 Overview of the Modules 1110 Writing the Components 1111 Creating and Packaging the Modules 1111 Deploying the EJB Module and Copying the Client 1113 Running the Application Client 1113 An Application Example That Deploys a Message-Driven Bean on Two Java EE Servers 1114 Overview of the Modules 1115 Writing the Module Components 1116 Creating and Packaging the Modules 1117 Deploying the Modules 1118 Running the Application Client 1119

xxiv

CONTENTS

Chapter 34: Transactions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1123What Is a Transaction? Container-Managed Transactions Transaction Attributes Rolling Back a Container-Managed Transaction Synchronizing a Session Beans Instance Variables Methods Not Allowed in Container-Managed Transactions Bean-Managed Transactions JTA Transactions Returning without Committing Methods Not Allowed in Bean-Managed Transactions Transaction Timeouts Updating Multiple Databases Transactions in Web Components 1123 1124 1125 1129 1130 1130 1131 1131 1132 1132 1132 1133 1135

Chapter 35: Resource Connections . . . . . . . . . . . . . . . . . . . . .1137Resources and JNDI Naming DataSource Objects and Connection Pools Resource Injection Field-Based Injection Method-Based Injection Class-Based Injection The confirmer Example Application Running the confirmer Example Application Further Information 1137 1139 1140 1141 1142 1143 1144 1145 1147

Chapter 36: Connector Architecture . . . . . . . . . . . . . . . . . . . .1149About Resource Adapters Resource Adapter Contracts Management Contracts Outbound Contracts Inbound Contracts Common Client Interface Further Information 1149 1151 1152 1153 1154 1155 1156

Part Six: Case Studies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1157 Chapter 37: The Coffee Break Application . . . . . . . . . . . . . . .1159Common Code 1160

CONTENTS

xxv 1160 1161 1162 1163 1171 1177 1178 1181 1183 1183 1184 1184 1185 1185 1186 1186 1186 1188

JAX-WS Coffee Supplier Service Service Implementation SAAJ Coffee Supplier Service SAAJ Client SAAJ Service Coffee Break Server JSP Pages JavaBeans Components RetailPriceListServlet Resource Configuration Building, Packaging, Deploying, and Running the Application Setting the Port Building the Common Classes Building, Packaging, and Deploying the JAX-WS Service Building, Packaging, and Deploying the SAAJ Service Building, Packaging, and Deploying the Coffee Break Server Running the Coffee Break Client Removing the Coffee Break Application

Chapter 38: The Dukes Bank Application . . . . . . . . . . . . . . . 1189Enterprise Beans Session Beans Java Persistence Entities Helper Classes Database Tables Protecting the Enterprise Beans Application Client The Classes and Their Relationships BankAdmin Class Web Client Design Strategies Client Components Request Processing Protecting the Web Client Resources Building, Packaging, Deploying, and Running the Application Setting Up the Servers Building the Dukes Bank Application Running the Clients Running the Application Client Running the Web Client 1190 1190 1193 1194 1194 1195 1196 1198 1198 1199 1201 1202 1205 1208 1209 1210 1211 1211 1211 1212

xxvi

CONTENTS

Appendix A: Java Encoding Schemes . . . . . . . . . . . . . . . . . . .1215Further Information 1216

About the Authors . . . . . . . . . . . . . . . . . . . . . . . . .1217Current Writers 1217

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1219

About This TutorialHE Java EE 5 Tutorial is a guide to developing enterprise applications for the Java Platform, Enterprise Edition 5 (Java EE 5). Here we cover all the things you need to know to make the best use of this tutorial.

T

Who Should Use This TutorialThis tutorial is intended for programmers who are interested in developing and deploying Java EE 5 applications on the Sun Java System Application Server Platform Edition 9.

PrerequisitesBefore 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 all the basic and some of the specialized trails in The Java Tutorial, Mary Campione et al., (Addison-Wesley, 2000). In particular, you should be familiar with relational database and security features described in the trails listed in Table 1.Table 1 Prerequisite Trails in The Java Tutorial Trail JDBC Security URLhttp://java.sun.com/docs/books/tutorial/jdbc http://java.sun.com/docs/books/tutorial/security1.2

xxvii

xxviii

How to Read This TutorialThe Java EE 5 platform is quite large, and this tutorial reflects this. However, you dont have to digest everything in it at once. The tutorial has been divided into parts to help you navigate the content more easily. This tutorial opens with an introductory chapter, which you should read before proceeding to any specific technology area. Chapter 1 covers the Java EE 5 platform architecture and APIs along with the Sun Java System Application Server Platform Edition 9. When you have digested the basics, you can delve into one or more of the five main technology areas listed next. Because there are dependencies between some of the chapters, Figure 1 contains a roadmap for navigating through the tutorial. The web-tier technology chapters cover the components used in developing the presentation layer of a Java EE 5 or stand-alone web application: Java Servlet JavaServer Pages (JSP) JavaServer Pages Standard Tag Library (JSTL) JavaServer Faces Web application internationalization and localization The web services technology chapters cover the APIs used in developing standard web services: The Java API for XML-based Web Services (JAX-WS) The Java API for XML Binding (JAXB) The Streaming API for XML (StAX) The SOAP with Attachments API for Java (SAAJ) The Java API for XML Registries (JAXR) The Enterprise JavaBeans (EJB) technology chapters cover the components used in developing the business logic of a Java EE 5 application: Session beans Message-driven beans The Persistence technology chapters cover the Java Persistence API, which is used for accessing databases from Java EE applications: Introduction to the Java Persistence API

xxix

Persistence in the Web Tier Persistence in the EJB Tier The Java Persistence Query Language The platform services chapters cover the system services used by all the Java EE 5 component technologies: Transactions Resource connections Security Java Message Service The Connector architecture

Figure 1 Roadmap to This Tutorial

After you have become familiar with some of the technology areas, you are ready to tackle the case studies, which tie together several of the technologies discussed in the tutorial. The Coffee Break Application (Chapter 37) describes an application that uses the web application and web services APIs. The Dukes Bank Application (Chapter 38) describes an application that employs web application technologies, enterprise beans, and the Java Persistence API.

xxx

Finally, the appendix contains auxiliary information helpful to the Java EE 5 application developer: Java encoding schemes (Appendix A)

About the ExamplesThis section tells you everything you need to know to install, build, and run the examples.

Required SoftwareThe following software is required to run the examples.

Tutorial BundleThe tutorial example source is contained in the tutorial bundle. If you are viewing this online, you need to click on the Download link at the top of any page. After you have installed the tutorial bundle, the example source code is in the /javaee5tutorial/examples/ directory, with subdirectories for each of the technologies discussed in the tutorial.

Application ServerThe Sun Java System Application Server Platform Edition 9 is targeted as the build and runtime environment for the tutorial examples. To build, deploy, and run the examples, you need a copy of the Application Server and Java 2 Platform, Standard Edition 5.0 (J2SE 5.0). If you already have a copy of the J2SE SDK, you can download the Application Server from:http://java.sun.com/javaee/downloads/index.html

You can also download the Java EE 5 SDKwhich contains the Application Server and the J2SE SDKfrom the same site.

xxxi

Application Server Installation TipsIn the Admin configuration pane of the Application Server installer, Select the Dont Prompt for Admin User Name radio button. This will save the user name and password so that you wont need to provide them when performing administrative operations with asadmin. You will still have to provide the user name and password to log in to the Admin Console. Note the HTTP port at which the server is installed. This tutorial assumes that you are accepting the default port of 8080. If 8080 is in use during installation and the installer chooses another port or if you decide to change it yourself, you will need to update the common build properties file (described in the next section) and the configuration files for some of the tutorial examples to reflect the correct port. In the Installation Options pane, check the Add Bin Directory to PATH checkbox so that Application Server scripts (asadmin, asant, wsimport, wsgen, xjc, and schemagen) override other installations.

Apache AntAnt is a Java technology-based build tool developed by the Apache Software Foundation (http://ant.apache.org), and is used to build, package, and deploy the tutorial examples. Ant is included with the Application Server. To use the ant command-line tool add /lib/ant/bin to your PATH environment variable.

Registry ServerYou need a registry server to run the examples discussed in Chapter 19. Instructions for obtaining and setting up a registry server are provided in Chapter 19.

Building the ExamplesThe tutorial examples are distributed with a configuration file for ant or asant, a portable build tool contained in the Application Server. This tool is an extension of the Ant tool developed by the Apache Software Foundation (http://ant.apache.org). The asant utility contains additional tasks that invoke the Application Server administration utility asadmin. Directions for building the examples are provided in each chapter. Either ant or asant may be used to build, package, and deploy the examples.

xxxii

Build properties common to all the examples are specified in the/javaeetutorial5/examples/bp-project/build.properties

file. This file must be created before you run the examples. Weve included a /javaeetutorial5/examples/bpsample file that you should rename to project/build.properties.sample /javaeetutorial5/examples/bp-project/build.properties and edit to reflect your environment. The tutorial examples use the Java BluePrints (http://java.sun.com/reference/blueprints/) build system and application layout structure. To run the ant scripts, you must set common build properties in the /javaeetutorial5/examples/bp-project/build.properties follows: Set the javaee.home property to the location of your Application Server installation. The build process uses the javaee.home property to include the libraries in /lib/ in the classpath. All examples that run on the Application Server include the Java EE library archive /lib/javaee.jarin the build classpath. Some examples use additional libraries in /lib/; the required libraries are enumerated in the individual technology chapters. refers to the directory where you have installed the Application Server.Note: On Windows, you must escape any backslashes in the javaee.home property with another backslash or use forward slashes as a path separator. So, if your Application Server installation is C:\Sun\AppServer, you must set javaee.home as follows:javaee.home = C:\\Sun\\AppServer

file as

orjavaee.home=C:/Sun/AppServer

Set the javaee.tutorial.home property to the location of your tutorial. This property is used for asant deployment and undeployment. For example, on UNIX:javaee.tutorial.home=/home/username/javaeetutorial5

On Windows:javaee.tutorial.home=C:/javaeetutorial5

xxxiii

Do not install the tutorial to a location with spaces in the path. If you did not use the default value (admin) for the admin user, set the admin.user property to the value you specified when you installed the Application Server. If you did not use port 8080, set the domain.resources.port property to the value specified when you installed the Application Server. Set the admin users password in/javaeetutorial5/examples/common/admin-password.txt to the value you specified when you installed the Application Server. The format of this file is AS_ADMIN_PASSWORD=password. For

example:AS_ADMIN_PASSWORD=mypassword

Tutorial Example Directory StructureTo facilitate iterative development and keep application source separate from compiled files the tutorial examples use the Java BluePrints application directory structure. Each application module has the following structure: build.xml: Ant build file src/java: Java source files for the module src/conf: configuration files for the module, with the exception of web applications web: JSP and HTML pages, style sheets, tag files, and images web/WEB-INF: configuration files for web applications nbproject: NetBeans project files Examples that have multiple application modules packaged into an enterprise application archive (or EAR) have submodule directories that use the following naming conventions: -app-client: Application clients -ejb: Enterprise bean JARs -war: web applications The Ant build files (build.xml) distributed with the examples contain targets to create a build subdirectory and to copy and compile files into that directory; a

xxxiv

subdirectory, which holds the packaged module file; and a client-jar directory, which holds the retrieved application client JAR.dist

Further InformationThis tutorial includes the basic information that you need to deploy applications on and administer the Application Server. See the Sun Java System Application Server Platform Edition 9 Developers Guide at http://docs.sun.com/doc/819-3659 for information about developer features of the Application Server. See the Sun Java System Application Server Platform Edition 9 Administration Guide at http://docs.sun.com/doc/819-3658 for information about administering the Application Server. For information about the Java DB database included with the Application Server see the Apache web site at http://db.apache.org/derby.

How to Print This TutorialTo print this tutorial, follow these steps: 1. Ensure that Adobe Acrobat Reader is installed on your system. 2. Open the PDF version of this book. 3. Click the printer icon in Adobe Acrobat Reader.

Typographical ConventionsTable 2 lists the typographical conventions used in this tutorial.Table 2 Typographical Conventions Font Styleitalic

UsesEmphasis, titles, first occurrence of terms

xxxv Table 2 Typographical Conventions Font Style UsesURLs, code examples, file names, path names, tool names, application names, programming language keywords, tag, interface, class, method, and field names, properties Variables in code, file paths, and URLs User-selected file path components

monospace

italic monospace

Menu selections indicated with the right-arrow character , for example, FirstSecond, should be interpreted as: select the First menu, then choose Second from the First submenu.

FeedbackTo send comments, broken link reports, errors, suggestions, and questions about this tutorial to the tutorial team, please use the feedback form athttp://java.sun.com/javaee/5/docs/tutorial/information/sendusmail.html.

xxxvi

1OverviewDevelopers today increasingly recognize the need for distributed, transactional, and portable applications that leverage the speed, security, and reliability of server-side technology. 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 5 platform is to provide developers a powerful set of APIs while reducing development time, reducing application complexity, and improving application performance. The Java EE 5 platform introduces a simplified programming model. With Java EE 5 technology, XML deployment descriptors are now 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 run-time. These annotations are generally used to embed in a program data that would otherwise be furnished in a deployment descriptor. With annotations, the specification information is put directly in your code next to the program element that it affects. In the Java EE platform, dependency injection can be applied to all resources that a component needs, effectively hiding the creation and lookup of resources from application code. Dependency injection can be used in 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.

1

2

OVERVIEW

The Java Persistence API is new to the Java EE 5 platform. The Java Persistence API provides an object/relational mapping for managing relational data in enterprise beans, web components, and application clients. It can also be used in Java SE applications, outside of the Java EE environment. This tutorial uses examples to describe the features and functionalities available in the Java EE 5 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. If you are new to Java EE enterprise application development, this chapter is a good place to start. 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.

Java EE Application ModelThe Java EE application model begins with the Java programming language and the Java virtual machine. The proven portability, security, and developer productivity they provide forms 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 enterprises 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 multi-tier applications that deliver the scalability, accessibility, and manageability needed by enterprise-level applications. This model partitions the work needed to implement a multi-tier service into two parts: the business and presentation logic to be implemented by the developer, and 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.

DISTRIBUTED MULTITIERED APPLICATIONS

3

Distributed Multitiered ApplicationsThe Java EE platform uses a distributed multitiered application model for enterprise applications. Application logic is divided into components according to function, and the various application components that make up a Java EE application are installed on different machines depending on the tier in the multitiered Java EE environment to which the application component belongs. Figure 11 shows two multitiered Java EE applications divided into the tiers described in the following list. The Java EE application parts shown in Figure 11 are presented in Java EE Components (page 4). 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 the three or four tiers shown in Figure 11, 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.

Figure 11 Multitiered Applications

4

OVERVIEW

SecurityWhile 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 application developers do not have to implement these mechanisms in their applications. The same application works in a variety of different security environments without changing the source code.

Java EE ComponentsJava 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. Enterprise JavaBeans (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 difference between Java EE components and standard Java classes is that Java EE components are assembled into a Java EE application, are verified to be well formed and in compliance with the Java EE specification, and are deployed to production, where they are run and managed by the Java EE server.

Java EE ClientsA Java EE client can be a web client or an application client.

JAVA EE CLIENTS

5

Web ClientsA web client consists of two parts: (1) 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, and (2) 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.

AppletsA web page received from the web tier can include an embedded applet. An applet is a small client application written in the Java programming language 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 in order 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.

Application ClientsAn 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. It typically has a graphical user interface (GUI) created from the Swing 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 5 servers, enabling the Java EE 5 platform to interoperate with legacy systems, clients, and non-Java languages.

6

OVERVIEW

The JavaBeans Component ArchitectureThe server and client tiers might also include components based on the JavaBeans component architecture (JavaBeans components) to manage the data flow between an application client or applet and components running on the Java EE server, or between 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 the 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.

Java EE Server CommunicationsFigure 12 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 JSP pages or servlets running in the web tier. Your Java EE application uses a thin browser-based client or thick application client. In deciding which one to use, you should be aware of the trade-offs between keeping functionality on the client and close to the user (thick client) and off-loading as much functionality as possible to the server (thin client). The more functionality you off-load to the server, the easier it is to distribute, deploy, and manage the application; however, keeping more functionality on the client can make for a better perceived user experience.

WEB COMPONENTS

7

Figure 12 Server Communication

Web ComponentsJava EE web components are either servlets or pages created using JSP technology (JSP pages) and/or JavaServer Faces technology. 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. As shown in Figure 13, 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.

Business ComponentsBusiness 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 the business tier. Figure 14 shows how an enterprise bean receives

8

OVERVIEW

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.

Figure 13 Web Tier and Java EE Applications

Figure 14 Business and EIS Tiers

ENTERPRISE INFORMATION SYSTEM TIER

9

Enterprise Information System TierThe 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.

Java EE ContainersNormally, 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 Java EE 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.

Container ServicesContainers are the interface between a component and the low-level platformspecific functionality that supports the component. Before a web, enterprise bean, or application client component can be executed, it 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 services such as security, transaction management, Java Naming and Directory

10

OVERVIEW

Interface (JNDI) 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, application components within the same Java EE 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 life cycles, database connection resource pooling, data persistence, and access to the Java EE platform APIs (see section Java EE 5 APIs, page 19).

Container TypesThe deployment process installs Java EE application components in the Java EE containers illustrated in Figure 15.

WEB SERVICES SUPPORT

11

Figure 15 Java EE Server and Containers

Java EE server The runtime portion of a Java EE product. A Java EE server provides EJB and web containers. Enterprise JavaBeans (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 JSP page and servlet 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 Java Plugin running on the client together.

Web Services SupportWeb 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,

12

OVERVIEW

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 do is pass parameter data to the method calls and process the data returned; or 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 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.

XMLXML is a cross-platform, extensible, text-based standard for representing data. When XML data is exchanged between parties, the parties are free to 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 stylesheets 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 stylesheets 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 to 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.

SOAP TRANSPORT PROTOCOL

13

SOAP Transport ProtocolClient 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 XMLbased protocol that follows the HTTP request-and-response model. The SOAP portion of a transported message handles the following: Defines an XML-based envelope to describe what is in the message and how to process the message Includes XML-based encoding rules to express instances of applicationdefined data types within the message Defines an XML-based convention for representing the request to the remote service and the resulting response

WSDL Standard FormatThe 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 stored in UDDI registries or published on the web (or both). The Sun Java System Application Server Platform Edition 8 provides a tool for generating the WSDL specification of a web service that uses remote procedure calls to communicate with clients.

UDDI and ebXML Standard FormatsOther XML-based standards, such as Universal Description, Discovery and Integration (UDDI) and ebXML, make it possible for businesses to publish information on the Internet about their products and web services, where the information can be readily and globally accessed by clients who want to do business.

14

OVERVIEW

Java EE Application Assembly and DeploymentA 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 (enterprise bean, JSP page, servlet, applet, etc.) 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 platforms deployment tool to specify location-specific information, such as a list of local users that can access it and the name of the local database. Once deployed on a local platform, the application is ready to run.

Packaging ApplicationsA Java EE application is delivered in an Enterprise Archive (EAR) file, a standard Java Archive (JAR) file with an .ear extension. Using EAR files and modules makes it possible to assemble a number of different Java EE applications using some of the same components. No extra coding is needed; it is only a matter of assembling (or packaging) various Java EE modules into Java EE EAR files. An EAR file (see Figure 16) contains Java EE modules and deployment descriptors. A deployment descriptor is an XML document with an .xml extension that describes the deployment settings of an application, a module, or a component. Because deployment descriptor information is declarative, it can be changed without the need to modify the source code. At runtime, the Java EE server reads the deployment descriptor and acts upon the application, module, or component accordingly. There are two types of deployment descriptors: Java EE and runtime. A Java EE deployment descriptor is defined by a Java EE specification and can be used to configure deployment settings on any Java EE-compliant implementation. A runtime deployment descriptor is used to configure Java EE implementation-specific parameters. For example, the Sun Java System Application Server Platform Edition 9 runtime deployment descriptor contains information such as the context root of a web application, the mapping of portable names of an applications

PACKAGING APPLICATIONS

15

resources to the servers resources, and Application Server implementation-specific parameters, such as caching directives. The Application Server runtime deployment descriptors are named sun-moduleType.xml and are located in the same directory as the Java EE deployment descriptor.

Figure 16 EAR File Structure

A Java EE module consists of one or more Java EE components for the same container type and one component deployment descriptor of that type. An enterprise bean module deployment descriptor, for example, declares transaction attributes and security authorizations for an enterprise bean. A Java EE module without an application deployment descriptor can be deployed as a stand-alone module. The four types of Java EE modules are as follows: EJB modules, which contain class files for enterprise beans and an EJB deployment descriptor. EJB modules are packaged as JAR files with a .jar extension. Web modules, which contain servlet class files, JSP files, supporting class files, GIF and HTML files, and a web application deployment descriptor. Web modules are packaged as JAR files with a .war (Web ARchive) extension. Application client modules, which contain class files and an application client deployment descriptor. Application client modules are packaged as JAR files with a .jar extension. Resource adapter modules, which contain all Java interfaces, classes, native libraries, and other documentation, along with the resource adapter deployment descriptor. Together, these implement the Connector architecture (see J2EE Connector Architecture, page 24) for a particular EIS.

16

OVERVIEW

Resource adapter modules are packaged as JAR files with an .rar (resource adapter archive) extension.

Development RolesReusable modules make it possible to divide the application development and deployment process into distinct roles so that different people or companies can perform different parts of the process. The first two roles involve purchasing and installing the Java EE product and tools. After software is purchased and installed, Java EE components can be developed by application component providers, assembled by application assemblers, and deployed by application deployers. In a large organization, each of these roles might be executed by different individuals or teams. This division of labor works because each of the earlier roles outputs a portable file that is the input for a subsequent role. For example, in the application component development phase, an enterprise bean software developer delivers EJB JAR files. In the application assembly role, another developer combines these EJB JAR files into a Java EE application and saves it in an EAR file. In the application deployment role, a system administrator at the customer site uses the EAR file to install the Java EE application into a Java EE server. The different roles are not always executed by different people. If you work for a small company, for example, or if you are prototyping a sample application, you might perform the tasks in every phase.

Java EE Product ProviderThe Java EE product provider is the company that designs and makes available for purchase the Java EE platform APIs, and other features defined in the Java EE specification. Product providers are typically application server vendors who implement the Java EE platform according to the Java EE 5 Platform specification.

Tool ProviderThe tool provider is the company or person who creates development, assembly, and packaging tools used by component providers, assemblers, and deployers.

APPLICATION COMPONENT PROVIDER

17

Application Component ProviderThe application component provider is the company or person who creates web components, enterprise beans, applets, or application clients for use in Java EE applications.

Enterprise Bean DeveloperAn enterprise bean developer performs the following tasks to deliver an EJB JAR file that contains the enterprise bean(s): Writes and compiles the source code Specifies the deployment descriptor Packages the .class files and deployment descriptor into the EJB JAR file

Web Component DeveloperA web component developer performs the following tasks to deliver a WAR file containing the web component(s): Writes and compiles servlet source code Writes JSP, JavaServer Faces, and HTML files Specifies the deployment descriptor Packages the .class, .jsp, and.html files and deployment descriptor into the WAR file

Application Client DeveloperAn application client developer performs the following tasks to deliver a JAR file containing the application client: Writes and compiles the source code Specifies the deployment descriptor for the client Packages the .class files and deployment descriptor into the JAR file

Application AssemblerThe application assembler is the company or person who receives application modules from component providers and assembles them into a Java EE

18

OVERVIEW

application EAR file. The assembler or deployer can edit the deployment descriptor directly or can use tools that correctly add XML tags according to interactive selections. A software developer performs the following tasks to deliver an EAR file containing the Java EE application: Assembles EJB JAR and WAR files created in the previous phases into a Java EE application (EAR) file Specifies the deployment descriptor for the Java EE application Verifies that the contents of the EAR file are well formed and comply with the Java EE specification

Application Deployer and AdministratorThe application deployer and administrator is the company or person who configures and deploys the Java EE application, administers the computing and networking infrastructure where Java EE applications run, and oversees the runtime environment. Duties include such things as setting transaction controls and security attributes and specifying connections to databases. During configuration, the deployer follows instructions supplied by the application component provider to resolve external dependencies, specify security settings, and assign transaction attributes. During installation, the deployer moves the application components to the server and generates the container-specific classes and interfaces. A deployer or system administrator performs the following tasks to install and configure a Java EE application: Adds the Java EE application (EAR) file created in the preceding phase to the Java EE server Configures the Java EE application for the operational environment by modifying the deployment descriptor of the Java EE application Verifies that the contents of the EAR file are well formed and comply with the Java EE specification Deploys (installs) the Java EE application EAR file into the Java EE server

JAVA EE 5 APIS

19

Java EE 5 APIsFigure 17 illustrates the availability of the Java EE 5 platform APIs in each Java EE container type. The following sections give a brief summary of the technologies required by the Java EE platform, and the APIs used in Java EE applications.

Figure 17 Java EE Platform APIs

Enterprise JavaBeans TechnologyAn Enterprise JavaBeans (EJB) component, or enterprise bean, is a body of code having 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. There are two kinds of enterprise beans: session beans and 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 messagedriven 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 Java EE 5, entity beans have been replaced by Java persistence API entities. An entity represents persistent data stored in one row of a database table. If the client terminates, or if the server shuts down, the persistence manager ensures that the entity data is saved.

20

OVERVIEW

Java Servlet TechnologyJava servlet technology lets you define HTTP-specific servlet classes. A servlet class extends the capabilities of servers that host applications that are 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.

JavaServer Pages TechnologyJavaServer 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, WML, and XML) and JSP elements, which determine how the page constructs dynamic content.

JavaServer Pages Standard Tag LibraryThe 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 employ 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 commonly used functions.

JavaServer FacesJavaServer 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 gener-

JAVA MESSAGE SERVICE API

21

ates 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

All this functionality is available via standard Java APIs and XML-based configuration files.

Java Message Service APIThe 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.

Java Transaction APIThe 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.

JavaMail APIJava 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, and a service provider interface. The Java EE plat-

22

OVERVIEW

form includes JavaMail with a service provider that allows application components to send Internet mail.

JavaBeans Activation FrameworkThe JavaBeans Activation Framework (JAF) is included because JavaMail uses it. 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.

Java API for XML ProcessingThe 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 independent 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 W3C schema. You can find information on the W3C schema at this URL: http://www.w3.org/XML/Schema.

Java API for XML Web Services (JAX-WS)The 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 Web Services for J2EE specification describes the deployment of JAX-WS-based services and clients. The EJB and servlet specifications also describe aspects of such deployment. It must be possible to deploy JAX-WS-based applications 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 java:comp/env namespace as

JAVA ARCHITECTURE FOR XML BINDING (JAXB)

23

their associated component. Custom serializers and deserializers, if supported, are treated in the same way as message handlers.

Java Architecture for XML Binding (JAXB)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, where it provides a standard data binding for web service messages. All Java EE application client containers, web containers, and EJB containers support the JAXB API.

SOAP with Attachments API for JavaThe SOAP with Attachments API for Java (SAAJ) is a low-level API on which JAX-WS and JAXR depend. SAAJ enables the production and consumption of messages that conform to the SOAP 1.1 specification and SOAP with Attachments note. Most developers do not use the SAAJ API, instead using the higherlevel JAX-WS API.

Java API for XML RegistriesThe Java API for XML Registries (JAXR) lets you access business and generalpurpose registries over the web. JAXR supports the ebXML Registry and Repository standards and the emerging UDDI specifications. By using JAXR, developers can learn a single API and gain access to both of these important registry technologies. Additionally, businesses can submit material to be shared and search for material that others have submitted. Standards groups have developed schemas for particular kinds of XML documents; two businesses might, for example, agree to use the schema for their industrys standard purchase order form. Because the schema is stored in a standard business registry, both parties can use JAXR to access it.

24

OVERVIEW

J2EE Connector ArchitectureThe J2EE 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, typically there is a different resource adapter for each type of database or enterprise information system. The J2EE Connector architecture also provides a performance-oriented, secure, scalable, and message-based transactional integration of Java EE-based web services with existing EISs that can be either synchronous or asynchronous. Existing applications and EISs integrated through the J2EE 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 J2EE Connector architecture are complementary technologies for enterprise application integration (EAI) and end-to-end business integration.

Java Database Connectivity APIThe 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, and a service provider interface to attach a JDBC driver to the Java EE platform.

Java Persistence APIThe Java Persistence API is a new all 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. Java Persistence consists of three areas: The Java Persistence API The query language

JAVA NAMING AND DIRECTORY INTERFACE

25

Object/relational mapping metadata

Java Naming and Directory InterfaceThe Java Naming and Directory Interface (JNDI) provides naming and directory functionality, enabling applications to access multiple naming and directory services, including existing naming and directory services such as LDAP