Descarga la aplicación para disfrutar aún más
Vista previa del material en texto
The J2EE™ 1.4 Tutorial For Sun Java System Application Server Platform Edition 8.2 Eric Armstrong Jennifer Ball Stephanie Bodoff Debbie Bode Carson Ian Evans Dale Green Kim Haase Eric Jendrock December 7, 2005 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 supple- ments. 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 Microsys- tems, Inc. in the U.S. and other countries. Unless otherwise licensed, software code in all technical materials herein (including articles, FAQs, sam- ples) is provided under this License. Products covered by and information contained in this service manual are controlled by U.S. Export Con- trol 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 pro- hibited. 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 MER- CHANTABILITY, 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, États- Unis. Tous droits réservés. Droits du gouvernement américain, utlisateurs gouvernmentaux - logiciel commercial. Les utilisateurs gouvernmentaux sont soumis au contrat de licence standard de Sun Microsystems, Inc., ainsi qu aux dis- positions en vigueur de la FAR [ (Federal Acquisition Regulations) et des suppléments à celles-ci. Cette distribution peut comprendre des composants développés 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 déposées de Sun Microsystems, Inc. aux États-Unis et dans d’autres pays. A moins qu’autrement autorisé, le code de logiciel en tous les matériaux techniques dans le présent (arti- cles y compris, FAQs, échantillons) est fourni sous ce permis. Les produits qui font l’objet de ce manuel d’entretien et les informations qu’il contient sont régis par la législation américaine en matière de contrôle des exportations et peuvent être soumis au droit d’autres pays dans le domaine des exportations et importations. Les utilisations finales, ou utilisateurs finaux, pour des armes nucléaires, des missiles, des armes biologiques et chimiques ou du nucléaire maritime, directe- ment ou indirectement, sont strictement interdites. Les exportations ou réexportations vers des pays sous embargo des États-Unis, ou vers des entités figurant sur les listes d’exclusion d’exportation américaines, y compris, mais de manière non exclusive, la liste de personnes qui font objet d’un ordre de ne pas partic- iper, d’une façon directe ou indirecte, aux exportations des produits ou des services qui sont régi par la législation américaine en matière de contrôle des exportations ("U .S. Commerce Department’s Table of Denial Orders "et la liste de ressortissants spécifiquement désignés ("U.S. Treasury Department of Spe- cially Designated Nationals and Blocked Persons "),, sont rigoureusement interdites. LA DOCUMENTATION EST FOURNIE "EN L’ÉTAT" ET TOUTES AUTRES CONDITIONS, DEC- LARATIONS ET GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE, A L’APTITUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON. http://developer.sun.com/berkeley_license.html http://developer.sun.com/berkeley_license.html iii Contents Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxxi About This Tutorial. . . . . . . . . . . . . . . . . . . . . . . . . xxxiii Who Should Use This Tutorial xxxiii Prerequisites xxxiii How to Read This Tutorial xxxiv About the Examples xxxvi Further Information xxxix How to Buy This Tutorial xl How to Print This Tutorial xl Typographical Conventions xli Acknowledgments xli Feedback xlii Chapter 1: Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Distributed Multitiered Applications 2 J2EE Components 3 J2EE Clients 4 Web Components 6 Business Components 6 Enterprise Information System Tier 8 J2EE Containers 8 Container Services 8 Container Types 9 Web Services Support 10 XML 11 SOAP Transport Protocol 12 WSDL Standard Format 12 UDDI and ebXML Standard Formats 12 iv Packaging Applications 13 Development Roles 15 J2EE Product Provider 15 Tool Provider 15 Application Component Provider 16 Application Assembler 16 Application Deployer and Administrator 17 J2EE 1.4 APIs 18 Enterprise JavaBeans Technology 18 Java Servlet Technology 19 JavaServer Pages Technology 19 Java Message Service API 19 Java Transaction API 19 JavaMail API 20 JavaBeans Activation Framework 20 Java API for XML Processing 20 Java API for XML-Based RPC 20 SOAP with Attachments API for Java 21 Java API for XML Registries 21 J2EE Connector Architecture 22 JDBC API 22 Java Naming and Directory Interface 22 Java Authentication and Authorization Service 23 Simplified Systems Integration 24 Sun Java System Application Server Platform Edition 8 24 Technologies 25 Tools 26 Starting and Stopping the Application Server 27 Starting the Admin Console 28 Starting the deploytool Utility 29 Starting and Stopping the Derby Database Server 29 Debugging J2EE Applications 30 Chapter 2: Understanding XML. . . . . . . . . . . . . . . . . . . . . . . . . .33 Introduction to XML 33 What Is XML? 33 Why Is XML Important? 38 How Can You Use XML? 40 Generating XML Data 43 Writing a Simple XML File 43 v Defining the Root Element 44 Writing Processing Instructions 48 Introducing an Error 49 Substituting and Inserting Text 50 Creating a Document Type Definition 54 Documents and Data 59 Defining Attributes and Entities in the DTD 59 Referencing Binary Entities 66 Defining Parameter Entities and Conditional Sections 68 Resolving a Naming Conflict 72 Using Namespaces 73 Designing an XML Data Structure 76 Saving Yourself Some Work 77 Attributes and Elements 77 Normalizing Data 79 Normalizing DTDs 81 Summary 81 Chapter 3: Getting Started with Web Applications . . . . . . . . . 83 Web Application Life Cycle 86 Web Modules 88 Packaging Web Modules 90 Deploying Web Modules 92 Listing Deployed Web Modules 95 Updating Web Modules 96 Undeploying Web Modules 98 Configuring Web Applications 99 Mapping URLs to Web Components 99 Declaring Welcome Files 101 Setting Initialization Parameters 102 Mapping Errors to Error Screens 102 Declaring Resource References 103 Duke’s Bookstore Examples 103 Accessing Databases from Web Applications 104 Populating the Example Database 105 Creating a Data Source in the Application Server 106 Specifying a Web Application’s Resource Reference 106 Mapping the Resource Reference to a Data Source 107 Further Information 108 vi Chapter 4: Java API for XML Processing . . . . . . . . . . . . . . . . .109 The JAXP APIs 109 An Overview of the Packages 110The Simple API for XML APIs 111 The SAX Packages 114 The Document Object Model APIs 114 The DOM Packages 116 The Extensible Stylesheet Language Transformations APIs 117 The XSLT Packages 118 Using the JAXP Libraries 118 Where Do You Go from Here? 118 Chapter 5: Simple API for XML . . . . . . . . . . . . . . . . . . . . . . . . .121 When to Use SAX 122 Echoing an XML File with the SAX Parser 123 Creating the Skeleton 124 Importing Classes 124 Setting Up for I/O 125 Implementing the ContentHandler Interface 125 Setting up the Parser 127 Writing the Output 128 Spacing the Output 128 Handling Content Events 129 Compiling and Running the Program 134 Checking the Output 135 Identifying the Events 136 Compressing the Output 138 Inspecting the Output 140 Documents and Data 141 Adding Additional Event Handlers 141 Identifying the Document’s Location 142 Handling Processing Instructions 144 Summary 145 Handling Errors with the Nonvalidating Parser 145 Displaying Special Characters and CDATA 153 Handling Special Characters 153 Handling Text with XML-Style Syntax 154 Handling CDATA and Other Characters 155 Parsing with a DTD 156 DTD’s Effect on the Nonvalidating Parser 156 vii Tracking Ignorable Whitespace 157 Cleanup 159 Empty Elements, Revisited 159 Echoing Entity References 160 Echoing the External Entity 160 Summarizing Entities 161 Choosing Your Parser Implementation 161 Using the Validating Parser 162 Configuring the Factory 162 Validating with XML Schema 163 Experimenting with Validation Errors 166 Error Handling in the Validating Parser 168 Parsing a Parameterized DTD 168 DTD Warnings 170 Handling Lexical Events 170 How the LexicalHandler Works 171 Working with a LexicalHandler 172 Using the DTDHandler and EntityResolver 177 The DTDHandler API 178 The EntityResolver API 179 Further Information 179 Chapter 6: Document Object Model . . . . . . . . . . . . . . . . . . . 181 When to Use DOM 182 Documents Versus Data 182 Mixed-Content Model 183 A Simpler Model 184 Increasing the Complexity 185 Choosing Your Model 187 Reading XML Data into a DOM 188 Creating the Program 188 Additional Information 192 Looking Ahead 194 Displaying a DOM Hierarchy 195 Convert DomEcho to a GUI Application 195 Create Adapters to Display the DOM in a JTree 201 Finishing Up 211 Examining the Structure of a DOM 211 Displaying a Simple Tree 211 Displaying a More Complex Tree 214 viii Finishing Up 220 Constructing a User-Friendly JTree from a DOM 221 Compressing the Tree View 221 Acting on Tree Selections 227 Handling Modifications 237 Finishing Up 237 Creating and Manipulating a DOM 237 Obtaining a DOM from the Factory 237 Normalizing the DOM 241 Other Operations 243 Finishing Up 246 Validating with XML Schema 246 Overview of the Validation Process 247 Configuring the DocumentBuilder Factory 247 Validating with Multiple Namespaces 249 Further Information 252 Chapter 7: Extensible Stylesheet Language Transformations 253 Introducing XSL, XSLT, and XPath 254 The JAXP Transformation Packages 254 How XPath Works 255 XPath Expressions 255 The XSLT/XPath Data Model 256 Templates and Contexts 257 Basic XPath Addressing 257 Basic XPath Expressions 258 Combining Index Addresses 259 Wildcards 259 Extended-Path Addressing 260 XPath Data Types and Operators 261 String-Value of an Element 261 XPath Functions 262 Summary 265 Writing Out a DOM as an XML File 265 Reading the XML 266 Creating a Transformer 267 Writing the XML 270 Writing Out a Subtree of the DOM 271 Summary 272 Generating XML from an Arbitrary Data Structure 272 ix Creating a Simple File 273 Creating a Simple Parser 275 Modifying the Parser to Generate SAX Events 277 Using the Parser as a SAXSource 284 Doing the Conversion 286 Transforming XML Data with XSLT 287 Defining a Simple <article> Document Type 287 Creating a Test Document 289 Writing an XSLT Transform 290 Processing the Basic Structure Elements 291 Writing the Basic Program 295 Trimming the Whitespace 297 Processing the Remaining Structure Elements 300 Process Inline (Content) Elements 304 Printing the HTML 309 What Else Can XSLT Do? 309 Transforming from the Command Line with Xalan 311 Concatenating Transformations with a Filter Chain 311 Writing the Program 311 Understanding How the Filter Chain Works 315 Testing the Program 316 Further Information 318 Chapter 8: Building Web Services with JAX-RPC . . . . . . . . . . 319 Setting the Port 320 Creating a Simple Web Service and Client with JAX-RPC 320 Coding the Service Endpoint Interface and Implementation Class 322 Building the Service 323 Packaging and Deploying the Service 324 Static Stub Client 327 Types Supported by JAX-RPC 330 J2SE SDK Classes 331 Primitives 331 Arrays 332 Value Types 332 JavaBeans Components 332 Web Service Clients 333 Dynamic Proxy Client 333 Dynamic Invocation Interface Client 336 Application Client 340 x More JAX-RPC Clients 343 Web Services Interoperability and JAX-RPC 344 Further Information 344 Chapter 9: SOAP with Attachments API for Java . . . . . . . . . .345 Overview of SAAJ 346 Messages 346 Connections 350 Tutorial 352 Creating and Sending a Simple Message 353 Adding Content to the Header 362 Adding Content to the SOAPPart Object 363 Adding a Document to the SOAP Body 364 Manipulating Message Content Using SAAJ or DOM APIs 364 Adding Attachments 365 Adding Attributes 368 Using SOAP Faults 373 Code Examples 378 Request.java 378 MyUddiPing.java 380 HeaderExample.java 387 DOMExample.java and DOMSrcExample.java 388 Attachments.java 392 SOAPFaultTest.java 394 Further Information 395 Chapter 10: Java API for XML Registries . . . . . . . . . . . . . . . . . .397 Overview of JAXR 397 What Is a Registry? 397 What Is JAXR? 398 JAXR Architecture 399 Implementing a JAXR Client 400 Establishing a Connection 401 Querying a Registry 408 Managing Registry Data 413 Using Taxonomies in JAXR Clients 421 Running the Client Examples 426 Before You Compile the Examples 427 Compiling the Examples 429 xi Running the Examples 429 Using JAXR Clients in J2EE Applications 434 Coding the Application Client: MyAppClient.java 435 Coding the PubQuery Session Bean 435 Editing the Properties File 436 Compiling the Source Files 436 Starting the Application Server 436 Creating JAXR Resources 436 Creating and Packaging the Application 437 Deploying the Application 440 Running the Application Client 441 Further Information 441 Chapter 11: Java Servlet Technology . . . . . . . . . . . . . . . . . . . . 443 What Is a Servlet? 443 The Example Servlets 444 Troubleshooting 448 Servlet Life Cycle 449 Handling Servlet Life-Cycle Events 450 Handling Errors 452 Sharing Information 452 Using Scope Objects 453 Controlling Concurrent Access to Shared Resources 454 Accessing Databases 455 Initializing a Servlet 456 Writing Service Methods 457 Getting Information from Requests 458 Constructing Responses 460 Filtering Requests and Responses 463 Programming Filters 463 Programming Customized Requests and Responses 465 Specifying Filter Mappings 468 Invoking Other Web Resources 469 Including Other Resources in the Response 470 Transferring Control to Another Web Component 472 Accessing the Web Context 473 Maintaining Client State 474 Accessing a Session 474 Associating Objects with a Session 474 Session Management 475 xii Session Tracking 476 Finalizing a Servlet 477 Tracking Service Requests 478 Notifying Methods to Shut Down 478 Creating Polite Long-Running Methods 479 Further Information 480 Chapter 12: JavaServer Pages Technology . . . . . . . . . . . . . . .481 What Is a JSP Page? 481 Example 482 The Example JSP Pages 486 The Life Cycle of a JSP Page 493 Translation and Compilation 493 Execution 494 Creating Static Content 496 Response and Page Encoding 497 Creating Dynamic Content 497 Using Objects within JSP Pages 498 Expression Language 499 Deactivating Expression Evaluation 500 Using Expressions 500 Variables 501 Implicit Objects 502 Literals 503 Operators 504 Reserved Words 504 Examples505 Functions 506 JavaBeans Components 507 JavaBeans Component Design Conventions 507 Creating and Using a JavaBeans Component 509 Setting JavaBeans Component Properties 510 Retrieving JavaBeans Component Properties 512 Using Custom Tags 513 Declaring Tag Libraries 513 Including the Tag Library Implementation 516 Reusing Content in JSP Pages 517 Transferring Control to Another Web Component 518 jsp:param Element 518 Including an Applet 519 xiii Setting Properties for Groups of JSP Pages 521 Further Information 524 Chapter 13: JavaServer Pages Documents . . . . . . . . . . . . . . . 525 The Example JSP Document 526 Creating a JSP Document 531 Declaring Tag Libraries 534 Including Directives in a JSP Document 536 Creating Static and Dynamic Content 537 Using the jsp:root Element 541 Using the jsp:output Element 542 Identifying the JSP Document to the Container 546 Chapter 14: JavaServer Pages Standard Tag Library . . . . . . . 547 The Example JSP Pages 548 Using JSTL 551 Tag Collaboration 553 Core Tag Library 554 Variable Support Tags 554 Flow Control Tags 555 URL Tags 558 Miscellaneous Tags 559 XML Tag Library 560 Core Tags 562 Flow Control Tags 563 Transformation Tags 564 Internationalization Tag Library 564 Setting the Locale 565 Messaging Tags 566 Formatting Tags 566 SQL Tag Library 567 query Tag Result Interface 569 Functions 572 Further Information 573 Chapter 15: Custom Tags in JSP Pages . . . . . . . . . . . . . . . . . . . 575 What Is a Custom Tag? 576 The Example JSP Pages 576 Types of Tags 581 xiv Tags with Attributes 581 Tags with Bodies 584 Tags That Define Variables 585 Communication between Tags 585 Encapsulating Reusable Content Using Tag Files 586 Tag File Location 588 Tag File Directives 589 Evaluating Fragments Passed to Tag Files 597 Examples 598 Tag Library Descriptors 602 Top-Level Tag Library Descriptor Elements 603 Declaring Tag Files 604 Declaring Tag Handlers 607 Declaring Tag Attributes for Tag Handlers 609 Declaring Tag Variables for Tag Handlers 610 Programming Simple Tag Handlers 612 Including Tag Handlers in Web Applications 613 How Is a Simple Tag Handler Invoked? 613 Tag Handlers for Basic Tags 613 Tag Handlers for Tags with Attributes 614 Tag Handlers for Tags with Bodies 616 Tag Handlers for Tags That Define Variables 617 Cooperating Tags 620 Examples 622 Chapter 16: Scripting in JSP Pages . . . . . . . . . . . . . . . . . . . . . .631 The Example JSP Pages 632 Using Scripting 633 Disabling Scripting 634 Declarations 635 Initializing and Finalizing a JSP Page 635 Scriptlets 636 Expressions 636 Programming Tags That Accept Scripting Elements 637 TLD Elements 638 Tag Handlers 638 Tags with Bodies 640 Cooperating Tags 642 Tags That Define Variables 644 xv Chapter 17: JavaServer Faces Technology . . . . . . . . . . . . . . . 647 JavaServer Faces Technology Benefits 649 What Is a JavaServer Faces Application? 650 Framework Roles 651 A Simple JavaServer Faces Application 652 Steps in the Development Process 652 Creating the Pages 655 Defining Page Navigation 658 Developing the Beans 659 Adding Managed Bean Declarations 661 User Interface Component Model 662 User Interface Component Classes 663 Component Rendering Model 664 Conversion Model 669 Event and Listener Model 670 Validation Model 671 Navigation Model 672 Backing Bean Management 674 How the Pieces Fit Together 677 The Life Cycle of a JavaServer Faces Page 680 Request Processing Life Cycle Scenarios 681 Standard Request Processing Life Cycle 682 Further Information 687 Chapter 18: Using JavaServer Faces Technology in JSP Pages . . 689 The Example JavaServer Faces Application 690 Setting Up a Page 694 Using the Core Tags 697 Using the HTML Component Tags 699 UI Component Tag Attributes 700 The UIForm Component 703 The UIColumn Component 703 The UICommand Component 704 The UIData Component 706 The UIGraphic Component 709 The UIInput and UIOutput Components 710 The UIPanel Component 714 The UISelectBoolean Component 717 xvi The UISelectMany Component 717 The UIMessage and UIMessages Components 718 The UISelectOne Component 719 The UISelectItem, UISelectItems, and UISelectItemGroup Components 720 Using Localized Messages 724 Referencing a ResourceBundle from a Page 724 Referencing a Localized Message 725 Using the Standard Converters 726 Using DateTimeConverter 727 Using NumberConverter 729 Registering Listeners on Components 731 Registering a Value-Change Listener on a Component 731 Registering an Action Listener on a Component 732 Using the Standard Validators 732 Requiring a Value 734 Using the LongRangeValidator 734 Binding Component Values and Instances to External Data Sources 735 Binding a Component Value to a Property 736 Binding a Component Value to an Implicit Object 738 Binding a Component Instance to a Bean Property 739 Referencing a Backing Bean Method 741 Referencing a Method That Performs Navigation 741 Referencing a Method That Handles an Action Event 742 Referencing a Method That Performs Validation 743 Referencing a Method That Handles a Value-change Event 743 Using Custom Objects 744 Using a Custom Converter 745 Using a Custom Validator 746 Using a Custom Component 747 Chapter 19: Developing with JavaServer Faces Technology .749 Writing Component Properties 750 Writing Properties Bound to Component Values 750 Writing Properties Bound to Component Instances 759 Performing Localization 761 Creating a Resource Bundle 761 Localizing Dynamic Data 762 Localizing Messages 762 xvii Creating a Custom Converter 764 Implementing an Event Listener 767 Implementing Value-Change Listeners 768 Implementing Action Listeners 769 Creating a Custom Validator 770 Implementing the Validator Interface 771 Creating a Custom Tag 775 Writing Backing Bean Methods 777 Writing a Method to Handle Navigation 777 Writing a Method to Handle an Action Event 779 Writing a Method to Perform Validation 779 Writing a Method to Handle a Value-Change Event 780 Chapter 20: Creating Custom UI Components . . . . . . . . . . . . 783 Determining Whether You Need a Custom Component or Renderer 784 When to Use a Custom Component 784 When to Use a Custom Renderer 785 Component, Renderer, and Tag Combinations 786 Understanding the Image Map Example 787 Why Use JavaServer Faces Technology to Implement an Image Map? 788 Understanding the Rendered HTML 788 Understanding the JSP Page 789 Configuring Model Data 791 Summary of the Application Classes 793 Steps for Creating a Custom Component 794 Creating the Component Tag Handler 795 Defining the Custom Component Tag in a Tag Library Descriptor 800 Creating Custom Component Classes 801 Specifying the Component Family 804 Performing Encoding 804 Performing Decoding 806 Enabling Value-Binding of Component Properties 807 Saving and Restoring State 808 Delegating Rendering to a Renderer 810 Creating the Renderer Class 810 Identifying the Renderer Type 812 Handling Events for Custom Components 812 xviii Chapter 21: Configuring JavaServer Faces Applications . . . .815 Application Configuration Resource File 816 Configuring Beans 817 Using the managed-bean Element 818 Initializing Properties using the managed-property Element 819 Initializing Maps and Lists 825 Registering Messages 827 Registering a Custom Validator 828 Registering a Custom Converter 828 Configuring Navigation Rules 829 Registering a Custom Renderer with a Render Kit 833 Registering a Custom Component 835 Basic Requirements of a JavaServer Faces Application 837 Configuring an Application Using deploytool 838 Including the Required JAR Files 843 Including the Classes, Pages, and Other Resources 843 Chapter 22: Internationalizing and Localizing Web Applications . 845 Java Platform Localization Classes 845 Providing Localized Messages and Labels 846 Establishing the Locale 847 Setting the Resource Bundle 847 Retrieving Localized Messages 848 Date and Number Formatting 849 Character Sets and Encodings 849 Character Sets 849 Character Encoding 850Further Information 853 Chapter 23: Enterprise Beans . . . . . . . . . . . . . . . . . . . . . . . . . . .855 What Is an Enterprise Bean? 855 Benefits of Enterprise Beans 855 When to Use Enterprise Beans 856 Types of Enterprise Beans 857 What Is a Session Bean? 857 State Management Modes 857 When to Use Session Beans 858 What Is an Entity Bean? 859 xix What Makes Entity Beans Different from Session Beans? 859 Container-Managed Persistence 861 When to Use Entity Beans 864 What Is a Message-Driven Bean? 864 What Makes Message-Driven Beans Different from Session and Entity Beans? 865 When to Use Message-Driven Beans 866 Defining Client Access with Interfaces 866 Remote Clients 867 Local Clients 868 Local Interfaces and Container-Managed Relationships 868 Deciding on Remote or Local Access 869 Web Service Clients 870 Method Parameters and Access 870 The Contents of an Enterprise Bean 871 Naming Conventions for Enterprise Beans 872 The Life Cycles of Enterprise Beans 873 The Life Cycle of a Stateful Session Bean 873 The Life Cycle of a Stateless Session Bean 875 The Life Cycle of an Entity Bean 875 The Life Cycle of a Message-Driven Bean 877 Further Information 878 Chapter 24: Getting Started with Enterprise Beans . . . . . . . . . 879 Creating the J2EE Application 880 Creating the Enterprise Bean 880 Coding the Enterprise Bean 881 Compiling the Source Files 882 Packaging the Enterprise Bean 883 Creating the Application Client 884 Coding the Application Client 885 Compiling the Application Client 887 Packaging the Application Client 888 Specifying the Application Client’s Enterprise Bean Reference 889 Creating the Web Client 889 Coding the Web Client 889 Compiling the Web Client 891 Packaging the Web Client 891 Specifying the Web Client’s Enterprise Bean Reference 892 Mapping the Enterprise Bean References 893 xx Specifying the Web Client’s Context Root 894 Deploying the J2EE Application 895 Running the Application Client 895 Running the Web Client 896 Modifying the J2EE Application 897 Modifying a Class File 897 Adding a File 898 Modifying a Deployment Setting 898 Chapter 25: Session Bean Examples . . . . . . . . . . . . . . . . . . . . .899 The CartBean Example 899 Session Bean Class 900 Home Interface 904 Remote Interface 906 Helper Classes 906 Building the CartBean Example 906 Creating the Application 907 Packaging the Enterprise Bean 907 Packaging the Application Client 908 A Web Service Example: HelloServiceBean 911 Web Service Endpoint Interface 911 Stateless Session Bean Implementation Class 911 Building HelloServiceBean 912 Building the Web Service Client 915 Running the Web Service Client 916 Other Enterprise Bean Features 916 Accessing Environment Entries 916 Comparing Enterprise Beans 917 Passing an Enterprise Bean’s Object Reference 918 Using the Timer Service 919 Creating Timers 919 Canceling and Saving Timers 920 Getting Timer Information 921 Transactions and Timers 921 The TimerSessionBean Example 921 Building TimerSessionBean 923 Handling Exceptions 928 xxi Chapter 26: Bean-Managed Persistence Examples . . . . . . . . 931 The SavingsAccountBean Example 931 Entity Bean Class 932 Home Interface 943 Remote Interface 945 Running the SavingsAccountBean Example 946 Mapping Table Relationships for Bean-Managed Persistence 947 One-to-One Relationships 948 One-to-Many Relationships 951 Many-to-Many Relationships 959 Primary Keys for Bean-Managed Persistence 962 The Primary Key Class 963 Primary Keys in the Entity Bean Class 964 Getting the Primary Key 965 deploytool Tips for Entity Beans with Bean-Managed Persistence 965 Chapter 27: Container-Managed Persistence Examples . . . . 967 Overview of the RosterApp Application 967 The PlayerBean Code 969 Entity Bean Class 969 Local Home Interface 974 Local Interface 975 Method Invocations in RosterApp 975 Creating a Player 976 Adding a Player to a Team 977 Removing a Player 978 Dropping a Player from a Team 979 Getting the Players of a Team 980 Getting a Copy of a Team’s Players 982 Finding the Players by Position 984 Getting the Sports of a Player 985 Building and Running the RosterApp Example 987 Creating the Database Tables 987 Creating the Data Source 988 Capturing the Table Schema 988 Building the Enterprise Beans 989 Creating the Enterprise Application 989 Packaging the Enterprise Beans 989 Packaging the Enterprise Application Client 998 Deploying the Enterprise Application 999 xxii Running the Client Application 1000 A Guided Tour of the RosterApp Settings 1001 RosterApp 1001 RosterClient 1003 RosterJAR 1003 TeamJAR 1004 Primary Keys for Container-Managed Persistence 1010 The Primary Key Class 1011 Advanced CMP Topics: The OrderApp Example 1013 Structure of OrderApp 1013 Bean Relationships in OrderApp 1014 Primary Keys in OrderApp’s Entity Beans 1016 Entity Bean Mapped to More Than One Database Table 1019 Finder and Selector Methods 1019 Using Home Methods 1020 Cascade Deletes in OrderApp 1020 BLOB and CLOB Database Types in OrderApp 1020 Building and Running the OrderApp Example 1021 deploytool Tips for Entity Beans with Container-Managed Persistence 1030 Selecting the Persistent Fields and Abstract Schema Name 1031 Defining EJB QL Queries for Finder and Select Methods 1031 Defining Relationships 1032 Creating the Database Tables at Deploy Time in deploytool 1032 Chapter 28: A Message-Driven Bean Example . . . . . . . . . . .1033 Example Application Overview 1033 The Application Client 1034 The Message-Driven Bean Class 1035 The onMessage Method 1035 The ejbCreate and ejbRemove Methods 1037 Deploying and Running SimpleMessageApp 1037 Creating the Administered Objects 1037 Deploying the Application 1038 Running the Client 1039 Removing the Administered Objects 1039 deploytool Tips for Message-Driven Beans 1040 Specifying the Bean’s Type 1040 Setting the Message-Driven Bean’s Characteristics 1040 deploytool Tips for Components That Send Messages 1041 xxiii Setting the Resource References 1042 Setting the Message Destination References 1042 Setting the Message Destinations 1043 Chapter 29: Enterprise JavaBeans Query Language1045 Terminology 1046 Simplified Syntax 1046 Example Queries 1047 Simple Finder Queries 1047 Finder Queries That Navigate to Related Beans 1049 Finder Queries with Other Conditional Expressions 1050 Select Queries 1052 Full Syntax 1052 BNF Symbols 1053 BNF Grammar of EJB QL 1053 FROM Clause 1057 Path Expressions 1060 WHERE Clause 1062 SELECT Clause 1071 ORDER BY Clause 1074 EJB QL Restrictions 1075 Chapter 30: Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1077 What Is a Transaction? 1077 Container-Managed Transactions 1078 Transaction Attributes 1078 Rolling Back a Container-Managed Transaction 1082 Synchronizing a Session Bean’s Instance Variables 1084 Compiling the BankBean Example 1085 Packaging the BankBean Example 1086 Methods Not Allowed in Container-Managed Transactions 1089 Bean-Managed Transactions 1089 JDBC Transactions 1090 Deploying and Running the WarehouseBean Example 1091 Compiling the WarehouseBean Example 1091 Packaging the WarehouseBean Example 1092 JTA Transactions 1095 Deploying and Running the TellerBean Example 1096 xxiv Compiling the TellerBean Example 1097 Packaging the TellerBean Example 1097 Returning without Committing 1100 Methods Not Allowed in Bean-Managed Transactions 1101 Summary of Transaction Options for Enterprise Beans 1101 Transaction Timeouts 1102 Isolation Levels 1103 Updating Multiple Databases 1104 Transactions in Web Components 1105 Chapter 31: Resource Connections . . . . . . . . . . . . . . . . . . . . .1107 JNDI Naming 1107 DataSource Objects and Connection Pools 1109 Database Connections 1110 Coding a Database Connection 1110 Specifying a Resource Reference 1111 Creating a Data Source 1112 Mail Session Connections 1113 Running the ConfirmerBean Example 1114 URL Connections 1116 Running the HTMLReaderBean Example 1117 Further Information 1118 Chapter 32: Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1119 Overview 1119 Realms, Users, Groups, and Roles 1120 Managing Users 1121 Setting Up Security Roles 1122 Mapping Roles to Users and Groups 1123 Web-Tier Security 1125 Protecting Web Resources 1127 Setting Security Requirements Using deploytool 1128 Specifying a Secure Connection 1130 Using Programmatic Security in the Web Tier 1131 Understanding Login Authentication 1133 Using HTTP Basic Authentication 1133 Using Form-Based Authentication 1134 Using Client-Certificate Authentication 1135 Using Mutual Authentication 1136 xxv Using Digest Authentication 1138 Configuring Authentication 1139 Example: Using Form-Based Authentication 1139 Installing and Configuring SSL Support 1148 What Is Secure Socket Layer Technology? 1148 Understanding Digital Certificates 1149 Using SSL 1156 XML and Web Services Security 1159 Transport-Level Security 1160 Example: Basic Authentication with JAX-RPC 1161 Example: Client-Certificate Authentication over HTTP/SSL with JAX-RPC 1167 EJB-Tier Security 1175 Declaring Method Permissions 1175 Configuring IOR Security 1176 Using Programmatic Security in the EJB Tier 1178 Unauthenticated User Name 1178 Application Client-Tier Security 1178 EIS-Tier Security 1179 Container-Managed Sign-On 1180 Component-Managed Sign-On 1180 Configuring Resource Adapter Security 1181 Propagating Security Identity 1182 Configuring a Component’s Propagated Security Identity 1183 Configuring Client Authentication 1184 What Is Java Authorization Contract for Containers? 1184 Further Information 1185 Chapter 33: The Java Message Service API . . . . . . . . . . . . . . 1187 Overview 1188 What Is Messaging? 1188 What Is the JMS API? 1188 When Can You Use the JMS API? 1189 How Does the JMS API Work with the J2EE Platform? 1191 Basic JMS API Concepts 1192 JMS API Architecture 1192 Messaging Domains 1193 Message Consumption 1195 The JMS API Programming Model 1196 Administered Objects 1197 xxvi Connections 1199 Sessions 1199 Message Producers 1200 Message Consumers 1201 Messages 1204 Exception Handling 1207 Writing Simple JMS Client Applications 1208 A Simple Example of Synchronous Message Receives 1208 A Simple Example of Asynchronous Message Consumption 1219 Running JMS Client Programs on Multiple Systems 1223 Creating Robust JMS Applications 1228 Using Basic Reliability Mechanisms 1229 Using Advanced Reliability Mechanisms 1236 Using the JMS API in a J2EE Application 1248 Using Session and Entity Beans to Produce and to Synchronously Re- ceive Messages 1248 Using Message-Driven Beans 1250 Managing Distributed Transactions 1252 Using the JMS API with Application Clients and Web Components1255 Further Information 1255 Chapter 34: J2EE Examples Using the JMS API . . . . . . . . . . . .1257 A J2EE Application That Uses the JMS API with a Session Bean 1258 Writing the Application Components 1259 Creating and Packaging the Application 1261 Deploying the Application 1265 Running the Application Client 1266 A J2EE Application That Uses the JMS API with an Entity Bean 1267 Overview of the Human Resources Application 1267 Writing the Application Components 1269 Creating and Packaging the Application 1271 Deploying the Application 1274 Running the Application Client 1274 An Application Example That Consumes Messages from a Remote J2EE Server 1275 Overview of the Applications 1276 Writing the Application Components 1277 Creating and Packaging the Applications 1277 Deploying the Applications 1280 Running the Application Client 1281 xxvii An Application Example That Deploys a Message-Driven Bean on Two J2EE Servers 1282 Overview of the Applications 1282 Writing the Application Components 1284 Creating and Packaging the Applications 1285 Deploying the Applications 1288 Running the Application Client 1289 Chapter 35: The Coffee Break Application. . . . . . . . . . . . . . . 1291 Common Code 1293 JAX-RPC Coffee Supplier Service 1293 Service Interface 1293 Service Implementation 1294 Publishing the Service in the Registry 1295 Deleting the Service From the Registry 1300 SAAJ Coffee Supplier Service 1302 SAAJ Client 1303 SAAJ Service 1310 Coffee Break Server 1317 JSP Pages 1318 JavaBeans Components 1318 RetailPriceListServlet 1321 JavaServer Faces Version of Coffee Break Server 1321 JSP Pages 1322 JavaBeans Components 1324 Resource Configuration 1326 Building, Packaging, Deploying, and Running the Application 1327 Setting the Port 1327 Setting the Registry Properties 1328 Using the Provided WARs 1329 Building the Common Classes 1329 Building, Packaging, and Deploying the JAX-RPC Service 1330 Building, Packaging, and Deploying the SAAJ Service 1332 Building, Packaging, and Deploying the Coffee Break Server 1333 Building, Packaging, and Deploying the JavaServer Faces Technology Coffee Break Server 1335 Running the Coffee Break Client 1336 Removing the Coffee Break Application 1338 xxviii Chapter 36: The Duke’s Bank Application. . . . . . . . . . . . . . . .1339 Enterprise Beans 1340 Session Beans 1341 Entity Beans 1344 Helper Classes 1345 Database Tables 1346 Protecting the Enterprise Beans 1347 Application Client 1347 The Classes and Their Relationships 1349 BankAdmin Class 1350 EventHandle Class 1352 DataModel Class 1353 Web Client 1355 Design Strategies 1357 Client Components 1358 Request Processing 1361 Protecting the Web Client Resources 1363 Internationalization 1365 Building, Packaging, Deploying, and Running the Application 1366 Setting Up the Servers 1367 Compiling the Duke’s Bank Application Code 1369 Packaging and Deploying the Duke’s Bank Application 1369 Reviewing JNDI Names 1379 Running the Clients 1380 Running the Application Client 1380 Running the Web Client 1381 Appendix A: Java Encoding Schemes . . . . . . . . . . . . . . . . . . .1383 Further Information 1384 Appendix B: XML and Related Specs: Digesting the Alphabet Soup 1385 Basic Standards 1386 SAX 1386 StAX 1387 DOM 1387 JDOM and dom4j 1387 DTD 1388 Namespaces 1389 xxix XSL 1389 XSLT (+XPath) 1389 Schema Standards 1390 XML Schema 1391 RELAX NG 1391 SOX 1391 Schematron 1392 Linking and Presentation Standards 1392 XML Linking 1392 XHTML 1393 Knowledge Standards 1393 RDF 1393 RDF Schema 1394 XTM 1394 Standards That Build on XML 1394 Extended Document Standards 1395 e-Commerce Standards 1395 Summary 1396 Appendix C: HTTP Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . 1397 HTTP Requests 1398 HTTP Responses 1398 Appendix D: J2EE Connector Architecture . . . . . . . . . . . . . . . 1399 About Resource Adapters 1399 Resource Adapter Contracts 1401 Management Contracts 1402 Outbound Contracts 1403 Inbound Contracts 1404 Common Client Interface 1405 Further Information 1406 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1407 About the Authors . . . . . . . . . . . . . . . . . . . . . . . . 1445 Current Writers 1445 Past Writers 1446 xxx Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1447 xxxi Foreword When the first edition of The J2EE™ Tutorial was released, the Java™ 2 Plat- form, Enterprise Edition (J2EE) was the new kid on the block. Modeled after its forerunner, the Java 2 Platform, Standard Edition (J2SE™), the J2EE platform brought the benefits of “Write Once, Run Anywhere™” API compatibility to enterprise application servers. Now at version 1.4 and with widespread conform- ance in the application server marketplace, the J2EE platform has firmly estab- lished its position as the standard for enterprise application servers. The J2EE™ Tutorial, Second Edition covers the J2EE 1.4 platform and more. If you have used the first edition of The J2EE™ Tutorial you may notice that the second edition is triple the size. This reflects a major expansion in the J2EE plat- form and the availability of two upcoming J2EE technologies in the Sun Java System Application Server Platform Edition 8.2, the software on which the tuto- rial is based.One of the most important additions to the J2EE 1.4 platform is substantial sup- port for web services with the JAX-RPC 1.1 API, which enables web service endpoints based on servlets and enterprise beans. The platform also contains web services support APIs for handling XML data streams directly (SAAJ) and for accessing web services registries (JAXR). In addition, the J2EE 1.4 platform requires WS-I Basic Profile 1.0. This means that in addition to platform indepen- dence and complete web services support, the J2EE 1.4 platform offers web ser- vices interoperability. The J2EE 1.4 platform contains major enhancements to the Java servlet and Jav- aServer Pages (JSP) technologies that are the foundation of the web tier. The tutorial also showcases two exciting new technologies, not required by the J2EE 1.4 platform, that simplify the task of building J2EE application user interfaces: JavaServer Pages Standard Tag Library (JSTL) and JavaServer Faces. These new xxxii technologies are available in the Application Server. They will soon be featured in new developer tools and are strong candidates for inclusion in the next version of the J2EE platform. Readers conversant with the core J2EE platform enterprise bean technology will notice major upgrades with the addition of the previously mentioned web service endpoints, as well as a timer service, and enhancements to EJB QL and message- driven beans. With all of these new features, I believe that you will find it well worth your time and energy to take on the J2EE 1.4 platform. You can increase the scope of the J2EE applications you develop, and your applications will run on the widest pos- sible range of application server products. To help you to learn all about the J2EE 1.4 platform, The J2EE™ Tutorial, Sec- ond Edition follows the familiar Java Series tutorial model of concise descrip- tions of the essential features of each technology with code examples that you can deploy and run on the Application Server. Read this tutorial and you will become part of the next wave of J2EE application developers. Jeff Jackson Vice President, J2EE Platform and Application Servers Sun Microsystems Santa Clara, CA December 7, 2005 About This Tutorial THE J2EE™ 1.4 Tutorial is a guide to developing enterprise applications for the Java 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 Tutorial This tutorial is intended for programmers who are interested in developing and deploying J2EE 1.4 applications on the Sun Java System Application Server Platform Edition 8.2. Prerequisites Before proceeding with this tutorial you should have a good knowledge of the Java programming language. A good way to get to that point is to work through 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 URL JDBC http://java.sun.com/docs/books/tutorial/jdbc Security http://java.sun.com/docs/books/tutorial/security1.2 xxxiii http://java.sun.com/docs/books/tutorial/jdbc http://java.sun.com/docs/books/tutorial/security1.2 xxxiv How to Read This Tutorial The J2EE 1.4 platform is quite large, and this tutorial reflects this. However, you don’t have to digest everything in it at once. This tutorial opens with three introductory chapters, which you should read before proceeding to any specific technology area. Chapter 1 covers the J2EE 1.4 platform architecture and APIs along with the Sun Java System Application Server Platform Edition 8.2. Chapters 2 and 3 cover XML basics and getting started with web applications. When you have digested the basics, you can delve into one or more of the four 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 Java XML chapters cover the technologies for developing applications that process XML documents and implement web services components: • 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) • The web-tier technology chapters cover the components used in develop- ing the presentation layer of a J2EE or stand-alone web application: • Java Servlet • JavaServer Pages (JSP) • JavaServer Pages Standard Tag Library (JSTL) • JavaServer Faces • web application internationalization and localization • The Enterprise JavaBeans (EJB) technology chapters cover the compo- nents used in developing the business logic of a J2EE application: • Session beans • Entity beans • Message-driven beans xxxv • Enterprise JavaBeans Query Language • The platform services chapters cover the system services used by all the J2EE component technologies: • Transactions • Resource connections • Security • Java Message Service Figure 1 Roadmap to This Tutorial xxxvi 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 35) describes an application that uses the web application and web services APIs. The Duke’s Bank Application (Chapter 36) describes an application that employs web appli- cation technologies and enterprise beans. Finally, the appendixes contain auxiliary information helpful to the J2EE appli- cation developer along with a brief summary of the J2EE Connector architec- ture: • Java encoding schemes (Appendix A) • XML Standards (Appendix B) • HTTP overview (Appendix C) • J2EE Connector architecture (Appendix D) About the Examples This section tells you everything you need to know to install, build, and run the examples. Required Software Tutorial Bundle The tutorial example source is contained in the tutorial bundle. If you are view- ing this online, you need to download tutorial bundle from: http://java.sun.com/j2ee/1.4/download.html#tutorial After you have installed the tutorial bundle, the example source code is in the <INSTALL>/j2eetutorial14/examples/ directory, with subdirectories for each of the technologies discussed in the tutorial. Application Server The Sun Java System Application Server Platform Edition 8.2 is targeted as the build and runtime environment for the tutorial examples. To build, deploy, and http://java.sun.com/j2ee/1.4/download.html#tutorial xxxvii run the examples, you need a copy of the Application Server and the Java 2 Soft- ware Development Kit, Standard Edition (J2SE SDK) 1.4.2_06 or higher. If you already have a copy of the J2SE SDK, you can download the Application Server from: http://java.sun.com/j2ee/1.4/download.html#sdk You can also download the J2EE 1.4 SDK—which contains the Application Server and the J2SE SDK—from the same site. Application Server Installation Tips In the Admin configuration pane of the Application Server installer, • Select the Don’t Prompt for Admin User Name radio button. This will save the user name and password so that you won’t need to provide them when performing administrative operations with asadmin and deploytool. 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 ApplicationServer scripts (asadmin, asant, deploytool, and wscom- pile) override other installations. Registry Server You need a registry server to run the examples discussed in Chapters 10 and 35. Directions for obtaining and setting up a registry server are provided in those chapters. Building the Examples Most of the tutorial examples are distributed with a configuration file for asant, a portable build tool contained in the Application Server. This tool is an exten- sion of the Ant tool developed by the Apache Software Foundation http://java.sun.com/j2ee/1.4/download.html#sdk xxxviii (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. Build properties and targets common to all the examples are specified in the files <INSTALL>/j2eetutorial14/examples/common/build.properties and <INSTALL>/j2eetutorial14/examples/common/targets.xml. Build proper- ties and targets common to a particular technology are specified in the files <INSTALL>/j2eetutorial14/examples/tech/common/build.properties and <INSTALL>/j2eetutorial14/examples/tech/common/targets.xml. To run the asant scripts, you must set common build properties in the file <INSTALL>/j2eetutorial14/examples/common/build.properties as fol- lows: • Set the j2ee.home property to the location of your Application Server installation. The build process uses the j2ee.home property to include the libraries in <J2EE_HOME>/lib/ in the classpath. All examples that run on the Application Server include the J2EE library archive— <J2EE_HOME>/lib/j2ee.jar—in the build classpath. Some examples use additional libraries in <J2EE_HOME>/lib/ and <J2EE_HOME>/lib/endorsed/; the required libraries are enumerated in the individual technology chapters. <J2EE_HOME> refers to the directory where you have installed the Application Server or the J2EE 1.4 SDK. 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 Appli- cation Server installation is C:\Sun\AppServer, you must set j2ee.home as follows: j2ee.home = C:\\Sun\\AppServer or j2ee.home=C:/Sun/AppServer • Set the j2ee.tutorial.home property to the location of your tutorial. This property is used for asant deployment and undeployment. For example on Unix: j2ee.tutorial.home=/home/username/j2eetutorial14 http://ant.apache.org xxxix On Windows: j2ee.tutorial.home=C:/j2eetutorial14 You should 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 user’s password in <INSTALL>/j2eetutorial14/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 Structure To facilitate iterative development and keep application source separate from compiled files, the source code for the tutorial examples is stored in the follow- ing structure under each application directory: • build.xml: asant build file • src: Java source of servlets and JavaBeans components; tag libraries • web: JSP pages and HTML pages, tag files, and images The asant build files (build.xml) distributed with the examples contain targets to create a build subdirectory and to copy and compile files into that directory. Further Information This tutorial includes the basic information that you need to deploy applications on and administer the Application Server. For reference information on the tools distributed with the Application Server, see the man pages at http://docs.sun.com/db/doc/817-6092. http://docs.sun.com/db/doc/817-6092 xl See the Sun Java™ System Application Server Platform Edition 8 Developer’s Guide at http://docs.sun.com/db/doc/817-6087 for information about developer features of the Application Server. See the Sun Java™ System Application Server Platform Edition 8 Administra- tion Guide at http://docs.sun.com/db/doc/817-6088 for information about administering the Application Server. For information about the Derby database, which is included with Application Server 8.2, and the Pointbase database, which is included with Application Server 8.1, see the following web sites: • http://db.apache.org/derby • http://www.pointbase.com How to Buy This Tutorial This tutorial has been published in the Java Series by Addison-Wesley as The Java Tutorial, Second Edition. For information on the book and links to online booksellers, go to http://java.sun.com/docs/books/j2eetutorial/index.html#second How to Print This Tutorial To 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. http://docs.sun.com/db/doc/817-6088 http://db.apache.org/derby http://www.pointbase.com http://java.sun.com/docs/books/j2eetutorial/index.html#second http://docs.sun.com/db/doc/817-6087 J2EETutorial.pdf xli Typographical Conventions Table 2 lists the typographical conventions used in this tutorial. Menu selections indicated with the right-arrow character →, for example, First→Second, should be interpreted as: select the First menu, then choose Sec- ond from the First submenu. Acknowledgments The J2EE tutorial team would like to thank the J2EE specification leads: Bill Shannon, Pierre Delisle, Mark Roth, Yutaka Yoshida, Farrukh Najmi, Phil Good- win, Joseph Fialli, Kate Stout, and Ron Monzillo and the J2EE 1.4 SDK team members: Vivek Nagar, Tony Ng, Qingqing Ouyang, Ken Saks, Jean-Francois Arcand, Jan Luehe, Ryan Lubke, Kathy Walsh, Binod P G, Alejandro Murillo, and Manveen Kaur. The chapters on custom tags and the Coffee Break and Duke’s Bank applications use a template tag library that first appeared in Designing Enterprise Applica- tions with the J2EE™ Platform, Second Edition, Inderjeet Singh et al., (Addi- son-Wesley, 2002). The JavaServer Faces technology and JSP Documents chapters benefited greatly from the invaluable documentation reviews and example code contributions of these engineers: Ed Burns, Justyna Horwat, Roger Kitain, Jan Luehe, Craig McClanahan, Raj Premkumar, Mark Roth, and especially Jayashri Visvanathan. Table 2 Typographical Conventions Font Style Uses italic Emphasis, titles, first occurrence of terms monospace URLs, code examples, file names, path names, tool names, application names, programming language keywords, tag, interface, class, method, and field names, properties italic monospace Variables in code, file paths, and URLs <italic monospace> User-selected file path components xlii The OrderApp example application described in the Container-Managed Persis- tence chapter was coded by Marina Vatkina with contributions from Markus Fuchs, Rochelle Raccah, and Deepa Singh. Ms. Vatkina’s JDO/CMP team pro- vided extensive feedback on the tutorial’s discussion of CMP. The security chapter writers are indebted to Raja Perumal, who was a key con- tributor both to the chapter and to the examples. Monica Pawlan and Beth Stearns wrote the Overview and J2EE Connector chap- ters in the first edition of The J2EE Tutorial and much of that content has been carried forward to the current edition. We are extremely grateful to the many internal and external reviewers who pro- vided feedback on the tutorial. Their feedback helped improve the technical accuracy and presentation of the chapters and eliminate bugs from the examples. We would like to thank our manager, Alan Sommerer, for his support and steadying influence. We also thank Duarte Design, Inc.,and Zana Vartanian for developing the illus- trations in record time. Thanks are also due to our copy editor, Betsy Hardinger, for helping this multi-author project achieve a common style. Finally, we would like to express our profound appreciation to Ann Sellers, Eliz- abeth Ryan, and the production team at Addison-Wesley for graciously seeing our large, complicated manuscript to publication. Feedback To send comments, broken link reports, errors, suggestions, and questions about this tutorial to the tutorial team, please use the feedback form at http://java.sun.com/j2ee/1.4/docs/tutorial/information/sendus- mail.html. http://java.sun.com/j2ee/1.4/docs/tutorial/information/sendusmail.html http://java.sun.com/j2ee/1.4/docs/tutorial/information/sendusmail.html 1 1 Overview TODAY, more and more developers want to write distributed transactional applications for the enterprise and thereby leverage the speed, security, and reli- ability of server-side technology. If you are already working in this area, you know that in the fast-moving and demanding world of e-commerce and informa- tion technology, enterprise applications must be designed, built, and produced for less money, with greater speed, and with fewer resources than ever before. To reduce costs and fast-track application design and development, the 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 unified security model, flexible transaction control, and web ser- vices support through integrated data interchange on Extensible Markup Lan- guage (XML)-based open standards and protocols. Not only can you deliver innovative business solutions to market faster than ever, but also your platform-independent J2EE component-based solutions are not tied to the products and application programming interfaces (APIs) of any one ven- dor. Vendors and customers enjoy the freedom to choose the products and com- ponents that best meet their business and technological requirements. This tutorial uses examples to describe the features and functionalities available in the J2EE platform version 1.4 for developing enterprise applications. Whether you are a new or an experienced developer, you should find the examples and accompanying text a valuable and accessible knowledge base for creating your own solutions. 2 If you are new to J2EE enterprise application development, this chapter is a good place to start. Here you will review development basics, learn about the J2EE architecture and APIs, become acquainted with important terms and concepts, and find out how to approach J2EE application programming, assembly, and deployment. Distributed Multitiered Applications The J2EE platform uses a distributed multitiered application model for enter- prise applications. Application logic is divided into components according to function, and the various application components that make up a J2EE applica- tion are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. Figure 1–1 shows two multitiered J2EE applications divided into the tiers described in the following list. The J2EE application parts shown in Figure 1–1 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 Fig- ure 1–1, J2EE multitiered applications are generally considered to be three- tiered applications because they are distributed over three 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 two- tiered client and server model by placing a multithreaded application server between the client application and back-end storage. DISTRIBUTED MULTITIERED APPLICATIONS 3 Figure 1–1 Multitiered Applications J2EE Components J2EE applications are made up of components. A J2EE component is a self-con- tained functional software unit that is assembled into a J2EE application with its related classes and files and that communicates with other components. The J2EE specification defines 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 busi- ness components that run on the server. J2EE components are written in the Java programming language and are com- piled 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, are verified to be well formed and in compli- ance with the J2EE specification, and are deployed to production, where they are run and managed by the J2EE server. 4 J2EE Clients A J2EE client can be a web client or an application client. Web Clients A 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 enter- prise beans executing on the J2EE server, where they can leverage the security, speed, services, and reliability of J2EE server-side technologies. Applets A 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 under- stand Java programming language syntax to do their jobs. Application Clients An application client runs on a client machine and provides a way for users to handle tasks that require a richer user interface than can be provided by a markup language. It typically has a graphical user interface (GUI) created from the Swing or the Abstract Window Toolkit (AWT) API, but a command-line inter- face is certainly possible. DISTRIBUTED MULTITIERED APPLICATIONS 5 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. The JavaBeans™ Component Architecture The server and client tiers might also include components based on the Java- Beans component architecture (JavaBeans components) to manage the data flow 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 specification. JavaBeans components have properties and have get and set methods for accessing the properties. JavaBeans components usedin 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 Communications Figure 1–2 shows the various elements that can make up the client tier. The cli- ent 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 cli- ent. 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. 6 Figure 1–2 Server Communications Web Components J2EE web components are either servlets or pages created using JSP technology (JSP pages). Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static con- tent. Static HTML pages and applets are bundled with web components during appli- cation assembly but are not considered web components by the J2EE specifica- tion. Server-side utility classes can also be bundled with web components and, like HTML pages, are not considered web components. As shown in Figure 1–3, the web tier, like the client tier, might include a Java- Beans component to manage the user input and send that input to enterprise beans running in the business tier for processing. Business Components Business code, which is logic that solves or meets the needs of a particular busi- ness domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. Figure 1–4 shows how an enterprise bean receives data from client programs, processes it (if necessary), and sends it to the enter- DISTRIBUTED MULTITIERED APPLICATIONS 7 prise 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 1–3 Web Tier and J2EE Applications Figure 1–4 Business and EIS Tiers There are three kinds of enterprise beans: session beans, entity beans, and mes- sage-driven beans. A session bean represents a transient conversation with a cli- ent. When the client finishes executing, the session bean and its data are gone. In contrast, an entity bean represents persistent data stored in one row of a database 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 fea- 8 tures of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS messages asynchronously. Enterprise Information System Tier The enterprise information system tier handles EIS software and includes enter- prise infrastructure systems such as enterprise resource planning (ERP), main- frame transaction processing, database systems, and other legacy information systems. For example, J2EE application components might need access to enter- prise information systems for database connectivity. J2EE Containers Normally, thin-client multitiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling, and other complex low-level details. The com- ponent-based and platform-independent J2EE architecture makes J2EE applica- tions easy to write because business logic is organized into reusable components. In addition, the J2EE server provides underlying services in the form of a con- tainer for every component type. Because you do not have to develop these ser- vices yourself, you are free to concentrate on solving the business problem at hand. Container Services Containers are the interface between a component and the low-level platform- specific functionality that supports the component. Before a web component, enterprise bean, or application client component can be executed, it must be assembled into a J2EE module 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, including ser- vices such as security, transaction management, Java Naming and Directory J2EE CONTAINERS 9 Interface™ (JNDI) lookups, and remote connectivity. Here are some of the high- lights: • The J2EE security model lets you configure 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 unified 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. Because the J2EE architecture provides configurable services, application com- ponents 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 environ- ment 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 J2EE platform APIs described in section J2EE 1.4 APIs (page 18). Although data persistence is a nonconfigurable 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 finder (search) methods or to create a customized database cache. Container Types The deployment process installs J2EE application components in the J2EE con- tainers illustrated in Figure 1–5. 10 Figure 1–5 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 appli- cations. 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 Plug- in running on the client together. Web Services Support Web services are web-based enterprise applications that use open, XML-based standards and transport protocols to exchange data with calling clients. The J2EE WEB SERVICES SUPPORT 11 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. Towrite 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 docu- ment-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 fol- lowing 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 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. XML XML 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 exam- ples: • 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 appli- cation for processing. 12 SOAP Transport Protocol Client requests and web service responses are transmitted as Simple Object Access Protocol (SOAP) messages over HTTP to enable a completely interoper- able exchange between clients and web services, all running on different plat- forms and at various locations on the Internet. HTTP is a familiar request-and response standard for sending messages over the Internet, and SOAP is an XML- based protocol that follows the HTTP request-and-response model. The SOAP portion of a transported message 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 application- defined data types within the message • Defines an XML-based convention for representing the request to the remote service and the resulting response WSDL Standard Format The Web Services Description Language (WSDL) is a standardized XML format for describing network services. The description includes the name of the ser- vice, the location of the service, and ways to communicate with the service. WSDL service descriptions can be stored in 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 Formats Other XML-based standards, such as Universal Description, Discovery and Inte- gration (UDDI) and ebXML, make it possible for businesses to publish informa- tion 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. PACKAGING APPLICATIONS 13 Packaging Applications A J2EE 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 J2EE applications using some of the same components. No extra coding is needed; it is only a matter of assembling (or packaging) various J2EE modules into J2EE EAR files. An EAR file (see Figure 1–6) contains J2EE modules and deployment descrip- tors. 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 J2EE server reads the deployment descriptor and acts upon the application, module, or component accordingly. There are two types of deployment descriptors: J2EE and runtime. A J2EE deployment descriptor is defined by a J2EE specification and can be used to con- figure deployment settings on any J2EE-compliant implementation. A runtime deployment descriptor is used to configure J2EE implementation-specific parameters. For example, the Sun Java System Application Server Platform Edi- tion 8 runtime deployment descriptor contains information such as the context root of a web application, the mapping of portable names of an application’s resources to the server’s resources, and Application Server implementation-spe- cific 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 J2EE deployment descriptor. 14 Figure 1–6 EAR File Structure A J2EE module consists of one or more J2EE 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 J2EE module without an appli- cation deployment descriptor can be deployed as a stand-alone module. The four types of J2EE 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) exten- sion. • 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 architec- ture (see J2EE Connector Architecture, page 22) for a particular EIS. Resource adapter modules are packaged as JAR files with an .rar (resource adapter archive) extension. DEVELOPMENT ROLES 15 Development Roles Reusable 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 J2EE product and tools. After 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 file that is the input for a sub- sequent 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 J2EE application and saves it in an EAR file. In the application deployment role, a sys- tem administrator at the customer site uses
Compartir