1266
The J2EE™ 1.4 Tutorial Eric Armstrong Jennifer Ball Stephanie Bodoff Debbie Carson Ian Evans Maydene Fisher Dale Green Kim Haase Eric Jendrock November 16, 2003

J2EE Tutorial

Embed Size (px)

Citation preview

The J2EE 1.4 TutorialEric Armstrong Jennifer Ball Stephanie Bodoff Debbie Carson Ian Evans Maydene Fisher Dale Green Kim Haase Eric Jendrock

November 16, 2003

Copyright 2003 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, J2EE, JavaServer Pages, Enterprise JavaBeans, Java Naming and Directory Interface, EJB, JSP, J2EE, J2SE 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 identied 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 2003 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, JavaServer Pages, Enterprise JavaBeans, Java Naming and Directory Interface, EJB, JSP, J2EE, J2SE 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 nales, ou utilisateurs naux, 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 gurant 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 spciquement 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 How to Read This Tutorial About the Examples Further Information How to Print This Tutorial Typographical Conventions xxvii xxvii xxix xxxi xxxii xxxii

Chapter 1:

Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Distributed Multitiered Applications J2EE Components J2EE Clients Web Components Business Components Enterprise Information System Tier J2EE Containers Container Services Container Types Packaging Web Services Support Extensible Markup Language HTTP-SOAP Transport Protocol WSDL Standard Format UDDI and ebXML Standard Formats Development Roles J2EE Product Provider Tool Provider Application Component Provider Application Assembler 2 3 4 6 6 8 8 8 10 11 12 12 13 13 14 14 14 15 15 16 iii

iv

CONTENTS

Application Deployer and Administrator J2EE APIs JDBC API Java Servlet Technology JavaServer Pages Technology Java Message Service Java Naming and Directory Interface Java Transaction API JavaMail API JavaBeans Activation Framework Java API for XML Processing Java API for XML Registries Java API for XML-Based RPC SOAP with Attachments API for Java J2EE Connector Architecture Java Authentication and Authorization Service Simplified Systems Integration

16 17 17 17 18 18 18 19 19 19 20 20 20 21 21 22 22

Chapter 2:

Understanding XML. . . . . . . . . . . . . . . . . . . . . . . . . .23Introduction to XML What Is XML? Why Is XML Important? How Can You Use XML? XML and Related Specs: Digesting the Alphabet Soup Basic Standards Schema Standards Linking and Presentation Standards Knowledge Standards Standards That Build on XML Summary Generating XML Data Writing a Simple XML File Defining the Root Element Writing Processing Instructions Introducing an Error Substituting and Inserting Text Creating a Document Type Definition Documents and Data Defining Attributes and Entities in the DTD Referencing Binary Entities 23 23 28 31 33 34 38 40 41 43 45 45 45 46 50 52 53 56 61 62 68

CONTENTS

v 70 74 75 78 79 79 81 83 83

Defining Parameter Entities and Conditional Sections Resolving A Naming Conflict Using Namespaces Designing an XML Data Structure Saving Yourself Some Work Attributes and Elements Normalizing Data Normalizing DTDs Summary

Chapter 3:

Getting Started with Web Applications . . . . . . . . . 85Web Application Life Cycle 86 J2EE 1.4 Application Server 88 Components 89 Setting Up To Build and Deploy Tutorial Examples 90 Starting and Stopping the J2EE Application Server 91 Starting the Admin Console 92 Starting the deploytool Utility 92 Web Modules 92 Packaging Web Modules 94 Deploying Web Modules 95 Setting the Context Root 96 Deploying an Unpackaged Web Module 96 Deploying a Packaged Web Module 97 Listing Deployed Web Modules 99 Updating Web Modules 99 Updating an Unpackaged Web Module 99 Updating a Packaged Web Module 100 Dynamic Reloading 101 Debugging Web Modules 102 Using the Server Log 102 Using a Debugger 103 Undeploying Web Modules 103 Conguring Web Modules 104 Mapping URLs to Web Components 104 Declaring Welcome Files 106 Setting Initialization Parameters 107 Specifying Error Mappings 107 Declaring References to Environment Entries, Resource Environment Entries, or Resources 108

vi

CONTENTS

Dukes Bookstore Examples 109 Accessing Databases from Web Applications 109 Starting the PointBase Database Server 110 Populating the Example Database 111 Defining a Data Source in the J2EE Server 112 Configuring the Web Application to Reference a Resource 112 Mapping the Web Application Resource Reference to a Data Source 113 Further Information 113

Chapter 4:

Java API for XML Processing . . . . . . . . . . . . . . . . .115The JAXP APIs An Overview of the Packages The Simple API for XML (SAX) APIs The SAX Packages The Document Object Model (DOM) APIs The DOM Packages The XML Stylesheet Language for Transformation (XSLT) APIs The XSLT Packages Compiling and Running the Programs Where Do You Go from Here? 115 116 117 120 120 122 123 124 124 124

Chapter 5:

Simple API for XML . . . . . . . . . . . . . . . . . . . . . . . . .127When to Use SAX Echoing an XML File with the SAX Parser Creating the Skeleton Importing Classes Setting up for I/O Implementing the ContentHandler Interface Setting up the Parser Writing the Output Spacing the Output Handling Content Events Compiling and Running the Program Checking the Output Identifying the Events Compressing the Output Inspecting the Output Documents and Data 128 129 129 130 130 131 132 133 134 134 139 140 141 143 146 147

CONTENTS

vii 147 148 150 151 151 159 159 160 161 162 162 164 165 166 166 166 167 168 168 168 169 172 174 175 176 177 178 178 184 184 185 186

Adding Additional Event Handlers Identifying the Documents Location Handling Processing Instructions Summary Handling Errors with the Nonvalidating Parser Displaying Special Characters and CDATA Handling Special Characters Handling Text with XML-Style Syntax Handling CDATA and Other Characters Parsing with a DTD DTDs Effect on the Nonvalidating Parser Tracking Ignorable Whitespace Cleanup Empty Elements, Revisited Echoing Entity References Echoing the External Entity Summarizing Entities Choosing your Parser Implementation Using the Validating Parser Configuring the Factory Validating with XML Schema Experimenting with Validation Errors Error Handling in the Validating Parser Parsing a Parameterized DTD DTD Warnings Handling Lexical Events How the LexicalHandler Works Working with a LexicalHandler Using the DTDHandler and EntityResolver The DTDHandler API The EntityResolver API Further Information

Chapter 6:

Document Object Model . . . . . . . . . . . . . . . . . . . 187When to Use DOM Documents Versus Data Mixed Content Model A Simpler Model Increasing the Complexity Choosing Your Model 188 188 189 190 191 193

viii

CONTENTS

Reading XML Data into a DOM Creating the Program Additional Information Looking Ahead Displaying a DOM Hierarchy Echoing Tree Nodes Convert DomEcho to a GUI App Create Adapters to Display the DOM in a JTree Finishing Up Examining the Structure of a DOM Displaying A Simple Tree Displaying a More Complex Tree Finishing Up Constructing a User-Friendly JTree from a DOM Compressing the Tree View Acting on Tree Selections Handling Modifications Finishing Up Creating and Manipulating a DOM Obtaining a DOM from the Factory Normalizing the DOM Other Operations Finishing Up Validating with XML Schema Overview of the Validation Process Configuring the DocumentBuilder Factory Validating with Multiple Namespaces Further Information

