THEJ2EE Tutorial

Transcription

THETMJ2EE Tutorial

TMTHEJ2EE TutorialStephanie BodoffDale GreenKim HaaseEric JendrockMonica PawlanBeth StearnsBostonSan Francisco New York Toronto MontrealLondon Munich Paris MadridCapetown Sydney Tokyo Singapore Mexico City

Copyright 2002 Sun Microsystems, Inc. 901 San Antonio Road, Palo Alto, CA 94303 USA.All rights reserved.Duke logo designed by Joe Palrang.Sun, Sun Microsystems, Sun logo, Java, JDBC, JavaBeans, Enterprise JavaBeans, JavaServer Pages,J2EE, J2SE, JavaMail, Java Naming and Directory Interface, EJB, and JSP are trademarks or registeredtrademarks of Sun Microsystems, Inc. UNIX is a registered trademark in the United States and othercountries, exclusively licensed through X/Open Company, Ltd. .THIS PUBLICATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND,EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, ORNON-INFRINGEMENT.THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OFTHE PUBLICATION. SUN MICROSYSTEMS, INC., MAY MAKE IMPROVEMENTSAND/OR CHANGES IN ANY TECHNOLOGY, PRODUCT, OR PROGRAM DESCRIBEDIN THIS PUBLICATION AT ANY TIME.Pearson Education Corporate Sales DivisionOne Lake StreetUpper Saddle River, NJ 07458(800) 382-3419corpsales@pearsontechgroup.comVisit Addison-Wesley on the Web: www.aw.com/cseng/Library of Congress Control Number: 2002102527All rights reserved. No part of this publication may be reproduced, stored in a retrieval system,or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording,or otherwise, without the prior consent of the publisher. Printed in the United States of America.Published simultaneously in Canada.ISBN 0-201-79168-4Text printed on recycled paper1 2 3 4 5 6 7 8 9 10—MA—0605040302First printing, March 2002

ContentsForeword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviiPreface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxiChapter 1:Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Distributed Multitiered ApplicationsJ2EE ComponentsJ2EE ClientsWeb ComponentsBusiness ComponentsEnterprise Information System TierJ2EE ContainersContainer ServicesContainer TypesPackagingDevelopment RolesJ2EE Product ProviderTool ProviderApplication Component ProviderApplication AssemblerApplication Deployer and AdministratorReference Implementation SoftwareDatabase AccessJ2EE APIsSimplified Systems IntegrationTools234668889101112121213141415151819v

viCONTENTSChapter 2:Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21Setting UpGetting the Example CodeGetting the Build Tool (ant)Checking the Environment VariablesStarting the J2EE ServerStarting the deploytoolCreating the J2EE ApplicationCreating the Enterprise BeanCoding the Enterprise BeanCompiling the Source FilesPackaging the Enterprise BeanCreating the J2EE Application ClientCoding the J2EE Application ClientCompiling the Application ClientPackaging the J2EE Application ClientSpecifying the Application Client’s Enterprise Bean ReferenceCreating the Web ClientCoding the Web ClientCompiling the Web ClientPackaging the Web ClientSpecifying the Web Client’s Enterprise Bean ReferenceSpecifying the JNDI NamesDeploying the J2EE ApplicationRunning the J2EE Application ClientRunning the Web ClientModifying the J2EE ApplicationModifying a Class FileAdding a FileModifying the Web ClientModifying a Deployment SettingCommon Problems and Their SolutionsCannot Start the J2EE ServerCompilation ErrorsDeployment ErrorsJ2EE Application Client Runtime ErrorsWeb Client Runtime ErrorsDetecting Problems With the Verifier ToolComparing Your EAR Files with OursWhen All Else 737383939393940404041424344454545

viiCONTENTSChapter 3:Enterprise Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47What Is an Enterprise Bean?Benefits of Enterprise BeansWhen to Use Enterprise BeansTypes of Enterprise BeansWhat Is a Session Bean?State Management ModesWhen to Use Session BeansWhat Is an Entity Bean?What Makes Entity Beans Different from Session Beans?Container-Managed PersistenceWhen to Use Entity BeansWhat Is a Message-Driven Bean?What Makes Message-Driven Beans Different from Sessionand Entity Beans?When to Use Message-Driven BeansDefining Client Access with InterfacesRemote AccessLocal AccessLocal Interfaces and Container-Managed RelationshipsDeciding on Remote or Local AccessPerformance and AccessMethod Parameters and AccessThe Contents of an Enterprise BeanNaming Conventions for Enterprise BeansThe Life Cycles of Enterprise BeansThe Life Cycle of a Stateful Session BeanThe Life Cycle of a Stateless Session BeanThe Life Cycle of an Entity BeanThe Life Cycle of a Message-Driven BeanChapter 63646567A Session Bean Example . . . . . . . . . . . . . . . . . . . . . 69The CartEJB ExampleSession Bean ClassHome InterfaceRemote InterfaceHelper ClassesRunning the CartEJB ExampleOther Enterprise Bean FeaturesAccessing Environment EntriesComparing Enterprise BeansPassing an Enterprise Bean’s Object Reference70707476767678788080

viiiCONTENTSChapter 5:Bean-Managed Persistence Examples. . . . . . . . . .83The SavingsAccountEJB ExampleEntity Bean ClassHome InterfaceRemote InterfaceRunning the SavingsAccountEJB Exampledeploytool Tips for Entity Beans withBean-Managed PersistenceMapping Table Relationships for Bean-Managed PersistenceOne-to-One RelationshipsOne-to-Many RelationshipsMany-to-Many RelationshipsPrimary Keys for Bean-Managed PersistenceThe Primary Key ClassPrimary Keys in the Entity Bean ClassGetting the Primary KeyHandling ExceptionsChapter anaged Persistence Examples . . . .119Overview of the RosterApp ApplicationThe PlayerEJB CodeEntity Bean ClassLocal Home InterfaceLocal InterfaceA Guided Tour of the RosterApp d Invocations in RosterAppCreating a PlayerAdding a Player to a TeamRemoving a PlayerDropping a Player from a TeamGetting the Players of a TeamGetting a Copy of a Team’s PlayersFinding the Players by PositionGetting the Sports of a PlayerRunning the RosterApp ExampleSetting UpDeploying the ApplicationRunning the 0141142144145147147147148

ixCONTENTSdeploytool Tips for Entity Beans withContainer-Managed PersistenceSpecifying the Bean’s TypeSelecting the Persistent Fields and Abstract Schema NameDefining EJB QL Queries for Finder and Select MethodsGenerating SQL and Specifying Table CreationSpecifying the Database JNDI Name, User Name,and PasswordDefining RelationshipsPrimary Keys for Container-Managed PersistenceThe Primary Key ClassPrimary Keys in the Entity Bean ClassGenerating Primary Key ValuesChapter 7:150150151151152153A Message-Driven Bean Example . . . . . . . . . . . . 155Example Application OverviewThe J2EE Application ClientThe Message-Driven Bean ClassThe onMessage MethodThe ejbCreate and ejbRemove MethodsRunning the SimpleMessageEJB ExampleStarting the J2EE ServerCreating the QueueDeploying the ApplicationRunning the Clientdeploytool Tips for Message-Driven BeansSpecifying the Bean’s Type and Transaction ManagementSetting the Message-Driven Bean’s Characteristicsdeploytool Tips for JMS ClientsSetting the Resource ReferencesSetting the Resource Environment ReferencesSpecifying the JNDI NamesChapter 161161162162163163Enterprise JavaBeans Query Language . . . . . . . 165TerminologySimplified Syntax166167