194 194 199 201 201 201 201 207 217 217 218 220 227 228 228 234 244 244 244 245 248 250 253 253 254 254 256 259

Chapter 7:

XML Stylesheet Language for Transformations. . .261Introducing XSLT and XPath The JAXP Transformation Packages How XPath Works XPATH Expressions The XSLT/XPath Data Model Templates and Contexts Basic XPath Addressing Basic XPath Expressions Combining Index Addresses Wildcards 261 262 263 263 264 265 265 266 267 267

CONTENTS

ix 268 269 269 270 273 274 274 276 278 279 280 281 281 283 285 292 294 295 295 297 298 299 303 305 308 312 317 317 319 320 320 323 324 327 327

Extended-Path Addressing XPath Data Types and Operators String-Value of an Element XPath Functions Summary Writing Out a DOM as an XML File Reading the XML Creating a Transformer Writing the XML Writing Out a Subtree of the DOM Summary Generating XML from an Arbitrary Data Structure Creating a Simple File Creating a Simple Parser Modifying the Parser to Generate SAX Events Using the Parser as a SAXSource Doing the Conversion Transforming XML Data with XSLT Defining a Simple Document Type Creating a Test Document Writing an XSLT Transform Processing the Basic Structure Elements Writing the Basic Program Trimming the Whitespace Processing the Remaining Structure Elements Process Inline (Content) Elements Printing the HTML What Else Can XSLT Do? Transforming from the Command Line with Xalan Concatenating Transformations with a Filter Chain Writing the Program Understanding How the Filter Chain Works Testing the Program Conclusion Further Information

Chapter 8:

Building Web Services With JAX-RPC . . . . . . . . . . 329Types Supported By JAX-RPC J2SE SDK Classes Primitives 330 330 331

x

CONTENTS

Arrays Value Types JavaBeans Components Setting the Port Creating a Web Service with JAX-RPC Coding the Service Endpoint Interface and Implementation Class Building the Service Packaging the Service Specifying the Endpoint Address Deploying the Service Creating Web Service Clients with JAX-RPC Static Stub Client Example Dynamic Proxy Client Example Dynamic Invocation Interface (DII) Client Example J2EE Application Client Example More JAX-RPC Client Examples Web Services Interoperability (WS-I) and JAX-RPC Further Information

331 331 332 332 333 334 335 336 338 338 339 339 342 345 349 353 353 353

Chapter 9:

SOAP with Attachments API for Java . . . . . . . . . .355Overview of SAAJ Messages Connections Tutorial Creating and Sending a Simple Message Adding Content to the Header Adding Content to the SOAP Body 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 356 356 360 361 362 370 371 372 374 374 375 377 383 388 388 390 397 398 402 404

CONTENTS

xi 405

Further Information

Chapter 10: Java API for XML Registries . . . . . . . . . . . . . . . . . . 407Overview of JAXR What Is a Registry? What Is JAXR? JAXR Architecture Implementing a JAXR Client 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 J2EE Applications Coding the Application Client: MyAppClient.java Coding the PubQuery Session Bean Compiling the Source Files Starting the J2EE Application Server Creating JAXR Resources Creating and Packaging the Application Deploying the Application Running the Application Client Further Information 407 407 408 409 411 412 417 422 430 435 437 439 440 445 446 446 447 447 447 448 451 452 452

Chapter 11: Java Servlet Technology . . . . . . . . . . . . . . . . . . . . 455What 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 455 456 460 461 461 464 464 464 465 467 468

xii

CONTENTS

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 Accessing a Session Associating Attributes 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

468 469 471 474 475 477 479 481 482 484 485 486 486 486 487 488 489 490 490 491 492

Chapter 12: JavaServer Pages Technology . . . . . . . . . . . . . . .493What 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 Expression Language Deactivating Expression Evaluation Using Expressions Variables Implicit Objects Literals Operators 493 494 497 505 505 506 508 509 509 510 511 512 512 513 514 515 516

CONTENTS

xiii 516 517 518 519 519 521 522 524 525 525 528 529 530 530 531 533 536

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 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 13: JavaServer Pages Documents . . . . . . . . . . . . . . . 537The 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 538 543 545 547 549 553 553 558

Chapter 14: JavaServer Pages Standard Tag Library . . . . . . . 559The Example JSP Pages Using JSTL Tag Collaboration Core Tags Variable Support Tags Flow Control Tags URL Tags Miscellaneous Tags XML Tags Core Tags 559 563 564 566 566 567 570 571 572 574

xiv

CONTENTS

Flow Control Tags Transformation Tags Internationalization Tags Setting the Locale Messaging Tags Formatting Tags SQL Tags query Tag Result Interface Functions Further Information

575 576 576 577 578 578 579 581 584 585

Chapter 15: Custom Tags in JSP Pages . . . . . . . . . . . . . . . . . . .587What 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 Declaring Tag Files Declaring Tag Handlers Declaring Tag Attributes for Tag Handlers Declaring Tag Variables for Tag Handlers Programming Simple Tag Handlers Basic Tags Tags with Attributes Tags with Bodies Tags That Define Variables Cooperating Tags Examples 588 588 593 593 596 597 597 598 600 601 609 610 614 616 619 621 622 624 625 626 628 629 632 634

Chapter 16: Scripting in JSP Pages . . . . . . . . . . . . . . . . . . . . . .643The Example JSP Pages 644

CONTENTS

xv 645 646 646 646 647 648 649 649 649 652 653 655

Using Scripting Disabling Scripting Declarations Initializing and Finalizing a JSP Page Scriptlets Expressions Programming Tags That Accept Scripting Elements TLD Elements Tag Handlers Tags with Bodies Cooperating Tags Tags That Define Variables

Chapter 17: Internationalizing and Localizing Web Applications 657Java Platform Localization Classes Providing Localized Messages and Labels Date and Number Formatting Character Sets and Encodings Character Sets Character Encoding Further Information 657 658 660 660 660 661 664

Chapter 18: Enterprise Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . 665What Is an Enterprise Bean? 665 Benefits of Enterprise Beans 665 When to Use Enterprise Beans 666 Types of Enterprise Beans 666 What Is a Session Bean? 667 State Management Modes 667 When to Use Session Beans 668 What Is an Entity Bean? 669 What Makes Entity Beans Different from Session Beans? 669 Container-Managed Persistence 670 When to Use Entity Beans 674 What Is a Message-Driven Bean? 674 What Makes Message-Driven Beans Different from Session and Entity Beans? 675 When to Use Message-Driven Beans 676

xvi

CONTENTS

Dening Client Access with Interfaces Remote Clients Local Clients Local Interfaces and Container-Managed Relationships 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 The Life Cycle of a Stateful Session Bean The Life Cycle of a Stateless Session Bean The Life Cycle of an Entity Bean The Life Cycle of a Message-Driven Bean

676 677 678 678 678 679 680 681 682 683 683 684 685 687

Chapter 19: Getting Started With Enterprise Beans. . . . . . . . . .689Creating the J2EE Application Creating the Enterprise Bean Coding the Enterprise Bean Compiling the Source Files Packaging the Enterprise Bean Creating the J2EE Application Client Coding the J2EE Application Client Compiling the Application Client Packaging the J2EE Application Client Specifying the Application Clients Enterprise Bean Reference Creating the Web Client Coding the Web Client Compiling the Web Client Packaging the Web Client Specifying the Web Clients Enterprise Bean Reference Mapping the Enterprise Bean References Specifying the Web Clients Context Root Deploying the J2EE Application Running the J2EE Application Client Running the Web Client Modifying the J2EE Application Modifying a Class File Adding a File Modifying a Deployment Setting 690 690 691 692 693 694 695 697 698 699 699 699 701 701 702 703 704 705 705 706 707 707 708 708

CONTENTS

xvii 708

Chapter 20: Session Bean Examples . . . . . . . . . . . . . . . . . . . . . 709The CartEJB Example Session Bean Class Home Interface Remote Interface Helper Classes Building the CartEJB Example Creating the Application Packaging the Enterprise Bean Packaging the Application Client A Web Service Example: HelloServiceEJB Web Service Endpoint Interface Stateless Session Bean Implementation Class Building HelloServiceEJB Building the Web Service Client Running the Web Service Client Other Enterprise Bean Features Accessing Environment Entries Comparing Enterprise Beans Passing an Enterprise Beans Object Reference Using the Timer Service Creating Timers Cancelling and Saving Timers Getting Timer Information Transactions and Timers The TimerSessionEJB Example Building TimerSessionEJB Handling Exceptions 709 710 714 716 716 716 717 717 718 721 721 721 722 725 726 726 726 728 728 729 730 730 731 731 732 733 738

Chapter 21: Bean-Managed Persistence Examples . . . . . . . . 741The SavingsAccountEJB Example Entity Bean Class Home Interface Remote Interface Running the SavingsAccountEJB Example Mapping Table Relationships for Bean-Managed Persistence One-to-One Relationships 741 742 753 755 756 757 758

xviii

CONTENTS

One-to-Many Relationships Many-to-Many Relationships Primary Keys for Bean-Managed Persistence The Primary Key Class Primary Keys in the Entity Bean Class Getting the Primary Key deploytool Tips for Entity Beans with Bean-Managed Persistence

761 770 773 773 774 775 776

Chapter 22: Container-Managed Persistence Examples . . . .777Overview of the RosterApp Application The PlayerEJB Code Entity Bean Class Local Home Interface Local Interface Method Invocations in RosterApp Creating a Player Adding a Player to a Team Removing a Player Dropping a Player from a Team Getting the Players of a Team Getting a Copy of a Teams Players Finding the Players by Position Getting the Sports of a Player Building and Running the RosterApp Example Creating the Database Tables Creating the JDBC Resource Capturing the Table Schema Building the Enterprise Beans Creating the Enterprise Application Packaging the Enterprise Beans Packaging the Enterprise Application Client Deploying the Enterprise Application Running the Client Application A Guided Tour of the RosterApp Settings RosterApp RosterClient RosterJAR TeamJAR Primary Keys for Container-Managed Persistence The Primary Key Class 777 778 779 784 785 785 786 787 788 789 790 792 794 795 797 797 797 797 798 798 799 808 809 810 810 811 812 812 813 819 820

CONTENTS

xix

deploytool Tips for Entity Beans with Container-Managed Persistence 822 Selecting the Persistent Fields and Abstract Schema Name 822 Defining EJB QL Queries for Finder and Select Methods 823 Defining Relationships 823 Creating the Database Tables at Deploy Time in deploytool 824

Chapter 23: A Message-Driven Bean Example . . . . . . . . . . . . 825Example Application Overview The J2EE Application Client The Message-Driven Bean Class The onMessage Method The ejbCreate and ejbRemove Methods Deploying and Running SimpleMessageApp Creating the Administered Objects Deploying the Application Running the Client Removing the Administered Objects deploytool Tips for Message-Driven Beans Specifying the Beans Type Setting the Message-Driven Beans Characteristics deploytool Tips for Components that Send Messages Setting the Resource References Setting the Message Destination References Setting the Message Destinations 825 826 827 827 829 829 829 830 831 831 831 832 832 833 834 834 835

Chapter 24: Enterprise JavaBeans Query Language837Terminology Simplied Syntax Example Queries Simple Finder Queries Finder Queries That Navigate to Related Beans Finder Queries with Other Conditional Expressions Select Queries Full Syntax BNF Symbols BNF Grammar of EJB QL FROM Clause 838 838 839 839 841 842 844 844 845 845 848

xx

CONTENTS

Path Expressions WHERE Clause SELECT Clause ORDER BY Clause EJB QL Restrictions

852 854 862 865 866

Chapter 25: Transactions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .867What Is a Transaction? Container-Managed Transactions Transaction Attributes Rolling Back a Container-Managed Transaction Synchronizing a Session Beans Instance Variables Compiling the BankEJB Example Packaging the BankEJB Example Methods Not Allowed in Container-Managed Transactions Bean-Managed Transactions JDBC Transactions Deploying and Running the WarehouseEJB Example Compiling the WarehouseEJB Example Packaging the WarehouseEJB Example JTA Transactions Deploying and Running the TellerEJB Example Compiling the TellerEJB Example Packaging the TellerEJB Example Returning without Committing Methods Not Allowed in Bean-Managed Transactions Summary of Transaction Options for Enterprise Beans Transaction Timeouts Isolation Levels Updating Multiple Databases Transactions in Web Components 867 868 868 872 874 875 875 879 879 880 881 881 881 885 886 886 887 890 891 891 892 892 893 895

Chapter 26: Resource Connections . . . . . . . . . . . . . . . . . . . . . .897JNDI Naming DataSource Objects and Connection Pools Database Connections Coding a Database Connection Defining a Data Source in the J2EE Application Server Specifying a Resource Reference 897 899 900 900 901 901

CONTENTS

xxi 903 904 905 907 908

Mail Session Connections Running the ConfirmerEJB Example URL Connections Running the HTMLReaderEJB Example Further Information

Chapter 27: Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 909Overview 909 Realms, Users, Groups, and Roles 910 Setting up Security Roles 912 Web-Tier Security 914 Protecting Web Resources 916 Specifying a Secure Connection 919 Using Login Authentication 920 Example: Using Form-Based Authentication 922 Using Programmatic Security in the Web Tier 931 Installing and Conguring SSL Support 932 Setting Up Digital Certificates 933 Configuring the SSL Connector 939 XML and Web Services Security 942 Transport-Level Security 942 Example: Basic Authentication with JAX-RPC 943 Example: Client-Certificate Authentication over HTTP/SSL with JAXRPC 950 EJB-Tier Security 959 Declaring Method Permissions 960 Configuring IOR Security 960 Using Programmatic Security in the EJB Tier 962 Unauthenticated User Name 962 Application Client-Tier Security 963 EIS-Tier Security 964 Container-Managed Sign-On 964 Component-Managed Sign-On 964 Configuring Resource Adapter Security 965 Propagating Security Identity 966 Configuring a Components Propagated Security Identity 967 Configuring Client Authentication 968 What is Java Authorization Contract for Containers? 968

xxii

CONTENTS

Chapter 28: J2EE Connector Architecture . . . . . . . . . . . . . . . . .969About Resource Adapters Resource Adapter Contracts Connector 1.5 Resource Adapters Common Client Interface 969 970 972 974