xCONTENTSExample QueriesSimple Finder QueriesFinder Queries That Navigate to Related BeansFinder Queries with Other Conditional ExpressionsSelect QueriesFull SyntaxBNF SymbolsBNF Grammar of EJB QLFROM ClausePath ExpressionsWHERE ClauseSELECT ClauseEJB QL RestrictionsChapter 9:167167169170172173173173176179182190191Web Clients and Components. . . . . . . . . . . . . . . .193Web Client Life CycleWeb Application ArchivesCreating a WAR FileAdding a WAR File to an EAR FileAdding a Web Component to a WAR FileConfiguring Web ClientsApplication-Level ConfigurationWAR-Level ConfigurationComponent-Level ConfigurationDeploying Web ClientsRunning Web ClientsUpdating Web ClientsInternationalizing Web ter 10: Java Servlet Technology . . . . . . . . . . . . . . . . . . . .209What Is a Servlet?The Example ServletsTroubleshootingServlet Life CycleHandling Servlet Life-Cycle EventsHandling ErrorsSharing InformationUsing Scope ObjectsControlling Concurrent Access to Shared ResourcesAccessing DatabasesInitializing a Servlet210211215216216218218219220221222

xiCONTENTSWriting Service MethodsGetting Information from RequestsConstructing ResponsesFiltering Requests and ResponsesProgramming FiltersProgramming Customized Requests and ResponsesSpecifying Filter MappingsInvoking Other Web ResourcesIncluding Other Resources in the ResponseTransferring Control to Another Web ComponentAccessing the Web ContextMaintaining Client StateAccessing a SessionAssociating Attributes with a SessionSession ManagementSession TrackingFinalizing a ServletTracking Service RequestsNotifying Methods to Shut DownCreating Polite Long-Running 39240241242242243Chapter 11: JavaServer Pages Technology . . . . . . . . . . . . . . . 245What Is a JSP Page?The Example JSP PagesThe Life Cycle of a JSP PageTranslation and CompilationExecutionInitializing and Finalizing a JSP PageCreating Static ContentCreating Dynamic ContentUsing Objects within JSP PagesJSP Scripting ElementsIncluding Content in a JSP PageTransferring Control to Another Web ComponentParam ElementIncluding an AppletExtending the JSP 267Chapter 12: JavaBeans Components in JSP Pages . . . . . . . . . 269JavaBeans Component Design ConventionsWhy Use a JavaBeans Component?270271

xiiCONTENTSCreating and Using a JavaBeans ComponentSetting JavaBeans Component PropertiesRetrieving JavaBeans Component Properties272273275Chapter 13: Custom Tags in JSP Pages . . . . . . . . . . . . . . . . . . .279What Is a Custom Tag?The Example JSP PagesUsing TagsDeclaring Tag LibrariesTypes of TagsDefining TagsTag HandlersTag Library DescriptorsSimple TagsTags with AttributesTags With BodiesTags That Define Scripting VariablesCooperating TagsExamplesAn Iteration TagA Template Tag LibraryHow Is a Tag Handler 304308313Chapter 14: Transactions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .315What Is a Transaction?Container-Managed TransactionsTransaction AttributesRolling Back a Container-Managed TransactionSynchronizing a Session Bean’s Instance VariablesMethods Not Allowed in Container-Managed TransactionsBean-Managed TransactionsJDBC TransactionsJTA TransactionsReturning without CommittingMethods Not Allowed in Bean-Managed TransactionsSummary of Transaction Options for Enterprise BeansTransaction TimeoutsIsolation LevelsUpdating Multiple DatabasesTransactions in Web 28329331

xiiiCONTENTSChapter 15: Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333OverviewSecurity RolesDeclaring and Linking Role ReferencesMapping Roles to J2EE Users and GroupsWeb-Tier SecurityProtecting Web ResourcesControlling Access to Web ResourcesAuthenticating Users of Web ResourcesUsing Programmatic Security in the Web TierUnprotected Web ResourcesEJB-Tier SecurityDeclaring Method PermissionsUsing Programmatic Security in the EJB TierUnprotected EJB-Tier ResourcesApplication Client-Tier SecuritySpecifying the Application Client’s Callback HandlerEIS-Tier SecurityConfiguring Sign-OnContainer-Managed Sign-OnComponent-Managed Sign-OnConfiguring Resource Adapter SecurityPropagating Security IdentityConfiguring a Component’s Propagated Security IdentityConfiguring Client AuthenticationJ2EE Users, Realms, and GroupsManaging J2EE Users and GroupsSetting Up a Server 342342343343344344344345346346347348349350Chapter 16: Resource Connections . . . . . . . . . . . . . . . . . . . . . 353JNDI Names and Resource Referencesdeploytool Tips for Resource ReferencesDatabase Connections for Enterprise BeansCoded ConnectionsConnection PoolingMail Session ConnectionsRunning the ConfirmerEJB ExampleURL ConnectionsRunning the HTMLReaderEJB Example354354357357359359361362363

xivCONTENTSChapter 17: J2EE Connector Architecture . . . . . . . . . . . . . . . . .365About Resource AdaptersResource Adapter ContractsAdministering Resource AdaptersThe Black Box Resource AdaptersTransaction LevelsPropertiesConfiguring JDBC DriversResource Adapter TutorialSetting UpDeploying the Resource AdapterTesting the Resource AdapterCommon Client InterfaceOverview of the CCIProgramming with the CCIWriting a CCI ClientCCI 385386Chapter 18: The Duke’s Bank Application . . . . . . . . . . . . . . . . .391Enterprise BeansSession BeansEntity BeansHelper ClassesDatabase TablesProtecting the Enterprise BeansApplication ClientThe Classes and Their RelationshipsBankAdmin ClassEventHandle ClassDataModel ClassWeb ClientDesign StrategiesWeb Client Life CycleProtecting the Web 401403404405408409410414414

xvCONTENTSBuilding, Packaging, Deploying, and Running the ApplicationAdding Groups and Users to the RealmStarting the J2EE Server, deploytool, and DatabaseCompiling the Enterprise BeansPackaging the Enterprise BeansCompiling the Web ClientPackaging the Web ClientCompiling the J2EE Application ClientPackaging the J2EE Application ClientPackaging the Enterprise Archive FileOpening the Enterprise Archive FileReviewing JNDI NamesMapping the Security Roles to GroupsDeploying the Duke’s Bank ApplicationCreating the Bank DatabaseRunning the J2EE Application ClientRunning the Web 4424425Appendix A: HTTP Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427HTTP RequestsHTTP Responses428428Appendix B: J2EE SDK Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429J2EE Administration ToolCleanup ToolCloudscape ServerStarting CloudscapeStopping CloudscapeRunning the Interactive SQL ToolCloudscape Server ConfigurationDeployment ToolJ2EE ServerKey ToolPackager ToolEJB JAR FileWeb Application WAR FileApplication Client JAR FileJ2EE Application EAR FileSpecifying the Runtime Deployment DescriptorResource Adapter RAR 38439

xviCONTENTSRealm ToolExamplesrunclient ScriptSyntaxExampleAccessing a Remote ServerPreventing the User Name and Password PromptsVerifier ToolCommand-Line VerifierStand-Alone GUI Verifier440440441441442442443443443444Appendix C: Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .445Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .449About the Authors . . . . . . . . . . . . . . . . . . . . . . . . . .473Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .475

ForewordI joined Sun—actually, a small Sun spin-off called FirstPerson—in August1993. I knew about the company because a few of my favorite coworkers had leftNeXT to work at FirstPerson. But my main reason for joining was that I lovedthe cartoony user interfaces FirstPerson was developing, interfaces that featureda character nicknamed Duke.1Figure F–1 Duke, the Unofficial Mascot of the Java PlatformFirstPerson’s first demo, called Star 7, was a household remote control with asmall touchscreen. By the time I arrived, they were working on a demo for videoon demand.The wonderfully loony animation for the video-on-demand demo was created bya San Francisco studio called Colossal Pictures (where, incidentally, my husbandhad gotten his start in the animation industry). Both demos were written using aprogramming language that was then called Oak.My first task was to help the creator of the Oak language, James Gosling, writethe language specification. What I really wanted to do, though, was to write taskoriented documentation aimed at ordinary programmers.1You can get more information about Duke in the article “It’s Duke’s Birthday, html.xvii