Chapter 29: The Java Message Service API . . . . . . . . . . . . . . .977Overview 977 What Is Messaging? 978 What Is the JMS API? 978 When Can You Use the JMS API? 979 How Does the JMS API Work with the J2EE Platform? 980 Basic JMS API Concepts 981 JMS API Architecture 982 Messaging Domains 982 Message Consumption 985 The JMS API Programming Model 986 Administered Objects 987 Connections 989 Sessions 989 Message Producers 990 Message Consumers 991 Messages 993 Exception Handling 997 Writing Simple JMS Client Applications 997 A Simple Example of Synchronous Message Receives 998 A Simple Example of Asynchronous Message Consumption 1006 Running JMS Client Programs on Multiple Systems 1011 Creating Robust JMS Applications 1014 Using Basic Reliability Mechanisms 1015 Using Advanced Reliability Mechanisms 1023 Using the JMS API in a J2EE Application 1035 Using Session and Entity Beans to Produce and to Synchronously Receive Messages 1036 Using Message-Driven Beans 1037 Managing Distributed Transactions 1040 Using the JMS API with Application Clients and Web Components 1043 Specifying Deployment Descriptors 1043 Further Information 1049

CONTENTS

xxiii

Chapter 30: J2EE Examples Using the JMS API . . . . . . . . . . . . 1051A J2EE Application that Uses the JMS API with a Session Bean 1052 Writing the Application Components 1053 Creating and Packaging the Application 1055 Deploying the Application 1059 Running the Application Client 1060 A J2EE Application that Uses the JMS API with an Entity Bean 1061 Overview of the Human Resources Application 1061 Writing the Application Components 1063 Creating and Packaging the Application 1065 Running the Application Client 1068 An Application Example that Consumes Messages from a Remote J2EE Server 1069 Overview of the Applications 1070 Writing the Application Components 1071 Creating and Packaging the Applications 1071 Deploying the Applications 1073 Running the Application Client 1074 An Application Example that Deploys a Message-Driven Bean on Two J2EE Servers 1075 Overview of the Applications 1076 Writing the Application Components 1077 Creating and Packaging the Applications 1078 Deploying the Applications 1081 Running the Application Client 1082

Chapter 31: The Coffee Break Application. . . . . . . . . . . . . . . 1085Common Code JAX-RPC Distributor Service Service Interface Service Implementation Publishing the Service in the Registry Deleting the Service From the Registry SAAJ Distributor Service SAAJ Client SAAJ Service Coffee Break Server JSP Pages JavaBeans Components RetailPriceListServlet 1087 1087 1087 1088 1089 1093 1095 1096 1104 1110 1111 1112 1114

xxiv

CONTENTS

Building, Packaging, Deploying, and Running the Application Setting Up the Registry Server Building the Common Classes Building, Packaging, and Deploying the JAX-RPC 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

1114 1115 1116 1116 1118 1119 1120 1122

Chapter 32: The Dukes Bank Application . . . . . . . . . . . . . . . .1123Enterprise Beans Session Beans Entity Beans Helper Classes Database Tables Protecting the Enterprise Beans Application Client The Classes and Their Relationships BankAdmin Class EventHandle Class DataModel Class Web Client Design Strategies Web Client Life Cycle Protecting the Web Resources Internationalization Building, Packaging, Deploying, and Running the Application Setting Up the Servers Compiling the Dukes Bank Application Code Packaging and Deploying the Dukes Bank Application Reviewing JNDI Names Running the Clients Running the J2EE Application Client Running the Web Client 1124 1125 1128 1129 1130 1131 1132 1133 1135 1136 1138 1140 1142 1143 1147 1148 1149 1150 1151 1151 1158 1160 1160 1161

Appendix A: Java Encoding Schemes . . . . . . . . . . . . . . . . . . .1163Further Information 1164

CONTENTS

xxv

Appendix B: HTTP Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . 1165HTTP Requests HTTP Responses 1166 1166

Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167 About the Authors . . . . . . . . . . . . . . . . . . . . . . . . 1201 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1203

xxvi

CONTENTS

About This TutorialTHIS tutorial is a beginners guide to developing enterprise applicationsJava 2 Platform, Enterprise Edition (J2EE) version 1.4. Here we cover all the things you need to know to make the best use of this tutorial.

Who Should Use This TutorialThis tutorial is intended for programmers interested in developing and deploying J2EE applications on the J2EE 1.4 Application Server Developer Release.

How to Read This TutorialThis tutorial is organized into six parts: Introduction The rst three chapters introduce basic J2EE concepts and technologies and we suggest that you read these rst in their entirety. Java XML technology These chapters cover the technologies for developing applications that process XML documents and provide Web services: The Java API for XML Processing (JAXP) The Java API for XML-based RPC (JAX-RPC) SOAP with Attachments API for Java (SAAJ) The Java API for XML Registries (JAXR)

xxvii

xxviii

Web technology These chapters cover the component technologies used in developing the presentation layer of a J2EE application or a standalone Web application. Java Servlets JavaServer Pages JavaServer Pages Standard Tag Library Enterprise JavaBeans technology These chapters cover the component technologies used in developing the business logic of a J2EE application. Session beans Entity beans Enterprise JavaBeans Query Language Platform Services These chapters cover the J2EE platform services used by all the J2EE component technologies. Security Transactions Resources Connectors Java Message Service

Case Studies The Coffee Break Application chapter describes an application that ties together the Web application and Web services APIs. The Dukes Bank Application chapter describes an application that uses Web application technologies and enterprise beans. Appendixes Java encoding schemes HTTP overview

ABOUT THE EXAMPLES

xxix

About the ExamplesPrerequisites for the ExamplesTo understand the examples you will need a good knowledge of the Java programming language, SQL, and relational database concepts. The topics in The JavaTutorial listed in Table 11 are particularly relevant:Table 11 Relevant Topics in The JavaTutorial Topic JDBC Threads JavaBeans Security Web Pagehttp://java.sun.com/docs/books/tutorial/jdbc http://java.sun.com/docs/books/tutorial/essential/threads http://java.sun.com/docs/books/tutorial/javabeans http://java.sun.com/docs/books/tutorial/security1.2

Building and Running the ExamplesThis section tells you everything you need to know to obtain, build, and run the examples.

Required SoftwareIf you are viewing this online, you need to download The J2EE 1.4 Tutorial from:http://java.sun.com/j2ee/1.4/download.html#tutorial

Once you have installed the tutorial bundle, the example source code is in the /j2eetutorial14/examples/ directory, with subdirectories for each of the technologies discussed in tutorial. This tutorial documents the J2EE 1.4 Application Server Developer Release. To build, deploy, and run the examples you need a copy of the J2EE 1.4 Application Server Developer Release and the Java 2 Software Development Kit, Standard

xxx

Edition (J2SE SDK) 1.4.2_01 or higher. You download the J2EE 1.4 Application Server from:http://java.sun.com/j2ee/1.4/download.html#sdk

and the J2SE 1.4 SDK fromhttp://java.sun.com/j2se/1.4/