xviiiFOREWORDBy July 1994, FirstPerson was in turmoil, having failed to convince cable companies that their video-on-demand solution was what customers needed. I stayedat the company only because I was about to go on maternity leave.Programming for the InternetWhen I returned to work in the fall of 1994, the company’s dynamic and visionhad completely changed. They had decided that the Oak language—with its ability to produce platform-independent, secure, easily transported code—was idealfor the Internet. And they were creating a Web browser called WebRunner thatshowcased the ability to deliver Oak code, packaged in a form they calledapplets, over the Internet.I set to work writing a guide to help people write and use applets. When theWebRunner browser was first released in early 1995, the guide was part of thesmall set of documentation included with the browser. That guide was the granddaddy of The J2EE Tutorial.The guide was the first documentation to include applets. It looked somewhatsimilar to The Java Tutorial, and in fact The Java Tutorial probably still hassome of the text originally published in the guide. Because we had no HTMLtools, however, I had to generate the guide completely by hand. Let me tell you,hand coding navigation links for a document in progress is not fun, even for asmall document. Much less painful was making name changes: The languagename changed from Oak to Java , and the name of the browser from WebRunner to HotJava.Mary Enters the PictureIn early 1995, we hired a contract writer named Mary Campione. She and I knewof each other from her time in NeXT developer support. Mary’s job was to helpprogrammers use platform features such as threads. We soon realized that ourwork was too similar for us to do it separately, and we started working togetheron a programmer’s guide for the Java platform.On May 18, 1995, Mary Campione and I released the first version of our guide,which we called The Java Programmer’s Guide. It was an incomplete firstdraft—nothing pretty—but it provided people with the information they neededto get started programming for the Java platform.

FOREWORDThe next week, Sun officially announced the Java platform at a show called SunWorld. The best part of the show for us was the announcement that Netscape hadagreed (just hours before) to support applets in their Web browser.In the following months, Mary and I continued to add to and refine our programmer’s guide.2 We worked together closely, sharing the same office and even thesame train commute from San Francisco to Palo Alto. By coincidence, we evengot pregnant within days of each other.By late 1995, the first wave of books in The Java Series was being developed.The Java Series was a group of books published by Addison-Wesley and writtenmainly by employees of what used to be FirstPerson. By that time, FirstPersonhad been absorbed back into Sun, in the form of a division called JavaSoft. TheSeries Editor was JavaSoft technical publications manager Lisa Friendly.3Our programmer’s guide was slated to be one of the books in The Java Series,but the publisher wanted it to have a less intimidating name. So we changed itsname to The Java Tutorial. There we were, two increasingly large womenworking insanely long hours to finish the book before the babies arrived in mid1996. We managed—just barely—to get the book to our publisher in time. Wecouldn’t have done it without the help of yet another ex-NeXTer, Randy Nelson,who took care of all the final details of the book and Web site.The Tutorial Team GrowsWhen Mary and I returned from maternity leave, we felt completely overwhelmed. Our book and Web site covered the 1.0 version of the Java platform(JDK 1.0), but JDK 1.1 was scheduled to be released soon and work had alreadystarted on JDK 1.2 (which would be renamed to the Java 2 Platform, StandardEdition, Version 1.2—J2SE v 1.2, for short). We would be able to update ourexisting documentation to 1.1, but for 1.2 we’d need help.Help arrived in the form of guest authors and Alison Huml. The guest authorswere writers and engineers on the teams developing the new 1.2 features. Alisonwas a postgraduate student with experience in both software and publishing. Shedid whatever was necessary to make the Tutorial succeed, ranging from producing camera-ready copy for books to writing text and examples.2By looking at n/history.html, you can see what was in each of our updates.3 Lisa has some great anecdotes about the early days of FirstPerson. You can read some ofthem at .xix

xxFOREWORDBetween 1998 and 2000, the Tutorial team updated the Web site many times andproduced two completely new books, as well as two major revisions of the original book. In mid-2000, Mary retired from paid work. Alison and I still work onThe Java Tutorial, in both its Web and book forms. Although we rely on guestauthors from time to time, the rate of change has become less frantic as the J2SEplatform matures.The J2EE TutorialNow there’s a new platform—and a new tutorial—in town. The success of theJava 2 Platform, Enterprise Edition (J2EE ) has been phenomenal. Developersare clamoring for information about how to write applications using this newJava platform for the server. And this book helps, continuing the tradition of TheJava Tutorial, but this time for the J2EE platform. Like the original Tutorial,this is an example-filled, easy-to-use entry point and quick reference for programming with the J2EE platform. And I’m sure, like the original tutorial team,Stephanie, Dale, Eric, Kim, and Beth all have stories to tell about the timethey’ve spent working on the J2EE platform and bringing you this book.Just a note—Because the J2EE platform sits on top of the J2SE platform, youneed to be comfortable writing programs for the J2SE platform before you canmake full use of this book. If you’re not comfortable with the J2SE platform, goto The Java Tutorial4 and learn!Then come back here, so you can find out all about developing and deployingapplications for the J2EE platform.Kathy WalrathSun MicrosystemsSan Francisco, CADecember 21, 20014On the Web at http://java.sun.com/docs/books/tutorial/, or in book form asThe Java Tutorial: A Short Course on the Basics.

PrefaceThe Java Tutorial has been an indispensable resource for many programmers learning the Java programming language. This tutorial hopes to serve thesame role for developers encountering the Java 2 Platform, Enterprise Edition(J2EE ) for the first time. It follows an example-oriented focus similar to TheJava Tutorial.Who Should Use This TutorialThis tutorial is intended for programmers interested in developing and deployingJ2EE applications. It covers the technologies comprising the J2EE platform anddescribes how to develop J2EE components and deploy them on the J2EE Software Development Kit (SDK).This tutorial is not intended for J2EE server or tool vendors. It does not explainhow to implement the J2EE architecture, nor does it explain the internals of theJ2EE SDK. The J2EE specifications describe the J2EE architecture and can bedownloaded fromhttp://java.sun.com/j2ee/docs.html#specsAbout the ExamplesThis tutorial includes many complete, working examples. SeeExamples (page 445) for a list of the examples and the chapters where theyappear.xxi

xxiiPREFACEPrerequisites 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 TheJava Tutorial listed in Table P–1 are particularly relevant.Table P–1 Prerequisite TopicsTopicJava TutorialJDBC /threadsJavaBeans urity1.2Downloading the ExamplesIf you are viewing this online and you want to build and run the examples, youneed to download the tutorial bundle lOnce you have installed the bundle, the example source code is in thej2eetutorial/examples/src directory, with subdirectories ejb for enterprisebean technology examples, web for Web technology examples, and connectorfor connector technology examples. For most of the examples, the bundle alsoincludes J2EE application Enterprise Archive (EAR) files, which are located inthe j2eetutorial/examples/ears directory.How to Build and Run the ExamplesThis tutorial documents the J2EE SDK version 1.3. To build, deploy, and run theexamples you need a copy of the J2EE SDK 1.3 and the Java 2 Platform, Standard Edition (J2SE ) SDK 1.3.1 (earlier versions were called JDK). You candownload the J2EE SDK fromhttp://java.sun.com/j2ee/download.html#sdk