Building the ExamplesMost of the tutorial examples are distributed with a conguration le for asant, a portable build tool contained in the J2EE 1.4 Application Server, that is an extension of the Ant tool developed by the Apache Software Foundation (http://www.apache.org). asant contains additional tasks that interact with the J2EE 1.4 Application Server adminstration utility asadmin. Directions for building the examples are provided in each chapter. In order to run the asant scripts, you must congure your environment and properties les as follows: Add /bin to the front of your path. Add /bin and /share/bin to the front of your path so that J2EE 1.4 Application Server scripts (asadmin, asant, deploytool, and wscompile) override other installations. Set the j2ee.home property in the le /j2eetutorial14/examples/common/build.properties to the location of your J2EE Application Server installation. The build process uses the j2ee.home property to include the J2EE library archive, /lib/j2ee.jar, in the classpath. If you wish to use an IDE or the javac compiler to build J2EE applications, you must add this JAR to your classpath.Note: On Windows, you must escape any backslashes in the j2ee.home property with another backslash or use forward slashes as a path separator. So, if your J2EE 1.4 Application Server installation is C:\Sun\AppServer, you must set j2ee.home as follows:j2ee.home = C:\\Sun\\AppServer

or

FURTHER INFORMATION

xxxi

j2ee.home=C:/Sun/AppServer

Tutorial Example Directory StructureTo facilitate iterative development and keep application source separate from compiled les, the source code for the tutorial examples is stored in the following structure under each application directory: build.xmlasant build le srcJava source of servlets and JavaBeans components, and tag libraries webJSP pages and HTML pages, tag les, images The asant build les (build.xml) distributed with the examples contain targets to create a build subdirectory and copy and compile les into that directory and perform administrative functions on the application server. Build properties and targets common to a particular technology are specied in the les/j2eetutorial14/examples/technology/common/build.propert ies and /j2eetutorial14/examples/technology/common/targets.xml.

Further InformationFor information on the tools distributed with the J2EE 1.4 Application Server, see the man pages at http://java.sun.com/j2ee/1.4/docs/relnotes/cliref/index.html. This tutorial includes the basic information that you need to deploy applications on and administer the J2EE 1.4 Application Server. Seehttp://java.sun.com/j2ee/1.4/docs/devguide/index.html

Guide at for information about various developer features of the J2EE 1.4 Application Server. See the J2EE 1.4 Application Server Administrators Guide at for infor-

the

J2EE

1.4

Application

Server

Developers

http://java.sun.com/j2ee/1.4/docs/adminguide/index.html

mation about administering the J2EE 1.4 Application Server.

xxxii

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 12 lists the typographical conventions used in this tutorial.Table 12 Typographical Conventions Font Styleitalic

UsesEmphasis, titles, rst occurrence of terms URLs, code examples, le names, path names, command names, programming language keywords, properties Variable names Variable path names, environment variables in paths

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.

1OverviewODAY, more and more developers want to write distributed transactional applications for the enterprise and leverage the speed, security, and reliability of server-side technology. If you are already working in this area, you know that in todays fast-moving and demanding world of e-commerce and information technology, enterprise applications have to be designed, built, and produced for less money, with greater speed, and with fewer resources than ever before.

T

To reduce costs and fast-track application design and development, Java 2 Platform, Enterprise Edition (J2EE) provides a component-based approach to the design, development, assembly, and deployment of enterprise applications. The J2EE platform offers a multitiered distributed application model, reusable components, a unied security model, exible transaction control, and Web services support through integrated data interchange on Extensible Markup Language (XML)-based open standards and protocols. Not only can you deliver innovative business solutions to market faster than ever, but your platform-independent J2EE component-based solutions are not tied to the products and application programming interfaces (APIs) of any one vendor. Vendors and customers enjoy the freedom to choose the products and components that best meet their business and technological requirements. This tutorial takes an examples-based approach to describing the features and functionalities available in J2EE version 1.4 for developing enterprise applications. Whether you are a new or an experienced developer, you should nd the examples and accompanying text a valuable and accessible knowledge base for creating your own solutions.1

2

OVERVIEW

If you are new to J2EE enterprise application development, this chapter is a good place to start. Here you will learn development basics, be introduced to the J2EE architecture and APIs, become acquainted with important terms and concepts, and nd out how to approach J2EE application programming, assembly, and deployment.

Distributed Multitiered ApplicationsThe J2EE platform uses a multitiered distributed application model for enterprise applications. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. Figure 11 shows two multitiered J2EE applications divided into the tiers described in the following list. The J2EE application parts shown in Figure 11 are presented in J2EE Components (page 3). Client-tier components run on the client machine. Web-tier components run on the J2EE server. Business-tier components run on the J2EE server. Enterprise information system (EIS)-tier software runs on the EIS server.

Although a J2EE application can consist of the three or four tiers shown in Figure 11, J2EE multitiered applications are generally considered to be threetiered applications because they are distributed over three different locations: client machines, the J2EE server machine, and the database or legacy machines at the back end. Three-tiered applications that run in this way extend the standard

J2EE COMPONENTS

3

two-tiered client and server model by placing a multithreaded application server between the client application and back-end storage.

Figure 11 Multitiered Applications

J2EE ComponentsJ2EE applications are made up of components. A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and les and that communicates with other components. The J2EE specication denes the following J2EE components: Application clients and applets are components that run on the client. Java Servlet 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. J2EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between J2EE components and standard Java classes is that J2EE components are assembled into a J2EE application, veried to be well formed and in compliance with the J2EE specication, and deployed to production, where they are run and managed by the J2EE server.

4

OVERVIEW

J2EE ClientsA J2EE client can be a Web client or an application client.

Web ClientsA Web client consists of two parts: dynamic Web pages containing various types of markup language (HTML, XML, and so on), which are generated by Web components running in the Web tier, and 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 do things like query databases, execute complex business rules, or connect to legacy applications. When you use a thin client, heavyweight operations like these are off-loaded to enterprise beans executing on the J2EE server where they can leverage the security, speed, services, and reliability of J2EE 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 le 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 les 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 ClientsA J2EE 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 Swing or Abstract Window Toolkit (AWT) APIs, but a command-line interface is certainly possible.

J2EE CLIENTS

5

Application clients directly access enterprise beans running in the business tier. However, if application requirements warrant it, a J2EE application client can open an HTTP connection to establish communication with a servlet running in the Web tier.

JavaBeans Component ArchitectureThe server and client tiers might also include components based on the JavaBeans component architecture (JavaBeans component) to manage the data ow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components are not considered J2EE components by the J2EE specication. JavaBeans components have instance variables and get and set methods for accessing the data in the instance variables. 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.

J2EE Server CommunicationsFigure 12 shows the various elements that can make up the client tier. The client communicates with the business tier running on the J2EE 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 J2EE 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 offloading 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

6

OVERVIEW

manage the application; however, keeping more functionality on the client can make for a better perceived user experience.

Figure 12 Server Communications

Web ComponentsJ2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. Static HTML pages and applets are bundled with Web components during application assembly, but are not considered Web components by the J2EE specication. Server-side utility classes can also be bundled with Web components and, like HTML pages, are not considered Web components. Like the client tier and as shown in Figure 13, the Web 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 nance, is handled by enterprise beans running in the business tier. Figure 14 shows how an enterprise bean receives

BUSINESS COMPONENTS

7

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 J2EE Applications

Figure 14 Business and EIS Tiers

There are three kinds of enterprise beans: session beans, entity beans, and message-driven beans. A session bean represents a transient conversation with a client. When the client nishes executing, the session bean and its data are gone. In contrast, an entity bean represents persistent data stored in one row of a database

8

OVERVIEW

table. If the client terminates or if the server shuts down, the underlying services ensure that the entity bean data is saved. A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS messages asynchronously.

Enterprise Information System TierThe enterprise information system tier handles enterprise information system software and includes enterprise infrastructure systems such as enterprise resource planning (ERP), mainframe transaction processing, database systems, and other legacy information systems. J2EE application components might need access to enterprise information systems for database connectivity, for example.

J2EE 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 J2EE architecture makes J2EE applications easy to write because business logic is organized into reusable components. In addition, the J2EE 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 platformspecic functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container. The assembly process involves specifying container settings for each component in the J2EE application and for the J2EE application itself. Container settings customize the underlying support provided by the J2EE server, which includes services such as security, transaction management, Java Naming and Directory

CONTAINER SERVICES

9

Interface (JNDI) lookups, and remote connectivity. Here are some of the highlights: The J2EE security model lets you congure a Web component or enterprise bean so that system resources are accessed only by authorized users. The J2EE 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 unied interface to multiple naming and directory services in the enterprise so that application components can access naming and directory services. The J2EE 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. The fact that the J2EE architecture provides congurable services means that application components within the same J2EE 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 non-congurable services such as enterprise bean and servlet life cycles, database connection resource pooling, data persistence, and access to the J2EE platform APIs described in the section J2EE APIs (page 17). Although data persistence is a non-congurable service, the J2EE architecture lets you override container-managed persistence by including the appropriate code in your enterprise bean implementation when you want more control than the default container-managed persistence provides. For example, you might use bean-managed persistence to implement your own nder (search) methods or to create a customized database cache.

10

OVERVIEW

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

Figure 15 J2EE Server and Containers

J2EE server The runtime portion of a J2EE product. A J2EE server provides EJB and Web containers. Enterprise JavaBeans (EJB) container Manages the execution of enterprise beans for J2EE applications. Enterprise beans and their container run on the J2EE server. Web container Manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE 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.

PACKAGING

11

PackagingA J2EE application is delivered in an Enterprise Archive (EAR) le. An EAR le is a standard Java Archive (JAR) le with an .ear extension. The EAR le contains J2EE modules. Using EAR les and modules makes it possible to assemble a number of different J2EE applications using some of the same components. No extra coding is needed; it is just a matter of assembling various J2EE modules into J2EE EAR les. A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type. A deployment descriptor is an XML document with an .xml extension that describes a components deployment settings. An enterprise bean module deployment descriptor, for example, declares transaction attributes and security authorizations for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly. A J2EE module without an application deployment descriptor can be deployed as a stand-alone module. The four types of J2EE modules are: Enterprise JavaBeans modules contain class les for enterprise beans and an EJB deployment descriptor. EJB modules are packaged as JAR les with a .jar extension. Web modules contain JSP les, class les for servlets, GIF and HTML les, and a Web deployment descriptor. Web modules are packaged as JAR les with a .war (Web ARchive) extension. Resource adapter modules 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 21) for a particular EIS. Resource adapter modules are packages as JAR les with a .rar (Resource adapter ARchive) extension. Application client modules contain class les and an application client deployment descriptor. Application client modules are packaged as JAR les with a .jar extension.

12

OVERVIEW

Web Services SupportWeb services are Web-based enterprise applications that use open, Extensible Markup Language (XML)-based standards and transport protocols to exchange data with calling clients. The J2EE platform provides the XML APIs and tools you need to quickly design, develop, test, and deploy Web services and clients that fully interoperate with other Web services and clients running on Java-based or non-Java-based platforms. It is easy to write Web services and clients with the J2EE XML APIs. All you do is pass parameter data to the method calls and process the data returned, or for document-oriented web services, 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 next sections. The translation of data to a standardized XML-based data stream is what makes Web services and clients written with the J2EE XML APIs fully interoperable. This does not necessarily mean 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 les, CAD documents or the like. The next section, introduces XML and explains how parties doing business can use XML tags and schemas to exchange data in a meaningful way.

Extensible Markup LanguageExtensible Markup Language is a cross-platform, extensible, and 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 style sheets to manage the display and handling of the data.

HTTP-SOAP TRANSPORT PROTOCOL

13

For example, a Web service can use XML and a schema to produce price lists, and companies that receive the price lists and schema can have their own style sheets to handle the data in a way that best suits their needs. One company might put the XML pricing information through a program to translate the XML to HTML so 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.

HTTP-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: Denes 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 applicationdened data types within the message. Denes 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 how to communicate with the service. WSDLs can be stored in UDDI registries and/or published on the Web. The J2EE platform provides a tool for generating the WSDL for a Web service that uses remote procedure calls to communicate with clients.

14

OVERVIEW

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.

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 rst two roles involve purchasing and installing the J2EE product and tools. Once software is purchased and installed, J2EE 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 le that is the input for a subsequent role. For example, in the application component development phase, an enterprise bean software developer delivers EJB JAR les. In the application assembly role, another developer combines these EJB JAR les into a J2EE application and saves it in an EAR le. In the application deployment role, a system administrator at the customer site uses the EAR le to install the J2EE application into a J2EE 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.

J2EE Product ProviderThe J2EE product provider is the company that designs and makes available for purchase the J2EE platform, APIs, and other features dened in the J2EE specication. Product providers are typically operating system, database system, application server, or Web server vendors who implement the J2EE platform according to the Java 2 Platform, Enterprise Edition Specication.

TOOL PROVIDER

15

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 ProviderThe application component provider is the company or person who creates Web components, enterprise beans, applets, or application clients for use in J2EE applications.

Enterprise Bean DeveloperAn enterprise bean developer performs the following tasks to deliver an EJB JAR le that contains the enterprise bean: Writes and compiles the source code Species the deployment descriptor Bundles the .class les and deployment descriptor into an EJB JAR le

Web Component DeveloperA Web component developer performs the following tasks to deliver a WAR le containing the Web component: Writes and compiles servlet source code Writes JSP and HTML les Species the deployment descriptor for the Web component Bundles the .class, .jsp, .html, and deployment descriptor les in the WAR le

J2EE Application Client DeveloperAn application client developer performs the following tasks to deliver a JAR le containing the J2EE application client: Writes and compiles the source code Species the deployment descriptor for the client Bundles the .class les and deployment descriptor into the JAR le

16

OVERVIEW

Application AssemblerThe application assembler is the company or person who receives application component JAR les from component providers and assembles them into a J2EE application EAR le. The assembler or deployer can edit the deployment descriptor directly or use tools that correctly add XML tags according to interactive selections. A software developer performs the following tasks to deliver an EAR le containing the J2EE application: Assembles EJB JAR and WAR les created in the previous phases into a J2EE application (EAR) le Species the deployment descriptor for the J2EE application Veries that the contents of the EAR le are well formed and comply with the J2EE specication

Application Deployer and AdministratorThe application deployer and administrator is the company or person who congures and deploys the J2EE application, administers the computing and networking infrastructure where J2EE applications run, and oversees the runtime environment. Duties include such things as setting transaction controls and security attributes and specifying connections to databases. During conguration, 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-specic classes and interfaces. A deployer/system administrator performs the following tasks to install and congure a J2EE application: Adds the J2EE application (EAR) le created in the preceding phase to the J2EE server Congures the J2EE application for the operational environment by modifying the deployment descriptor of the J2EE application Veries that the contents of the EAR le are well formed and comply with the J2EE specication Deploys (installs) the J2EE application EAR le into the J2EE server

J2EE APIS

17