PREFACExxiiiand the J2SE 1.3.1 fromhttp://java.sun.com/j2se/1.3/The examples are distributed with a configuration file for version 1.3 of ant, aportable make tool. The ant utility is hosted by the Jakarta project at the ApacheSoftware Foundation. You can download ant elease/v1.3/binTo build the tutorial examples, follow these steps:1. Download and install the J2SE SDK 1.3.1, J2EE SDK 1.3, and ant.2. The installation instructions for the J2SE SDK, J2EE SDK, and antexplain how to set the required environment variables. Verify that the environment variables have been set to the values noted in the Table P–2.Table P–2 Settings for Environment VariablesEnvironment VariableValueJAVA HOMEThe location of the J2SE SDK installation.J2EE HOMEThe location of the J2EE SDK installation.ANT HOMEThe location of the ant installation.PATHShould include the bin directories of the J2EE SDK, J2SE SDK, andant installations.3. Go to the j2eetutorial/examples directory.4. Execute ant target. For example, to build all the examples, execute antall; to build the Web layer examples, execute ant web. The build processdeposits the output into the directory j2eetutorial/examples/build.

xxivPREFACERelated InformationThis tutorial provides a concise overview of how to use the central componenttechnologies in the J2EE platform. For more information about these technologies, see the Web sites listed in Table P–3.Table P–3 Information SourcesComponent TechnologyWeb SiteEnterprise JavaBeans (EJB )http://java.sun.com/products/ejbJava rver Pages (JSP )http://java.sun.com/products/jspThe J2EE platform includes a wide variety of APIs that this tutorial only brieflytouches on. Some of these technologies have their own tutorials, which are listedin Table P–4.Table P–4 Other TutorialsAPITutorialJava Message Service a Naming and DirectoryInterface ava API for XML 1.1/docs/tutorial/index.html

PREFACEFor complete information on these topics, see the Web sites listed in Table P–5.Table P–5 Other Web SitesAPIWeb SiteJ2EE p://java.sun.com/products/jaxpJavaMail ucts/jndiJDBC http://java.sun.com/products/jdbcOnce you have become familiar with the J2EE technologies described in thistutorial, you may be interested in guidelines for architecting J2EE applications.The Java BluePrints illustrate best practices for developing and deploying J2EEapplications. You can obtain the Java BluePrints fromhttp://java.sun.com/blueprintsHow to Print This TutorialTo print this tutorial, follow these steps:1. Ensure that Adobe Acrobat Reader is installed on your system.2. Download the PDF version of this book l3. Click the printer icon in Adobe Acrobat Reader.xxv

xxviPREFACETypographical ConventionsTable P–6 lists the typographical conventions used in this tutorial.Table P–6 Typographical ConventionsFont StyleUsesItalicEmphasis, titles, first occurrence of termsMonospaceURLs, code examples, file names, commandnames, programming language keywordsItalic monospaceProgramming variables, variable file namesMenu selections indicated with the right-arrow character , for example,First Second, should be interpreted as: select the First menu, then choose Second from the First submenu.AcknowledgmentsThe J2EE tutorial team would like to thank the J2EE SDK team for their technical advice.We are extremely grateful to the many internal and external reviewers who provided feedback on the tutorial. This helped us to improve the presentation, correct errors, and eliminate bugs.We would also like to thank our manager, Jim Inscore, for his support andsteadying influence.The chapters on Web components use an example and some material that firstappeared in the servlet trail of The Java Tutorial. The chapters on custom tagsand the Duke’s Bank application use a template tag library that first appeared inthe Java BluePrints.

1OverviewMonica PawlanTODAY, more and more developers want to write distributed transactionalapplications for the enterprise and leverage the spe

Sun, Sun Microsystems, Sun logo, Java, JDBC, JavaBeans, Enterprise JavaBeans, JavaServer Pages, . Programming Filters 229 Programming Customized Requests and Responses 230 Specifying Filter Mappings 232 Invoking Other Web Re