J2EE APIsEnterprise JavaBeans TechnologyAn Enterprise JavaBeans (EJB) component or enterprise bean is a body of code with elds 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 J2EE server. There are three kinds of enterprise beans: session beans, entity beans, and message-driven beans. Enterprise beans often interact with databases. One of the benets of entity beans is that you do not have to write any SQL code or use the JDBC API directly to perform database access operations; the EJB container handles this for you. However, if you override the default container-managed persistence for any reason, you will need to use the JDBC API. Also, if you choose to have a session bean access the database, you have to use the JDBC API.

JDBC APIThe JDBC API lets you invoke SQL commands from Java programing language methods. You use the JDBC API in an enterprise bean when you override the default container-managed persistence or have a session bean access the database. With container-managed persistence, database access operations are handled by the container, and your enterprise bean implementation contains no JDBC code or SQL commands. You can also use the JDBC API from a servlet or 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 J2EE platform.

Java Servlet TechnologyJava Servlet technology lets you dene HTTP-specic servlet classes. A servlet class extends the capabilities of servers that host applications accessed by way of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers.

18

OVERVIEW

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 template 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.

Java Message ServiceThe Java Message Service (JMS) is a messaging standard that allows J2EE application components to create, send, receive, and read messages. It enables distributed communication that is loosely coupled, reliable, and asynchronous.

Java Naming and Directory InterfaceThe Java Naming and Directory Interface (JNDI) provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. J2EE naming services provide application clients, enterprise beans, and Web components with access to a JNDI naming environment. A naming environment allows a component to be customized without the need to access or change the component's source code. A container implements the components environment and provides it to the component as a JNDI naming context. A J2EE component locates its environment naming context using JNDI interfaces. A component creates a javax.naming.InitialContext object and looks up the environment naming context in InitialContext under the name java:comp/env. A components naming environment is stored directly in the environment naming context or in any of its direct or indirect subcontexts. A J2EE component can access named system-provided and user-dened objects. The names of system-provided objects, such as JTA UserTransaction objects, are stored in the environment naming context, java:comp/env. The J2EE platform allows a component to name user-dened objects, such as enterprise beans, environment entries, JDBC DataSource objects, and message connections. An object should be named within a subcontext of the naming environment accord-

JAVA TRANSACTION API

19

ing to the type of the object. For example, enterprise beans are named within the subcontext java:comp/env/ejb and JDBC DataSource references in the subcontext java:comp/env/jdbc. Because JNDI is independent of any specic implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS. This allows J2EE applications to coexist with legacy applications and systems. For more information on JNDI, see the online JNDI Tutorial:http://java.sun.com/products/jndi/tutorial/index.html

Java Transaction APIThe Java Transaction API (JTA) provides a standard interface for demarcating transactions. The J2EE architecture provides a default auto commit to handle transaction commits and rollbacks. An auto commit means that any other applications 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 APIJ2EE applications can use the JavaMail API to send e-mail notications. The JavaMail API has two parts: an application-level interface used by the application components to send mail, and a service provider interface. The J2EE platform 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. It 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.

20

OVERVIEW

Java API for XML ProcessingThe Java API for XML Processing (JAXP) supports the processing of XML documents using Document Object Model (DOM), Simple API for XML Parsing (SAX), and XML Stylesheet Language Transformation (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 conicts. Designed to be exible, JAXP lets you use any XML-compliant parser of XSL processor from within your application and supports the W3C schema. You can nd information on the W3C schema at this URL: http://www.w3.org/XML/Schema.

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/Repository standards and the emerging UDDI specications. By using JAXR, developers can learn a single API and get access to both of these important registry technologies. Additionally, businesses submit material to be shared and search for material that others have submitted. Standards groups have developed schemas for particular kinds of XML documents, and 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.

Java API for XML-Based RPCThe Java API for XML-based RPC (JAX-RPC) uses the SOAP standard and HTTP so client programs can make XML-based remote procedure calls (RPCs) over the Internet. JAX-RPC also supports WSDL so you can import and export WSDL documents. With JAX-RPC and a WSDL, you can easily interoperate with clients and services running on Java-based or non-Java-based platforms such as .NET. For example, based on the WSDL document, a Visual Basic .NET client can be congured to use a Web service implemented in Java technology or a Web service can be congured to recognize a Visual Basic .NET client.

SOAP WITH ATTACHMENTS API FOR JAVA

21

JAX-RPC relies on the HTTP transport protocol. Taking that a step further, JAXRPC lets you create service applications that combine HTTP with a Java technology version of the Secure Socket Layer (SSL) and Transport Layer Security (TLS) protocols to establish basic or mutual authentication. SSL and TLS ensure message integrity by providing data encryption with client and server authentication capabilities. Authentication is a measured way to verify whether a party is eligible and able to access certain information as a way to protect against the fraudulent use of a system and/or the fraudulent transmission of information. Information transported across the Internet is especially vulnerable to being intercepted and misused, so conguring a JAX-RPC Web service to protect data in transit is very important.

SOAP with Attachments API for JavaThe SOAP with Attachments API for Java (SAAJ) is a low-level API upon which JAX-RPC depends. It enables the production and consumption of messages that conform to the SOAP 1.1 specication and SOAP with Attachments note. Most developers will not use the SAAJ API, but will use the higher-level JAX-RPC API instead.

J2EE Connector ArchitectureThe J2EE Connector architecture is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specic to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system. JAX-RPC and the J2EE Connector Architecture are complementary technologies for enterprise application integration (EAI) and end-to-end business integration. The J2EE Connector Architecture also provides a performance-oriented, secure, scalable, and message-based transactional integration of J2EE-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 J2EE platform can be exposed as XML-based Web services using JAXRPC and J2EE component models.

22

OVERVIEW

Java Authentication and Authorization ServiceThe Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specic user or group of users to run it. JAAS is a Java programing language version of the standard Pluggable Authentication Module (PAM) framework that extends the Java 2 Platform security architecture to support user-based authorization.

Simplied Systems IntegrationThe J2EE platform is a platform-independent, full systems integration solution that creates an open marketplace in which every vendor can sell to every customer. Such a marketplace encourages vendors to compete, not by trying to lock customers into their technologies but by trying to outdo each other by providing products and services that benet customers, such as better performance, better tools, or better customer support. The J2EE APIs enable systems and applications integration through the following: Unied application model across tiers with enterprise beans Simplied response and request mechanism with JSP pages and servlets Reliable security model with JAAS XML-based data interchange integration with JAXP Simplied interoperability with the J2EE Connector Architecture Easy database connectivity with the JDBC API Enterprise application integration with message-driven beans and JMS, JTA, and JNDI You can learn more about using the J2EE platform to build integrated business systems by reading J2EE Technology in Practice:http://java.sun.com/j2ee/inpractice/aboutthebook.html

2Understanding XMLTHIS chapter describes the Extensible Markup Language (XML) and itsrelated specications. It also gives you practice in writing XML data, so you become comfortably familiar with XML syntax.Note: The XML les mentioned in this chapter can be found in /j2eetutorial14/examples/xml/samples.

Introduction to XMLThis section covers the basics of XML. The goal is to give you just enough information to get started, so you understand what XML is all about. (Youll learn about XML in later sections of the tutorial.) We then outline the major features that make XML great for information storage and interchange, and give you a general idea of how XML can be used.

What Is XML?XML is a text-based markup language that is fast becoming the standard for data interchange on the Web. As with HTML, you identify data using tags (identiers enclosed in angle brackets, like this: ). Collectively, the tags are known as markup.23

24

UNDERSTANDING XML

But unlike HTML, XML tags identify the data, rather than specifying how to display it. Where an HTML tag says something like display this data in bold font (...), an XML tag acts like a eld name in your program. It puts a label on a piece of data that identies it (for example: ...).Note: Since identifying the data gives you some sense of what means (how to interpret it, what you should do with it), XML is sometimes described as a mechanism for specifying the semantics (meaning) of the data.

In the same way that you dene the eld names for a data structure, you are free to use any XML tags that make sense for a given application. Naturally, though, for multiple applications to use the same XML data, they have to agree on the tag names they intend to use. Here is an example of some XML data you might use for a messaging application: [email protected] [email protected] XML Is Really Cool How many ways is XML cool? Let me count the ways...

Note: Throughout this tutorial, we use boldface text to highlight things we want to bring to your attention. XML does not require anything to be in bold!

The tags in this example identify the message as a whole, the destination and sender addresses, the subject, and the text of the message. As in HTML, the tag has a matching end tag: . The data between the tag and its matching end tag denes an element of the XML data. Note, too, that the content of the tag is entirely contained within the scope of the .. tag. It is this ability for one tag to contain others that gives XML its ability to represent hierarchical data structures. Once again, as with HTML, whitespace is essentially irrelevant, so you can format the data for readability and yet still process it easily with a program. Unlike HTML, however, in XML you could easily search a data set for messages con-

WHAT IS XML?

25

taining cool in the subject, because the XML tags identify the content of the data, rather than specifying its representation.

Tags and AttributesTags can also contain attributesadditional information included as part of the tag itself, within the tags angle brackets. The following example shows an email message structure that uses attributes for the to, from, and subject elds: How many ways is XML cool? Let me count the ways...

As in HTML, the attribute name is followed by an equal sign and the attribute value, and multiple attributes are separated by spaces. Unlike HTML, however, in XML commas between attributes are not ignoredif present, they generate an error. Since you could design a data structure like equally well using either attributes or tags, it can take a considerable amount of thought to gure out which design is best for your purposes. Designing an XML Data Structure (page 78), includes ideas to help you decide when to use attributes and when to use tags.

Empty TagsOne really big difference between XML and HTML is that an XML document is always constrained to be well formed. There are several rules that determine when a document is well-formed, but one of the most important is that every tag has a closing tag. So, in XML, the tag is not optional. The element is never terminated by any tag other than .Note: Another important aspect of a well-formed document is that all tags are completely nested. So you can have ......, but never ....... A complete list of requirements is contained in the list of XML Frequently Asked Questions (FAQ) at

26

UNDERSTANDING XMLhttp://www.ucc.ie/xml/#FAQ-VALIDWF. (This FAQ is on the w3c Recommended Reading list at http://www.w3.org/XML/.)

Sometimes, though, it makes sense to have a tag that stands by itself. For example, you might want to add a flag tag that marks message as important. A tag like that doesnt enclose any content, so its known as an empty tag. You can create an empty tag by ending it with /> instead of >. For example, the following message contains such a tag: How many ways is XML cool? Let me count the ways...

Note: The empty tag saves you from having to code in order to have a well-formed document. You can control which tags are allowed to be empty by creating a Document Type Denition, or DTD. Well talk about that in a few moments. If there is no DTD, then the document can contain any kinds of tags you want, as long as the document is well-formed.

Comments in XML FilesXML comments look just like HTML comments: How many ways is XML cool? Let me count the ways...

WHAT IS XML?

27

The XML PrologTo complete this journeymans introduction to XML, note that an XML le always starts with a prolog. The minimal prolog contains a declaration that identies the document as an XML document, like this:

The declaration may also contain additional information, like this:

The XML declaration is essentially the same as the HTML header, , except that it uses and it may contain the following attributes: version Identies the version of the XML markup language used in the data. This attribute is not optional. encoding Identies the character set used to encode the data. ISO-8859-1 is Latin1 the Western European and English language character set. (The default is compressed Unicode: UTF-8.) standalone Tells whether or not this document references an external entity or an external data type specication (see below). If there are no external references, then yes is appropriate The prolog can also contain denitions of entities (items that are inserted when you reference them from within the document) and specications that tell which tags are valid in the document, both declared in a Document Type Denition (DTD) that can be dened directly within the prolog, as well as with pointers to external specication les. But those are the subject of later tutorials. For more information on these and many other aspects of XML, see the Recommended Reading list of the w3c XML page at http://www.w3.org/XML/.Note: The declaration is actually optional. But its a good idea to include it whenever you create an XML le. The declaration should have the version number, at a minimum, and ideally the encoding as well. That standard simplies things if the XML standard is extended in the future, and if the data ever needs to be localized for different geographical regions.

Everything that comes after the XML prolog constitutes the documents content.

28

UNDERSTANDING XML

Processing InstructionsAn XML le can also contain processing instructions that give commands or information to an application that is processing the XML data. Processing instructions have the following format:

where the target is the name of the application that is expected to do the processing, and instructions is a string of characters that embodies the information or commands for the application to process. Since the instructions are application specic, an XML le could have multiple processing instructions that tell different applications to do similar things, though in different ways. The XML le for a slideshow, for example, could have processing instructions that let the speaker specify a technical or executive-level version of the presentation. If multiple presentation programs were used, the program might need multiple versions of the processing instructions (although it would be nicer if such applications recognized standard instructions).Note: The target name xml (in any combination of upper or lowercase letters) is reserved for XML standards. In one sense, the declaration is a processing instruction that ts that standard. (However, when youre working with the parser later, youll see that the method for handling processing instructions never sees the declaration.)

Why Is XML Important?There are a number of reasons for XMLs surging acceptance. This section lists a few of the most prominent.

Plain TextSince XML is not a binary format, you can create and edit les with anything from a standard text editor to a visual development environment. That makes it easy to debug your programs, and makes it useful for storing small amounts of data. At the other end of the spectrum, an XML front end to a database makes it possible to efciently store large amounts of XML data as well. So XML provides scalability for anything from small conguration les to a company-wide data repository.

WHY IS XML IMPORTANT?

29

Data IdenticationXML tells you what kind of data you have, not how to display it. Because the markup tags identify the information and break up the data into parts, an email program can process it, a search program can look for messages sent to particular people, and an address book can extract the address information from the rest of the message. In short, because the different parts of the information have been identied, they can be used in different ways by different applications.

StylabilityWhen display is important, the stylesheet standard, XSL (page 37), lets you dictate how to portray the data. For example, the stylesheet for:[email protected]

can say: 1. Start a new line. 2. Display To: in bold, followed by a space 3. Display the destination data. Which produces:To: you@yourAddress

Of course, you could have done the same thing in HTML, but you wouldnt be able to process the data with search programs and address-extraction programs and the like. More importantly, since XML is inherently style-free, you can use a completely different stylesheet to produce output in postscript, TEX, PDF, or some new format that hasnt even been invented yet. That exibility amounts to what one author described as future-proong your information. The XML documents you author today can be used in future document-delivery systems that havent even been imagined yet.

Inline ReusabilityOne of the nicer aspects of XML documents is that they can be composed from separate entities. You can do that with HTML, but only by linking to other documents. Unlike HTML, XML entities can be included in line in a document. The included sections look like a normal part of the documentyou can search

30

UNDERSTANDING XML

the whole document at one time or download it in one piece. That lets you modularize your documents without resorting to links. You can single-source a section so that an edit to it is reected