Docstoc

The J2EE Tutorial

Document Sample
The J2EE Tutorial Powered By Docstoc
					The J2EETM Tutorial

           Stephanie Bodoff
                Dale Green
                 Kim Haase
              Eric Jendrock
             Monica Pawlan
               Beth Stearns




             January 24, 2002
Copyright © 2002 by Sun Microsystems, Inc.
901 San Antonio Road, Palo Alto, California 94303 U.S.A.
All rights reserved.

RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Government is
subject to the restrictions set forth in DFARS 252.227-7013(c)(1)(iii) and FAR 52.227-19.
The release described in this book may be protected by one or more U.S. patents, foreign patents, or
pending applications.
Sun, Sun Microsystems, Sun Microsystems Computer Corporation, the Sun logo, the Sun Microsystems
Computer Corporation logo, Java, JavaSoft, Java Software, JavaScript, JDBC, JDBC Compliant, Jav-
aOS, JavaBeans, Enterprise JavaBeans, JavaServer Pages, J2EE, J2SE, JavaMail, Java Naming and
Directory Interface, EJB, and JSP are trademarks or registered trademarks of Sun Microsystems, Inc.
UNIX® is a registered trademark in the United States and other countries, exclusively licensed through
X/Open Company, Ltd. All other product names mentioned herein are the trademarks of their respective
owners.
THIS PUBLICATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-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 OF THE PUBLICATION. SUN
MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PROD-
UCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.
                                                   Contents
             Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

             Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxi

Chapter 1:   Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
             Distributed Multitiered Applications                                          2
                J2EE Components                                                            3
                J2EE Clients                                                               4
                Web Components                                                             6
                Business Components                                                        7
                Enterprise Information System Tier                                         8
             J2EE Containers                                                               8
                Container Services                                                         8
                Container Types                                                           10
             Packaging                                                                    10
             Development Roles                                                            11
                J2EE Product Provider                                                     12
                Tool Provider                                                             12
                Application Component Provider                                            12
                Application Assembler                                                     13
                Application Deployer and Administrator                                    14
             Reference Implementation Software                                            14
                Database Access                                                           15
                J2EE APIs                                                                 15
                Simplified Systems Integration                                            18
                Tools                                                                     19




                                                                                                v
vi                                  CONTENTS



     Chapter 2:   Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21
                  Setting Up                                                              22
                     Getting the Example Code                                             22
                     Getting the Build Tool (ant)                                         22
                     Checking the Environment Variables                                   23
                     Starting the J2EE™ Server                                            23
                     Starting the deploytool                                              23
                  Creating the J2EE™ Application                                          24
                  Creating the Enterprise Bean                                            24
                     Coding the Enterprise Bean                                           24
                     Compiling the Source Files                                           26
                     Packaging the Enterprise Bean                                        26
                  Creating the J2EE™ Application Client                                   28
                     Coding the J2EE Application Client                                   28
                     Compiling the Application Client                                     31
                     Packaging the J2EE Application Client                                31
                     Specifying the Application Client’s Enterprise Bean Reference        32
                  Creating the Web Client                                                 32
                     Coding the Web Client                                                32
                     Compiling the Web Client                                             34
                     Packaging the Web Client                                             34
                     Specifying the Web Client’s Enterprise Bean Reference                35
                  Specifying the JNDI Names                                               35
                  Deploying the J2EE™ Application                                         37
                  Running the J2EE™ Application Client                                    37
                  Running the Web Client                                                  38
                  Modifying the J2EE™ Application                                         39
                     Modifying a Class File                                               39
                     Adding a File                                                        40
                     Modifying the Web Client                                             40
                     Modifying a Deployment Setting                                       40
                  Common Problems and Their Solutions                                     41
                     Cannot Start the J2EE Server                                         41
                     Compilation Errors                                                   42
                     Deployment Errors                                                    43
                     J2EE Application Client Runtime Errors                               43
                     Web Client Runtime Errors                                            45
                     Detecting Problems With the Verifier Tool                            45
                     Comparing Your EAR Files with Ours                                   46
                     When All Else Fails                                                  46
                                      CONTENTS                                             vii


Chapter 3:   Enterprise Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
             What Is an Enterprise Bean?                                       48
                Benefits of Enterprise Beans                                   48
                When to Use Enterprise Beans                                   49
                Types of Enterprise Beans                                      49
             What Is a Session Bean?                                           49
                State Management Modes                                         50
                When to Use Session Beans                                      51
             What Is an Entity Bean?                                           51
                What Makes Entity Beans Different from Session Beans?          52
                Container-Managed Persistence                                  53
                When to Use Entity Beans                                       56
             What Is a Message-Driven Bean?                                    56
                What Makes Message-Driven Beans Different from Session and Entity
                Beans?                                                         57
                When to Use Message-Driven Beans                               57
             Defining Client Access with Interfaces                            58
                Remote Access                                                  58
                Local Access                                                   59
                Local Interfaces and Container-Managed Relationships           59
                Deciding on Remote or Local Access                             60
                Performance and Access                                         61
                Method Parameters and Access                                   61
             The Contents of an Enterprise Bean                                62
             Naming Conventions for Enterprise Beans                           63
             The Life Cycles of Enterprise Beans                               63
                The Life Cycle of a Stateful Session Bean                      64
                The Life Cycle of a Stateless Session Bean                     65
                The Life Cycle of an Entity Bean                               65
                The Life Cycle of a Message-Driven Bean                        67

Chapter 4:   A Session Bean Example . . . . . . . . . . . . . . . . . . . . . 69
             The CartEJB Example                                                     70
                Session Bean Class                                                   70
                Home Interface                                                       75
                Remote Interface                                                     76
                Helper Classes                                                       76
                Running the CartEJB Example                                          76
             Other Enterprise Bean Features                                          78
                Accessing Environment Entries                                        78
                Comparing Enterprise Beans                                           80
                Passing an Enterprise Bean’s Object Reference                        80
viii                               CONTENTS



       Chapter 5:   Bean-Managed Persistence Examples. . . . . . . . . .83
                    The SavingsAccountEJB Example                                     84
                       Entity Bean Class                                              85
                       Home Interface                                                 94
                       Remote Interface                                               96
                       Running the SavingsAccountEJB Example                          97
                    deploytool Tips for Entity Beans With Bean-Managed Persistence    99
                    Mapping Table Relationships for Bean-Managed Persistence          99
                       One-to-One Relationships                                       99
                       One-to-Many Relationships                                     103
                       Many-to-Many Relationships                                    110
                    Primary Keys for Bean-Managed Persistence                        113
                       The Primary Key Class                                         113
                       Primary Keys in the Entity Bean Class                         114
                       Getting the Primary Key                                       115
                    Handling Exceptions                                              116

       Chapter 6:   Container-Managed Persistence Examples. . . . .119
                    Overview of the RosterApp Application                           120
                    The PlayerEJB Code                                              121
                       Entity Bean Class                                            122
                       Local Home Interface                                         126
                       Local Interface                                              128
                    A Guided Tour of the RosterApp Settings                         128
                       RosterApp                                                    128
                       RosterClient                                                 130
                       RosterJAR                                                    130
                       TeamJAR                                                      131
                    Method Invocations in RosterApp                                 137
                       Creating a Player                                            137
                       Adding a Player to a Team                                    138
                       Removing a Player                                            140
                       Dropping a Player from a Team                                140
                       Getting the Players of a Team                                141
                       Getting a Copy of a Team’s Players                           143
                       Finding the Players by Position                              145
                       Getting the Sports of a Player                               146
                    Running the RosterApp Example                                   147
                       Setting Up                                                   147
                       Deploying the Application                                    148
                       Running the Client                                           148
                    deploytool Tips for Entity Beans With Container-Managed Persistence
                                    CONTENTS                                       ix


             148
                Specifying the Bean’s Type                                   149
                Selecting the Persistent Fields and Abstract Schema Name     149
                Defining EJB QL Queries for Finder and Select Methods        149
                Generating SQL and Specifying Table Creation                 150
                Specifying the Database JNDI Name, User Name, and Password   150
                Defining Relationships                                       151
             Primary Keys for Container-Managed Persistence                  151
                The Primary Key Class                                        151
                Primary Keys in the Entity Bean Class                        152
                Generating Primary Key Values                                153

Chapter 7:   A Message-Driven Bean Example . . . . . . . . . . . . 155
             Example Application Overview                                    156
             The J2EE™ Application Client                                    157
             The Message-Driven Bean Class                                   158
                The onMessage Method                                         158
                The ejbCreate and ejbRemove Methods                          159
             Running the SimpleMessageEJB Example                            159
                Starting the J2EE Server                                     159
                Creating the Queue                                           159
                Deploying the Application                                    159
                Running the Client                                           160
             deploytool Tips for Message-Driven Beans                        160
                Specifying the Bean’s Type and Transaction Management        161
                Setting the Message-Driven Bean’s Characteristics            161
             deploytool Tips for JMS Clients                                 162
                Setting the Resource References                              163
                Setting the Resource Environment References                  163
                Specifying the JNDI Names                                    163

Chapter 8: Enterprise JavaBeans™
Query Language165
             Terminology                                                     166
             Simplified Syntax                                               167
             Example Queries                                                 167
                Simple Finder Queries                                        167
                Finder Queries That Navigate to Related Beans                169
                Finder Queries with Other Conditional Expressions            170
                Select Queries                                               172
x                                   CONTENTS


                    Full Syntax                                               173
                       BNF Grammar of EJB QL                                  173
                       BNF Symbols                                            176
                       FROM Clause                                            176
                       Path Expressions                                       179
                       WHERE Clause                                           182
                       SELECT Clause                                          190
                    EJB QL Restrictions                                       191

    Chapter 9:      Web Clients and Components. . . . . . . . . . . . . . . .193
                    Web Client Life Cycle                                     194
                    Web Application Archives                                  196
                       Creating a WAR File                                    197
                       Adding a WAR File to an EAR File                       198
                       Adding a Web Component to a WAR File                   198
                    Configuring Web Clients                                   200
                       Application-Level Configuration                        200
                       WAR-Level Configuration                                200
                       Component-Level Configuration                          202
                    Deploying Web Clients                                     203
                    Running Web Clients                                       204
                    Updating Web Clients                                      204
                    Internationalizing Web Clients                            206

    Chapter 10: Java Servlet Technology . . . . . . . . . . . . . . . . . . . .209
                    What Is a Servlet?                                        210
                    The Example Servlets                                      211
                        Troubleshooting                                       215
                    Servlet Life Cycle                                        216
                        Handling Servlet Life-Cycle Events                    216
                        Handling Errors                                       218
                    Sharing Information                                       218
                        Using Scope Objects                                   219
                        Controlling Concurrent Access to Shared Resources     220
                        Accessing Databases                                   221
                    Initializing a Servlet                                    222
                    Writing Service Methods                                   223
                        Getting Information from Requests                     223
                        Constructing Responses                                225
                                    CONTENTS                             xi


              Filtering Requests and Responses                     228
                  Programming Filters                              229
                  Programming Customized Requests and Responses    231
                  Specifying Filter Mappings                       233
              Invoking Other Web Resources                         235
                  Including Other Resources in the Response        235
                  Transferring Control to Another Web Component    237
              Accessing the Web Context                            238
              Maintaining Client State                             239
                  Accessing a Session                              239
                  Associating Attributes with a Session            239
                  Session Management                               240
                  Session Tracking                                 241
              Finalizing a Servlet                                 242
                  Tracking Service Requests                        242
                  Notifying Methods to Shut Down                   243
                  Creating Polite Long-Running Methods             244

Chapter 11: JavaServer Pages™ Technology . . . . . . . . . . . . . 245
              What Is a JSP Page?                                  246
              The Example JSP Pages                                249
              The Life Cycle of a JSP Page                         253
                  Translation and Compilation                      253
                  Execution                                        254
              Initializing and Finalizing a JSP Page               256
              Creating Static Content                              257
              Creating Dynamic Content                             257
                  Using Objects within JSP Pages                   257
                  JSP Scripting Elements                           260
              Including Content in a JSP Page                      263
              Transferring Control to Another Web Component        264
                  Param Element                                    265
              Including an Applet                                  265
              Extending the JSP Language                           267

Chapter 12: JavaBeans™ Components in JSP™ Pages . . . . . 269
              JavaBeans Component Design Conventions               270
              Why Use a JavaBeans Component?                       271
              Creating and Using a JavaBeans Component             272
              Setting JavaBeans Component Properties               273
              Retrieving JavaBeans Component Properties            275
xii                                       CONTENTS



      Chapter 13: Custom Tags in JSP™ Pages. . . . . . . . . . . . . . . . . .279
                         What is a Custom Tag?                                                280
                         The Example JSP Pages                                                281
                         Using Tags                                                           285
                            Declaring Tag Libraries                                           285
                            Types of Tags                                                     286
                         Defining Tags                                                        289
                            Tag Handlers                                                      289
                            Tag Library Descriptors                                           290
                            Simple Tags                                                       293
                            Tags with Attributes                                              294
                            Tags With Bodies                                                  296
                            Tags That Define Scripting Variables                              298
                            Cooperating Tags                                                  302
                         Examples                                                             304
                            An Iteration Tag                                                  304
                            A Template Tag Library                                            308
                         How Is a Tag Handler Invoked?                                        313

      Chapter 14: Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .315
                         What Is a Transaction?                                               316
                         Container-Managed Transactions                                       316
                             Transaction Attributes                                           317
                             Rolling Back a Container-Managed Transaction                     321
                             Synchronizing a Session Bean’s Instance Variables                322
                             Methods Not Allowed in Container-Managed Transactions            323
                         Bean-Managed Transactions                                            323
                             JDBC Transactions                                                324
                             JTA Transactions                                                 325
                             Returning without Committing                                     326
                             Methods Not Allowed in Bean-Managed Transactions                 327
                         Summary of Transaction Options for Enterprise Beans                  327
                         Transaction Timeouts                                                 328
                         Isolation Levels                                                     329
                         Updating Multiple Databases                                          329
                         Transactions in Web Components                                       331

      Chapter 15: Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .333
                         Overview                                                             334
                                       CONTENTS                                    xiii


                Security Roles                                               335
                    Declaring and Linking Role References                    335
                    Mapping Roles to J2EE Users and Groups                   337
                Web-Tier Security                                            337
                    Protecting Web Resources                                 337
                    Controlling Access to Web Resources                      338
                    Authenticating Users of Web Resources                    338
                    Using Programmatic Security in the Web Tier              340
                    Unprotected Web Resources                                340
                EJB-Tier Security                                            341
                    Declaring Method Permissions                             341
                    Using Programmatic Security in the EJB Tier              341
                    Unprotected EJB-Tier Resources                           342
                Application Client-Tier Security                             342
                    Specifying the Application Client’s Callback Handler     343
                EIS-Tier Security                                            343
                    Configuring Sign-On                                      344
                    Container-Managed Sign-On                                344
                    Component-Managed Sign-On                                344
                    Configuring Resource Adapter Security                    345
                Propagating Security Identity                                346
                    Configuring a Component’s Propagated Security Identity   347
                    Configuring Client Authentication                        347
                J2EE Users, Realms, and Groups                               348
                    Managing J2EE Users and Groups                           349
                Setting Up a Server Certificate                              350

Chapter 16: Resource Connections. . . . . . . . . . . . . . . . . . . . . . 353
                JNDI Names and Resource References                           353
                   deploytool Tips for Resource References                   354
                Database Connections for Enterprise Beans                    356
                   Coded Connections                                         357
                   Connection Pooling                                        359
                Mail Session Connections                                     359
                   Running the ConfirmerEJB Example                          361
                URL Connections                                              362
                   Running the HTMLReaderEJB Example                         363
xiv                                  CONTENTS



      Chapter 17: J2EE™ Connector Architecture . . . . . . . . . . . . . . .365
                     About Resource Adapters                                  366
                        Resource Adapter Contracts                            366
                        Administering Resource Adapters                       368
                     The Black Box Resource Adapters                          369
                        Transaction Levels                                    369
                        Properties                                            370
                        Configuring JDBC™ Drivers                             371
                     Resource Adapter Tutorial                                372
                        Setting Up                                            372
                        Deploying the Resource Adapter                        372
                        Testing the Resource Adapter                          373
                     Common Client Interface                                  375
                        Overview of the CCI                                   375
                        Programming with the CCI                              377
                        Writing a CCI Client                                  386
                        CCI Tutorial                                          386

      Chapter 18: The Duke’s Bank Application . . . . . . . . . . . . . . . . .391
                     Enterprise Beans                                         393
                        Session Beans                                         394
                        CustomerControllerEJB                                 396
                        TxControllerEJB                                       396
                        Entity Beans                                          397
                        Helper Classes                                        397
                        Database Tables                                       398
                        Protecting the Enterprise Beans                       400
                     Application Client                                       400
                        The Classes and Their Relationships                   402
                        BankAdmin Class                                       403
                        EventHandle Class                                     404
                        DataModel Class                                       406
                     Web Client                                               409
                        Design Strategies                                     410
                        Web Client Life Cycle                                 411
                        Protecting the Web Resources                          415
                     Internationalization                                     415
                                        CONTENTS                                         xv


                 Building, Packaging, Deploying, and Running the Application      417
                    Adding Groups and Users to the Realm                          417
                    Starting the J2EE Server, deploytool, and Database            418
                    Compiling the Enterprise Beans                                419
                    Packaging the Enterprise Beans                                419
                    Compiling the Web Client                                      420
                    Packaging the Web Client                                      420
                    Compiling the J2EE Application Client                         420
                    Packaging the J2EE Application Client                         421
                    Packaging the Enterprise Archive File                         421
                    Opening the Enterprise Archive File                           421
                    Reviewing JNDI Names                                          423
                    Mapping the Security Roles to Groups                          425
                    Deploying the Duke’s Bank Application                         426
                    Creating the Bank Database                                    426
                    Running the J2EE Application Client                           427
                    Running the Web Client                                        428

Appendix A: HTTP Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
                 HTTP Requests                                                    432
                 HTTP Responses                                                   432

Appendix B: J2EE™ SDK Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
                 J2EE Administration Tool                                         434
                 Cleanup Tool                                                     435
                 Cloudscape Server                                                435
                    Starting Cloudscape                                           436
                    Stopping Cloudscape                                           436
                    Running the Interactive SQL Tool                              436
                    Cloudscape Server Configuration                               437
                 Deployment Tool                                                  438
                 J2EE Server                                                      439
                 Key Tool                                                         439
                 Packager Tool                                                    440
                    EJB JAR File                                                  440
                    Web Application WAR File                                      441
                    Application Client JAR File                                   441
                    J2EE Application EAR File                                     442
                    Specifying the Runtime Deployment Descriptor                  442
                    Resource Adapter RAR File                                     443
xvi                                        CONTENTS


                        Realm Tool                                                                 444
                           Examples                                                                444
                        runclient Script                                                           445
                           Syntax                                                                  445
                           Example                                                                 446
                           Accessing a Remote Server                                               446
                           Preventing the User Name and Password Prompts                           447
                        Verifier Tool                                                              447
                           Command-Line Verifier                                                   447
                           Stand-Alone GUI Verifier                                                448

      Appendix C: Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .449

                        Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .453

                        Biographies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .477

                        Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .479
                                                     Foreword

I joined Sun—actually, a small Sun spin-off called FirstPerson—in August
1993. I knew about the company because a few of my favorite coworkers had
left NeXT to work at FirstPerson. But my main reason for joining was that I
loved the cartoony user interfaces FirstPerson was developing interfaces that
featured a character nicknamed Duke.1




Figure 1 Duke, the Unofficial Mascot of the Java Platform

FirstPerson’s first demo, called Star 7, was a household remote control with a
small touchscreen. By the time I arrived, they were working on a demo for video
on demand.
The wonderfully loony animation for the video-on-demand demo was created by
a San Francisco studio called Colossal Pictures (where, incidentally, my husband
had gotten his start in the animation industry). Both demos were written using a
programming language that was then called Oak.
My first task was to help the creator of the Oak language, James Gosling, write
the language specification. What I really wanted to do, though, was to write task-
oriented documentation aimed at ordinary programmers.


1   You can get more information about Duke in the article “It’s Duke’s Birthday, Too!”:
    lmth.ekud/50/9991/serutaef/moc.nus.avaj//:ptth               .
                                                                                           xvii
xviii                                 FOREWORD



          By July 1994, FirstPerson was in turmoil, having failed to convince cable com-
          panies that their video-on-demand solution was what customers needed. I stayed
          at the company only because I was about to go on maternity leave.


        Programming for the Internet
          When I returned to work in the fall of 1994, the company’s dynamic and vision
          had completely changed. They had decided that the Oak language—with its abil-
          ity to produce platform-independent, secure, easily transported code—was ideal
          for the Internet. And they were creating a Web browser called WebRunner that
          showcased the ability to deliver Oak code, packaged in a form they called
          applets, over the Internet.
          I set to work writing a guide to help people write and use applets. When the
          WebRunner browser was first released in early 1995, the guide was part of the
          small set of documentation included with the browser. That guide was the grand-
          daddy of The J2EE™ Tutorial.
          The guide was the first documentation to include applets. It looked somewhat
          similar to The Java™ Tutorial, and in fact The Java Tutorial probably still has
          some of the text originally published in the guide. Because we had no HTML
          tools, 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 a
          small document. Much less painful was making name changes: The language
          name changed from Oak to Java, and the name of the browser from WebRunner
          to HotJava.


        Mary Enters the Picture
          In early 1995, we hired a contract writer named Mary Campione. She and I knew
          of each other from her time in NeXT developer support. Mary’s job was to help
          programmers use platform features such as threads. We soon realized that our
          work was too similar for us to do it separately, and we started working together
          on 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 first
          draft—nothing pretty—but it provided people with the information they needed
          to get started programming for the Java platform.
                                           FOREWORD                                           xix


  The next week, Sun officially announced the Java platform at a show called Sun-
  World. The best part of the show for us was the announcement that Netscape had
  agreed (just hours before) to support applets in their Web browser.
  In the following months, Mary and I continued to add to and refine our program-
  mer’s guide. 1We worked together closely, sharing the same office and even the
  same train commute from San Francisco to Palo Alto. By coincidence, we even
  got 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 written
  mainly by employees of what used to be FirstPerson. By that time, FirstPerson
  had been absorbed back into Sun, in the form of a division called JavaSoft. The
  Series Editor was JavaSoft technical publications manager Lisa Friendly.2
  Our 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 its
  name to The Java Tutorial. There we were, two increasingly large women work-
  ing insanely long hours to finish the book before the babies arrived in mid-1996.
  We managed—just barely—to get the book to our publisher in time. We couldn’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 Grows
  When Mary and I returned from maternity leave, we felt completely over-
  whelmed. 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 already
  started on JDK 1.2 (which would be renamed to the Java 2 Platform, Standard
  Edition, Version 1.2—J2SE v 1.2, for short). We would be able to update our
  existing 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 authors
  were writers and engineers on the teams developing the new 1.2 features. Alison
  was a postgraduate student with experience in both software and publishing. She
  did whatever was necessary to make the Tutorial succeed, ranging from produc-
  ing camera-ready copy for books to writing text and examples.

  1
    By looking at  sih/noitamrofni/lairotut/skoob/scod/moc.nus.avaj//:ptth
      lmth.yrot, you can see what was in each of our updates.
  2 Lisa has some great anecdotes about the early days of FirstPerson. You can read some of

    them at lmth.yadhtrib/50/8991/serutaef/moc.nus.avaj//:ptth               .
xx                                        FOREWORD



       Between 1998 and 2000, the Tutorial team updated the Web site many times and
       produced two completely new books, as well as two major revisions of the origi-
       nal book. In mid-2000, Mary retired from paid work. Alison and I still work on
       The Java Tutorial, in both its Web and book forms. Although we rely on guest
       authors from time to time, the rate of change has become less frantic as the J2SE
       platform matures.


     The J2EE Tutorial
       Now there’s a new platform—and a new tutorial—in town. The success of the
       Java 2 Platform, Enterprise Edition has been phenomenal. Developers are clam-
       oring for information about how to write applications using this new Java plat-
       form for the server. And this book helps, continuing the tradition of The Java
       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 time they’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, you
       need to be comfortable writing programs for the J2SE platform before you can
       make full use of this book. If you’re not comfortable with the J2SE platform, go
       to The Java Tutorial1 and learn!
       Then come back here, so you can find out all about developing and deploying
       applications for the J2EE platform.


       Kathy Walrath
       Sun Microsystems
       San Francisco, CA
       December 21, 2001




       1   On the Web at  /lairotut/skoob/scod/moc.nus.avaj//:ptth   , or in book form as
           The Java Tutorial: A Short Course on the Basics.
                                                                Preface

  THE Java Tutorial has been an indispensable resource for many programmers
  learning the Java programming language. This tutorial hopes to serve the same
  role for developers encountering the Java™ 2 Platform, Enterprise Edition
  (J2EE™) for the first time. It follows an example-oriented focus similar to the
  Java Tutorial.


Who Should Use This Tutorial
  This tutorial is intended for programmers interested in developing and deploying
  J2EE applications. It covers the main component technologies comprising the
  J2EE platform and describes 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 explain
  how to implement the J2EE architecture, nor does it explain the internals of the
  J2EE SDK. The J2EE specifications describe the J2EE architecture and can be
  downloaded from

      s ce ps #l m th .s c od /e e2 j /m oc .n u s. av a j/ /: pt t h


About the Examples
  This tutorial includes many complete, working examples. See
  Examples, page (449) for a list of the examples and the chapters where they
  appear.
xxii                                                   PREFACE



           Prerequisites for the Examples
           To understand the examples, you will need a good knowledge of the Java pro-
           gramming language, SQL, and relational database concepts. The topics in the
           Java Tutorial listed in Table 1 are particularly relevant:


           Table 1 Prerequisite Topics

       Topic                    Java Tutorial

       JDBC™                    cbdj/lairotut/skoob/scod/moc.nus.avaj//:ptth

       Threads                  sdaerht/laitnesse/lairotut/skoob/scod/moc.nus.avaj//:ptth

       JavaBeans™               snaebavaj/lairotut/skoob/scod/moc.nus.avaj//:ptth

       Security                 2.1ytiruces/lairotut/skoob/scod/moc.nus.avaj//:ptth



           Downloading the Examples
           If you are viewing this online and you want to build and run the examples, you
           need to download the tutorial bundle from

                  l a ir ot u t# lm th . da ol n wo d/ ee 2 j/ mo c .n us .a v aj // :p t th

           Once you have installed the bundle, the example source code is in the
                                          directory, with subdirectories
             c rs / se lp m ax e/ la i ro tu te e 2j                         for enterprise    b je
           bean technology examples,
           b ew                            for Web technology examples, and                           ro tc e nn oc
           for connector technology examples. For most of the examples, the bundle also
           includes J2EE application Enterprise Archive EAR files, which are located in the
                                           directory.
           sr ae / se lp m ax e/ la i ro tu te e 2j


           How to Build and Run the Examples
           This tutorial documents the J2EE SDK version 1.3. To build, deploy, and run the
           examples you need a copy of the J2EE SDK 1.3 and the Java 2 Platform, Stan-
           dard Edition (J2SE™) SDK 1.3.1 (earlier versions were called JDK). You can
           download the J2EE SDK from

                  k d s# lm th . da ol n wo d/ ee 2 j/ mo c .n us .a v aj // :p t th
                                            PREFACE                                                   xxiii


and the J2SE 1.3.1 from:

    / 3 .1 /e s2 j /m oc .n u s. av a j/ /: pt t h

The examples are distributed with a configuration file for version 1.3 of       a              tn a
portable make tool. The    utility is hosted by the Jakarta project at the Apache
                              tna
Software Foundation. You can download         from   tn a

    ni b/ 3 .1 v/ e sa el er / tn a a tr ak aj / sd li u b/ gr o. e hc ap a. a tr ak a j/ /: pt t h

To build the tutorial examples:
    1. Download and install the J2SE SDK 1.3.1, J2EE SDK 1.3, and         .             t na
    2. The installation instructions for the J2SE SDK, J2EE SDK, and                             t na
       explain how to set the required environment variables. Verify that the
       environment variables have been set to the values noted in the Table 1.


Table 1 Settings for Environment Variables

 Environment Variable          Value

 EMOH_AVAJ                     The location of the J2SE SDK installation.

 EMOH_EE2J                     The location of the J2EE SDK installation.

 EMOH_TNA                      The location of the   tna    installation.

                               Should include the     directories of the J2EE SDK, J2SE SDK,
                                                     nib
 HTAP
                               and  tnainstallations.



    3. Go to the                             directory.
                    se l pm ax e/ l ai ro t ut ee 2j
    4. Execute              . For example, to build all the examples, execute
                   t eg r at t na                                                                t na
          ; to build the Web layer examples, execute
        l la                                                   . The build process
                                                                             be w tn a
       deposits the output into the directory                                  .
                                                        d li ub / se lp ma x e/ la i ro tu te e 2j
xxiv                                          PREFACE



       Related Information
             This tutorial provides a concise overview of how to use the central component
             technologies in the J2EE platform. For more information about these technolo-
             gies, see the Web sites listed in Table 2


             Table 2 Information Sources

       Component Technology                   Web Site

       Enterprise JavaBeans™ (EJB™)           bje/stcudorp/moc.nus.avaj//:ptth

       Java Servlet                           stelvres/stcudorp/moc.nus.avaj//:ptth

       JavaServer Pages™ (JSP™)               psj/stcudorp/moc.nus.avaj//:ptth



             The J2EE platform includes a wide variety of APIs that this tutorial only briefly
             touches on. Some of these technologies have their own tutorials, which are listed
             in Table 3.


             Table 3 Other Tutorials

       API                                   Tutorial

       Java Message Service (JMS)            /lairotut/smj/stcudorp/moc.nus.avaj//:ptth

       Java Naming and Directory
                                             /lairotut/idnj/stcudorp/moc.nus.avaj//:ptth
       Interface™ (JNDI)

       Java API for XML Processing           /scod/1.1/tsid/pxaj/lmx/moc.nus.avaj//:ptth
       (JAXP)                                                        lmth.xedni/lairotut
                                                  PREFACE                                     xxv


      For complete information on these topics, see the Web sites listed in Table 4.


      Table 4 Other Web sites

API                                                   Web Site

J2EE Connector                                        rotcennoc/ee2j/moc.nus.avaj//:ptth

JAXP                                                  pxaj/stcudorp/moc.nus.avaj//:ptth

JavaMail™                                             liamavaj/stcudorp/moc.nus.avaj//:ptth

JMS                                                   smj/stcudorp/moc.nus.avaj//:ptth

JNDI                                                  idnj/stcudorp/moc.nus.avaj//:ptth

JDBC™                                                 cbdj/stcudorp/moc.nus.avaj//:ptth



      Once you have become familiar with the J2EE technologies described in this
      tutorial, you may be interested in guidelines for architecting J2EE applications.
      The J2EE BluePrints illustrate best practices for developing and deploying J2EE
      applications. You can obtain the J2EE BluePrints from

          st n ir pe ul b /m oc .n u s. av a j/ /: pt t h


How to Print This Tutorial
      To 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 from

          . la i ro tu t #l mt h. d ao ln w od /e e2 j /m oc .n u s. av a j/ /: pt t h

          3. Click the printer icon in Adobe Acrobat Reader.
xxvi                                          PREFACE



       Typographical Conventions
            Table 5 lists the typographical conventions used in this tutorial.


            Table 5 Typographical Conventions

       Font Style                                   Uses

       Italic                                       Emphasis, titles, first occurrence of terms

       ec ap so n oM                                URLs, code examples, file names, command
                                                    names, programming language keywords

       ec ap so n om c il a tI                      Programming variables, variable file names




            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 SDK team for their techni-
            cal advice.
            We are extremely grateful to the many internal and external reviewers who pro-
            vided feedback on the tutorial. This helped us to improve the presentation, cor-
            rect errors, and eliminate bugs.
            We would also like to thank our manager, Jim Inscore, for his support and
            steadying influence.
            The chapters on Web components use an example and some material that first
            appeared in the servlet trail of the Java Tutorial. The chapters on custom tags and
            the Duke’s Bank application use a template tag library that first appeared in the
            J2EE BluePrints.
                                                   1
                                            Overview
                                                              Monica Pawlan



TODAY, more and more developers want to write distributed transactional
applications for the enterprise and leverage the speed, security, and reliability of
server-side technology. If you are already working in this area, you know that in
today’s fast-moving and demanding world of e-commerce and information tech-
nology, enterprise applications have to be designed, built, and produced for less
money, with greater speed, and with fewer resources than ever before.
To reduce costs and fast-track enterprise application design and development,
the Java™ 2 Platform, Enterprise Edition (J2EE™) technology provides a com-
ponent-based approach to the design, development, assembly, and deployment of
enterprise applications. The J2EE platform offers a multitiered distributed appli-
cation model, the ability to reuse components, integrated Extensible Markup
Language (XML)-based data interchange, a unified security model, and flexible
transaction control. Not only can you deliver innovative customer solutions to
market faster than ever, but your platform-independent J2EE component-based
solutions are not tied to the products and application programming interfaces
(APIs) of any one vendor. Vendors and customers enjoy the freedom to choose
the products and components that best meet their business and technological
requirements.
This tutorial takes an examples-based approach to describing the features and
functionalities available in J2EE Software Development Kit (SDK) version 1.3.
Whether you are a new or an experienced enterprise developer, you should find
the examples and accompanying text a valuable and accessible knowledge base
for creating your own enterprise solutions.

                                                                                       1
2                                  OVERVIEW



      If you are new to J2EE applications development, this chapter is a good place to
      start. Here you will learn the J2EE architecture, become acquainted with impor-
      tant terms and concepts, and find out how to approach J2EE application pro-
      gramming, assembly, and deployment.

      In This Chapter
                Distributed Multitiered Applications 2
                    J2EE Components 3
                    J2EE Clients 4
                    Web Components 6
                    Business Components 7
                    Enterprise Information System Tier 8
                J2EE Containers 8
                    Container Services 8
                    Container Types 10
                Packaging 10
                Development Roles 11
                    J2EE Product Provider 12
                    Tool Provider 12
                    Application Component Provider 12
                    Application Assembler 13
                    Application Deployer and Administrator 14
                Reference Implementation Software 14
                    Database Access 15
                    J2EE APIs 15
                    Simplified Systems Integration 18
                    Tools 19


    Distributed Multitiered Applications
      The J2EE platform uses a multitiered distributed application model. Application
      logic is divided into components according to function, and the various applica-
      tion components that make up a J2EE application are installed on different
      machines depending on the tier in the multitiered J2EE environment to which the
      application component belongs. Figure 1–1 shows two multitiered J2EE applica-
      tions 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.
                                      DISTRIBUTED MULTITIERED APPLICATIONS           3


    • 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 different locations: client
machines, the J2EE server machine, and the database or legacy machines at the
back end. Three-tiered applications that run in this way extend the standard two-
tiered client and server model by placing a multithreaded application server
between the client application and back-end storage.




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.
4                                OVERVIEW



        • 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, verified to be well formed and in compliance
    with the J2EE specification, and deployed to production, where they are run and
    managed by the J2EE server.

    J2EE Clients
    A J2EE client can be a Web client or an application client.

    Web Clients
    A Web client consists of two parts: dynamic Web pages containing various types
    of markup language (HTML, XML, and so on), which are generated by Web
    components running in the Web tier, and a Web browser, which renders the
    pages received from the server.
    A Web client is sometimes called a thin client. Thin clients usually do not do
    things like query databases, execute complex business rules, or connect to legacy
    applications. When you use a thin client, heavyweight operations like these are
    off-loaded to enterprise beans executing on the J2EE server where they can
    leverage the security, speed, services, and reliability of J2EE server-side technol-
    ogies.

    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.
                                     DISTRIBUTED MULTITIERED APPLICATIONS               5


Application Clients
A J2EE application client runs on a client machine and provides a way for users
to handle tasks that require a richer user interface than can be provided by a
markup language. It typically has a graphical user interface (GUI) created from
Swing or Abstract Window Toolkit (AWT) APIs, but a command-line interface
is certainly possible.
Application clients directly access enterprise beans running in the business tier.
However, if application requirements warrant it, a J2EE application client can
open an HTTP connection to establish communication with a servlet running in
the Web tier.

JavaBeans™ Component Architecture
The server and client tiers might also include components based on the Java-
Beans component architecture (JavaBeans component) 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 instance variables and          and
                                                         te g     methods for
                                                                    t es
accessing the data in the instance variables. JavaBeans components used in this
way are typically simple in design and implementation, but should conform to
the naming and design conventions outlined in the JavaBeans component archi-
tecture.

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                                OVERVIEW




    Figure 1–2 Server Communications


    Web Components
    J2EE Web components can be either servlets or JSP pages. Servlets are Java pro-
    gramming language classes that dynamically process requests and construct
    responses. JSP pages are text-based documents that execute as servlets but allow
    a more natural approach to creating static content.
    Static HTML pages and applets are bundled with Web components during 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.
    Like the client tier and as shown in Figure 1–3, the Web tier might include a Jav-
    aBeans component to manage the user input and send that input to enterprise
    beans running in the business tier for processing.
                                    DISTRIBUTED MULTITIERED APPLICATIONS              7




Figure 1–3 Web Tier and J2EE Application


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-
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–4 Business and EIS Tiers
8                                        OVERVIEW



      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 features of a session bean and a Java Message
      Service (JMS) message listener, allowing a business component to receive JMS
      messages asynchronously. This tutorial describes entity beans and session beans.
      For information on message-driven beans, see the Java Message Service Tuto-
      rial, available at

          lm th .x e dn i/ l ai ro tu t /s mj / st cu do r p/ mo c .n us .a v aj // :p t th

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


    J2EE 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, enterprise
      bean, or application client component can be executed, it must be assembled into
      a J2EE application and deployed into its container.
                                     J2EE CONTAINERS                                     9


The assembly process involves specifying container settings for each component
in the J2EE application and for the J2EE application itself. Container settings
customize the underlying support provided by the J2EE server, which includes
services such as security, transaction management, Java Naming and Directory
Interface™ (JNDI) lookups, and remote connectivity. Here are some of the high-
lights:
    • The J2EE security model lets you configure a Web component or enter-
      prise 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.
The fact that the J2EE architecture provides configurable services means that
application components within the same J2EE application can behave differently
based on where they are deployed. For example, an enterprise bean can have
security settings that allow it a certain level of access to database data in one pro-
duction environment and another level of database access in another production
environment.
The container also manages nonconfigurable services such as enterprise bean
and servlet life cycles, database connection resource pooling, data persistence,
and access to the J2EE platform APIs described in the section J2EE
APIs, page (15). 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.
10                                 OVERVIEW



       Container Types
       The deployment process installs J2EE application components in the J2EE con-
       tainers illustrated in Figure 1–5.
           • J2EE server: Is the runtime portion of a J2EE product. A J2EE server pro-
             vides EJB and Web containers.
           • Enterprise JavaBeans (EJB) container: Manages the execution of enter-
             prise beans for J2EE applications. Enterprise beans and their container run
             on the J2EE server.
           • Web container: Manages the execution of JSP page and servlet compo-
             nents for J2EE applications. Web components and their container run on
             the J2EE server.
           • Application client container: Manages the execution of application client
             components. Application clients and their container run on the client.
           • Applet container: Manages the execution of applets. Consists of a Web
             browser and Java Plug-in running on the client together.




       Figure 1–5 J2EE Server and Containers


     Packaging
       J2EE components are packaged separately and bundled into a J2EE application
       for deployment. Each component, its related files such as GIF and HTML files
                                     DEVELOPMENT ROLES                                 11


  or server-side utility classes, and a deployment descriptor are assembled into a
  module and added to the J2EE application. A J2EE application is composed of
  one or more enterprise bean, Web, or application client component modules. The
  final enterprise solution can use one J2EE application or be made up of two or
  more J2EE applications, depending on design requirements.
  A J2EE application and each of its modules has its own deployment descriptor.
  A deployment descriptor is an XML document with an          lm x.  extension that
  describes a component’s deployment settings. An enterprise bean module
  deployment descriptor, for example, declares transaction attributes and security
  authorizations for an enterprise bean. Because deployment descriptor informa-
  tion is declarative, it can be changed without modifying the bean source code. At
  run time, the J2EE server reads the deployment descriptor and acts upon the
  component accordingly.
  A J2EE application with all of its modules is delivered in an Enterprise ARchive
  (EAR) file. An EAR file is a standard Java Archive (JAR) file with an       r ae .
  extension. In the GUI version of the J2EE SDK application deployment tool, you
  create an EAR file first and add JAR and Web Archive (WAR) files to the EAR.
  If you use the command line packager tools, however, you create the JAR and
  WAR files first and then create the EAR. The J2EE SDK tools are described in
  the section Tools, page (19).
      • Each EJB JAR file contains a deployment descriptor, the enterprise bean
        files, and related files.
      • Each application client JAR file contains a deployment descriptor, the
        class files for the application client, and related files.
      • Each WAR file contains a deployment descriptor, the Web component
        files, and related resources.
  Using modules and EAR files makes it possible to assemble a number of differ-
  ent J2EE applications using some of the same components. No extra coding is
  needed; it is just a matter of assembling various J2EE modules into J2EE EAR
  files.


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.
12                                 OVERVIEW



     The first two roles involve purchasing and installing the J2EE product and tools.
     Once software is purchased and installed, J2EE components can be developed by
     application component providers, assembled by application assemblers, and
     deployed by application deployers. In a large organization, each of these roles
     might be executed by different individuals or teams. This division of labor works
     because each of the earlier roles outputs a portable 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 the EAR file to install the J2EE appli-
     cation into a J2EE server.
     The different roles are not always executed by different people. If you work for a
     small company, for example, or if you are prototyping a sample application, you
     might perform the tasks in every phase.

     J2EE Product Provider
     The J2EE product provider is the company that designs and makes available for
     purchase the J2EE platform, APIs, and other features defined in the J2EE speci-
     fication. Product providers are typically operating system, database system,
     application server, or Web server vendors who implement the J2EE platform
     according to the Java 2 Platform, Enterprise Edition Specification.

     Tool Provider
     The tool provider is the company or person who creates development, assembly,
     and packaging tools used by component providers, assemblers, and deployers.
     See the section Tools, page (19) for information on the tools available with J2EE
     SDK version 1.3.

     Application Component Provider
     The application component provider is the company or person who creates Web
     components, enterprise beans, applets, or application clients for use in J2EE
     applications.
                                     DEVELOPMENT ROLES                               13


Enterprise Bean Developer
An enterprise bean developer performs the following tasks to deliver an EJB
JAR file that contains the enterprise bean:
    • Writes and compiles the source code
    • Specifies the deployment descriptor
    • Bundles the         files and deployment descriptor into an EJB JAR file
                    s sa lc .

Web Component Developer
A Web component developer performs the following tasks to deliver a WAR file
containing the Web component:
    •   Writes and compiles servlet source code
    •   Writes JSP and HTML files
    •   Specifies the deployment descriptor for the Web component
    •   Bundles the         ,    ,       , and deployment descriptor files in the
                    l m th . ps j. s sa lc .
        WAR file

J2EE Application Client Developer
An application client developer performs the following tasks to deliver a JAR
file containing the J2EE application client:
    • Writes and compiles the source code
    • Specifies the deployment descriptor for the client
    • Bundles the         files and deployment descriptor into the JAR file
                    ss al c.


Application Assembler
The application assembler is the company or person who receives application
component JAR files from component providers and assembles them into a J2EE
application EAR file. The assembler or deployer can edit the deployment
descriptor directly or use tools that correctly add XML tags according to interac-
tive selections. A software developer performs the following tasks to deliver an
EAR file containing the J2EE application:
    • Assembles EJB JAR and WAR files created in the previous phases into a
      J2EE application (EAR) file.
    • Specifies the deployment descriptor for the J2EE application
14                                        OVERVIEW



           • Verifies that the contents of the EAR file are well formed and comply with
             the J2EE specification

       Application Deployer and Administrator
       The application deployer and administrator is the company or person who con-
       figures and deploys the J2EE application, administers the computing and net-
       working infrastructure where J2EE applications run, and oversees the runtime
       environment. Duties include such things as setting transaction controls and secu-
       rity attributes and specifying connections to databases.
       During configuration, the deployer follows instructions supplied by the applica-
       tion component provider to resolve external dependencies, specify security set-
       tings, and assign transaction attributes. During installation, the deployer moves
       the application components to the server and generates the container-specific
       classes and interfaces.
       A deployer/system administrator performs the following tasks to install and con-
       figure a J2EE application:
           • Adds the J2EE application (EAR) file created in the preceding phase to the
             J2EE server
           • Configures the J2EE application for the operational environment by mod-
             ifying the deployment descriptor of the J2EE application
           • Verifies that the contents of the EAR file are well formed and comply with
             the J2EE specification
           • Deploys (installs) the J2EE application EAR file into the J2EE server


     Reference Implementation Software
       The J2EE SDK is a noncommercial operational definition of the J2EE platform
       and specification made freely available by Sun Microsystems for demonstra-
       tions, prototyping, and educational use. It comes with the J2EE application
       server, Web server, relational database, J2EE APIs, and complete set of develop-
       ment and deployment tools. You can download the J2EE SDK from the Web

           k d s# lm th . da ol n wo d/ ee 2 j/ mo c .n us .a v aj // :p t th

       The purpose of the J2EE SDK is to allow product providers to determine what
       their implementations must do under a given set of application conditions, and to
       run the J2EE Compatibility Test Suite to test that their J2EE products fully com-
                                    REFERENCE IMPLEMENTATION SOFTWARE                15


ply with the specification. It also allows application component developers to
run their J2EE applications on the J2EE SDK to verify that applications are fully
portable across all J2EE products and tools.

Database Access
The relational database provides persistent storage for application data. A J2EE
implementation is not required to support a particular type of database, which
means that the database supported by different J2EE products can vary. See the
Release Notes included with the J2EE SDK download for a list of the databases
currently supported by the reference implementation.

J2EE APIs
The Java 2 Platform, Standard Edition (J2SE™) SDK is required to run the J2EE
SDK and provides core APIs for writing J2EE components, core development
tools, and the Java virtual machine. The J2EE SDK provides the following APIs
to be used in J2EE applications.

Enterprise JavaBeans Technology 2.0
An enterprise bean is a body of code with fields and methods to implement mod-
ules of business logic. You can think of an enterprise bean as a building block
that can be used alone or with other enterprise beans to execute business logic on
the J2EE server.
There are three kinds of enterprise beans: session beans, entity beans, and mes-
sage-driven beans. Enterprise beans often interact with databases. One of the
benefits of entity beans is that you do not have to write any SQL code or use the
JDBC™ API directly to perform database access operations; the EJB container
handles this for you. However, if you override the default container-managed
persistence for any reason, you will need to use the JDBC API. Also, if you
choose to have a session bean access the database, you have to use the JDBC
API.

JDBC API 2.0
The JDBC API lets you invoke SQL commands from Java programing language
methods. You use the JDBC API in an enterprise bean when you override the
default container-managed persistence or have a session bean access the data-
base. With container-managed persistence, database access operations are han-
dled by the container, and your enterprise bean implementation contains no
JDBC code or SQL commands. You can also use the JDBC API from a servlet or
16                                      OVERVIEW



     JSP page to access the database directly without going through an enterprise
     bean.
     The JDBC API has two parts: an application-level interface used by the applica-
     tion components to access a database, and a service provider interface to attach a
     JDBC driver to the J2EE platform.

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

     JavaServer Pages Technology 1.2
     JavaServer Pages technology lets you put snippets of servlet code directly into a
     text-based document. A JSP page is a text-based document that contains two
     types of text: static template data, which can be expressed in any text-based for-
     mat such as HTML, WML, and XML, and JSP elements, which determine how
     the page constructs dynamic content.

     Java Message Service 1.0
     The JMS is a messaging standard that allows J2EE application components to
     create, send, receive, and read messages. It enables distributed communication
     that is loosely coupled, reliable, and asynchronous. For more information on
     JMS, see the online Java Message Service Tutorial:

         lm th .x e dn i/ l ai ro tu t /s mj / st cu do r p/ mo c .n us .a v aj // :p t th

     Java Naming and Directory Interface 1.2
     The JNDI provides naming and directory functionality. It provides applications
     with methods for performing standard directory operations, such as associating
     attributes with objects and searching for objects using their attributes. Using
     JNDI, a J2EE application can store and retrieve any type of named Java object.
     Because JNDI is independent of any specific implementations, applications can
     use JNDI to access multiple naming and directory services, including existing
     naming and directory services such as LDAP, NDS, DNS, and NIS. This allows
     J2EE applications to coexist with legacy applications and systems. For more
     information on JNDI, see the online JNDI Tutorial:
                                            REFERENCE IMPLEMENTATION SOFTWARE              17


    l m th .x ed n i/ la i ro tu t/ i dn j/ s tc ud or p /m oc .n u s. av a j/ /: pt t h

Java Transaction API 1.0
The Java Transaction API (JTA) provides a standard interface for demarcating
transactions. The J2EE architecture provides a default auto commit to handle
transaction commits and rollbacks. An auto commit means that any other appli-
cations viewing data will see the updated data after each database read or write
operation. However, if your application performs two separate database access
operations that depend on each other, you will want to use the JTA API to
demarcate where the entire transaction, including both operations, begins, rolls
back, and commits.

JavaMail™ API 1.2
J2EE applications can use the JavaMail API to send e-mail notifications. The
JavaMail API has two parts: an application-level interface used by the applica-
tion components to send mail, and a service provider interface. The J2EE plat-
form includes JavaMail with a service provider that allows application
components to send Internet mail.

JavaBeans Activation Framework 1.0
The JavaBeans Activation Framework (JAF) is included because JavaMail uses
it. It provides standard services to determine the type of an arbitrary piece of
data, encapsulate access to it, discover the operations available on it, and create
the appropriate JavaBeans component to perform those operations.

Java API for XML Processing 1.1
XML is a language for representing text-based data so the data can be read and
handled by any program or tool. Programs and tools can generate XML docu-
ments that other programs and tools can read and handle. Java API for XML
Processing (JAXP) supports processing of XML documents using DOM, SAX,
and XSLT. JAXP enables applications to parse and transform XML documents
independent of a particular XML processing implementation.
For example, a J2EE application can use XML to produce reports, and different
companies that receive the reports can handle the data in a way that best suits
their needs. One company might put the XML data through a program to trans-
late the XML to HTML so it can post the reports to the Web, another company
might put the XML data through a tool to create a marketing presentation, and
yet another company might read the XML data into its J2EE application for pro-
cessing.
18                                 OVERVIEW



     J2EE Connector Architecture 1.0
     The J2EE Connector Architecture is used by J2EE tools vendors and system
     integrators to create resource adapters that support access to enterprise informa-
     tion systems that can be plugged into any J2EE product. A resource adapter is a
     software component that allows J2EE application components to access and
     interact with the underlying resource manager. Because a resource adapter is
     specific to its resource manager, there is typically a different resource adapter for
     each type of database or enterprise information system.

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

     Simplified Systems Integration
     The J2EE platform is a platform-independent, full systems integration solution
     that creates an open marketplace in which every vendor can sell to every cus-
     tomer. Such a marketplace encourages vendors to compete, not by trying to lock
     customers into their technologies but by trying to outdo each other by providing
     products and services that benefit customers, such as better performance, better
     tools, or better customer support.
     The J2EE APIs enable systems and applications integration through the follow-
     ing:
         • Unified application model across tiers with enterprise beans
         • Simplified response and request mechanism with JSP pages and servlets
         • Reliable security model with JAAS
         • XML-based data interchange integration with JAXP
         • Simplified interoperability with the J2EE Connector Architecture
         • Easy database connectivity with the JDBC API
         • Enterprise application integration with message-driven beans and JMS,
           JTA, and JNDI
     You can learn more about using the J2EE platform to build integrated business
     systems by reading J2EE Technology in Practice:
                                            REFERENCE IMPLEMENTATION SOFTWARE                  19


    l m th .k oo b eh tt u ob a/ ec i tc ar p ni /e e2 j /m oc .n u s. av a j/ /: pt t h

Tools
The J2EE reference implementation provides an application deployment tool
and an array of scripts for assembling, verifying, and deploying J2EE applica-
tions and managing your development and production environments. See
Appendix B for a discussion of the tools.

Application Deployment Tool
The J2EE reference implementation provides an application deployment tool
(            ) for assembling, verifying, and deploying J2EE applications. There
l oo ty o lp ed
are two versions: command line and GUI.
The GUI tool includes wizards for
    •     Packaging, configuring, and deploying J2EE applications
    •     Packaging and configuring enterprise beans
    •     Packaging and configuring Web components
    •     Packaging and configuring application clients
    •     Packaging and configuring resource adaptors
In addition, configuration information can be set for each component and mod-
ule type in the tabbed inspector panes.

Scripts
Table 1–1 lists the scripts included with the J2EE reference implementation that
let you perform operations from the command line.


Table 1–1 J2EE Scripts

 Script            Description

 ee2j              Start and stop the J2EE server

 epacsduolc        Start and stop the default database

 nimdaee2j         Add JDBC drivers, JMS destinations, and connection factories for various
                   resources

 lootyek           Create public and private keys and generate X509 self-signed certificate.
20                                 OVERVIEW


     Table 1–1 J2EE Scripts (Continued)

      Script         Description

      lootmlaer      Import certificate files. Add J2EE users to and remove J2EE users from the
                     authentication and authorization list for a J2EE application

      regakcap       Package J2EE application components into EAR, EJB JAR, application cli-
                     ent JAR, and WAR files

      reifirev       Verify that EAR, EJB JAR, application client JAR, and WAR files are well-
                     formed and comply with the J2EE specification

      tneilcnur      Run a J2EE application client

      punaelc        Remove all deployed applications from the J2EE server
                                   2
                     Getting Started
                                                                     Dale Green



T   HIS chapter shows how to develop, deploy, and run a simple client-server
application that consists of a currency conversion enterprise bean and two cli-
ents: a J2EE™ application client and a Web client that consists of a JSP page.

In This Chapter
          Setting Up 22
               Getting the Example Code 22
               Getting the Build Tool (ant) 22
               Checking the Environment Variables 23
               Starting the J2EE™ Server 23
               Starting the deploytool 23
          Creating the J2EE™ Application 24
          Creating the Enterprise Bean 24
               Coding the Enterprise Bean 24
               Compiling the Source Files 26
               Packaging the Enterprise Bean 27
          Creating the J2EE™ Application Client 28
               Coding the J2EE Application Client 28
               Compiling the Application Client 31
               Packaging the J2EE Application Client 31
               Specifying the Application Client’s Enterprise Bean Reference 32
          Creating the Web Client 32
               Coding the Web Client 33
               Compiling the Web Client 34
               Packaging the Web Client 34
               Specifying the Web Client’s Enterprise Bean Reference 35
                                                                                  21
22                                          GETTING STARTED


                    Specifying the JNDI Names 36
                    Deploying the J2EE™ Application 37
                    Running the J2EE™ Application Client 38
                    Running the Web Client 38
                    Modifying the J2EE™ Application 39
                        Modifying a Class File 39
                        Adding a File 40
                        Modifying the Web Client 40
                        Modifying a Deployment Setting 41
                    Common Problems and Their Solutions 41
                        Cannot Start the J2EE Server 41
                        Compilation Errors 42
                        Deployment Errors 43
                        J2EE Application Client Runtime Errors 44
                        Web Client Runtime Errors 45
                        Detecting Problems With the Verifier Tool 46
                        Comparing Your EAR Files with Ours 46
                        When All Else Fails 46


     Setting Up
       Before you start developing the example application, you should follow the
       instructions in this section.

       Getting the Example Code
       The      source     code     the components is in
                                     for                                          m ax e /l ai r ot ut ee 2 j
                                  , a directory that is created when you unzip the tuto-
       r et re v no c/ bj e /c rs /s e lp
       rial bundle. If you are viewing this tutorial online, you need to download the
       tutorial bundle from

             l a ir ot u t# lm th . da ol n wo d/ ee 2 j/ mo c .n us .a v aj // :p t th

       Getting the Build Tool (ant)
       To build the example code, you’ll need installations of the J2EE SDK and    ,a                 tn a
       portable make tool. For more information, see the section How to Build and Run
       the Examples, page (xxii).
                                      SETTING UP                                               23


Checking the Environment Variables
The installation instructions for the J2EE SDK and       explain how to set the
                                                                tn a
required environment variables. Verify that the environment variables have been
set to the values noted in Table 2–1.


Table 2–1 Required Environment Variables

 Environment Variable     Value

 EMOH_AVAJ                The location of the J2SE™ SDK installation.

 EMOH_EE2J                The location of the J2EE™ SDK installation.

 EMOH_TNA                 The location of the   tna   installation.

                          Should include the    nib   directories of the J2EE SDK, J2SE, and
 HTAP
                          tna installations.




Starting the J2EE™ Server
To launch the J2EE server, open a terminal window and type this command:

    ee 2 j   es ob r ev

Although not required, the   e so br ev   option is useful for debugging.
To stop the server, type the following command:

    ee 2 j   p o ts

Starting the deploytool
The lo o ty ol p edutility has two modes: command line and GUI. The instructions
in this chapter refer to the GUI version. To start the          GUI, open a ter-
                                                             l oo t yo lp ed
minal window and type this command:

    l o ot yo lp e d

To view the tool’s context-sensitive help, press the         1F   key.
24                                       GETTING STARTED



     Creating the J2EE™ Application
       The sample application contains three J2EE components: an enterprise bean, a
       J2EE application client, and a Web component. Before building these compo-
       nents, you will create a new J2EE application called                and will
                                                                               p pA re t re vn oC
       store it in an EAR file named                 .
                                           r a e. pp A re tr ev n oC
           1. In              , select File→New→Application.
                  l oo ty o lp ed
           2. Click Browse.
           3. In the file chooser, navigate to        n oc / bj e/ c rs /s el p ma xe / la ir ot u te e2 j
                      .
              r et re v
           4. In the File Name field, enter                  .
                                                   r ae .p pA r et re v no C
           5. Click New Application.
           6. Click OK.


     Creating the Enterprise Bean
       An enterprise bean is a server-side component that contains the business logic of
       an application. At runtime, the application clients execute the business logic by
       invoking the enterprise bean’s methods. The enterprise bean in our example is a
       stateless session bean called
                                B JE re t re vn oC . The source code for                  BJ Er e tr ev n oC
       is in the                                                 directory.
                re tr e vn oc / bj e/ cr s /s el pm a xe /l a ir ot ut e e2 j


       Coding the Enterprise Bean
       The enterprise bean in this example requires the following code:
           • Remote interface
           • Home interface
           • Enterprise bean class

       Coding the Remote Interface
       A remote interface defines the business methods that a client may call. The busi-
       ness methods are implemented in the enterprise bean code. The source code for
       the            remote interface follows.
          r et r ev no C

                   ; tc ej b OB JE . bj e. xa v aj t ro p mi
           ; no i tp ec xE e to me R .i mr .a v aj t ro p mi
                                ;* . ht am .a v aj t ro p mi
                                                                                           }
                   ; )P U_ DN U OR .l a mi ce Dg i B, 2( e la cS te s .t lu se r n ru t er
                   ; )e ta Rn e y( yl p it lu m. s ra ll o d = tl u se r la m ic eD g iB
                 { ) sr al lo d l am i ce Dg iB ( ne Yo T ra ll od la mi ce D gi B c il bu p
                       ;) " 77 00 . 0" (l am i ce Dg i B we n = e ta Ro r ue l a mi ce Dg i B
                     ; )" 0 00 6. 1 21 "( la m ic eD g iB w en = et aR n ey l a mi ce Dg i B
                      { na eB n oi ss e S st ne m el pm i n ae Br e tr ev no C s sa l c ci lb u p
                                                                       ; *. ht a m. av a j    tr op m i
                                                   ;t xe t no Cn oi s se S. bj e .x av a j    tr op m i
                                                       ; n ae Bn oi s se S. bj e .x av a j    tr op m i
                                                   ;n oi t pe cx Ee t om eR .i m r. av a j    tr op m i
                          class follows.
     n ae Br e tr ev n oC             remote interface defines. The source code for the       r et re vn o C
       , that theo ru Eo T ne y       n eY o Tr al lo d
                          implements the two business methods,                 and
     . This class   na eB r et re v no C
                          The enterprise bean class for this example is called
                                                   Coding the Enterprise Bean Class
                                                                                                     }
     ; no it p ec xE e ta er C , n oi tp e cx Ee to m eR sw o rh t ) (e t ae rc r et re vn o C
                          { e m oH BJ E s dn et x e em o Hr et re v no C ec a fr et n i ci lb u p
                                                               ;e mo H BJ E. bj e .x av a j   tr op m i
                                                  ; no it p ec xE et a er C. bj e .x av a j   tr op m i
                                                    ;n oi t pe cx Ee t om eR .i m r. av a j   tr op m i
                                                          ; el ba zi l ai re S. o i. av a j   tr op m i
     source code for the               interface:            em oH r et re vn o C
     ate method, which returns an object of the remote interface type. Here is the
     remove an enterprise bean. The          em oH r et re vn o C
                                                   interface contains a single cre-
     A home interface defines the methods that allow a client to create, find, or
                                                            Coding the Home Interface
                                                                                                     }
                                                       ; n oi tp ec x Ee to me R s wo r ht
                             ) n ey l a mi ce Dg i B( or u Eo Tn ey la mi ce D gi B c il bu p
                                                       ; n oi tp ec x Ee to me R s wo r ht
                    ) sr al lo d l am i ce Dg iB ( ne Yo T ra ll od la mi ce D gi B c il bu p
                             { tc ej b OB JE s d ne tx e r et re v no C ec a fr et n i ci lb u p
25                           CREATING THE ENTERPRISE BEAN
26                                      GETTING STARTED


                    { ) ne y l am ic eD g iB (o r uE oT ne y l am i ce Dg iB ci lb up
                  ; )e t aR or u e( yl pi t lu m. n ey = t l us er la mi ce D gi B
              ;) PU _D N UO R. l am ic eD g iB ,2 ( el ac St e s. tl u se r nr u te r
                                                                                      }

              ci lb up                                           }{ ) (n a eB re t re vn oC
              ci lb up                                         } { )( et a er Cb j e di ov
              ci lb up                                         } { )( ev o me Rb j e di ov
              ci lb up                                      }{ )( et av i tc Ab j e di ov
              ci lb up                                    } { ) (e ta vi s sa Pb j e di ov
              ci lb up   } { ) cs t x et no C no is se S (t xe t no Cn oi s se St e s di ov
          }

     Compiling the Source Files
     Now you are ready to compile the remote interface (                                      ), home
                                                                                  av aj .r e tr ev n oC
     interface (
     av a j. em o Hr et re v no C ), and the enterprise bean class (     r et r ev no C
                 ):              av aj .n a eB
          1. In a terminal window, go to the        se l pm ax e/ l ai ro t ut ee 2j   directory.
          2. Type the following command:

          r et r ev no c t na

     This command compiles the source files for the enterprise bean and the J2EE
     application client. It places the resulting class files in the         m ax e /l ai r ot ut ee 2 j
                                     directory (not the
     re t re vn o c/ bj e/ d li ub /s e lp                     directory). For more infor-
                                                                cr s
     mation about      , see How to Build and Run the Examples, page (xxii).
                    t na


        Note: When compiling the code, the preceding         task includes the
                                                            tna                         file
                                                                                       raj.ee2j
        in the classpath. This file resides in the directory of your J2EE SDK installation.
                                                  bil
        If you plan on using other tools to compile the source code for J2EE components,
        make sure that the classpath includes the           file.
                                                      raj.ee2j



     Packaging the Enterprise Bean
     To package an enteprise bean, you run the New Enterprise Bean wizard of the
                utility. During this process, the wizard performs the following tasks.
     l oo ty ol p ed
          • Creates the bean’s deployment descriptor
          • Packages the deployment descriptor and the bean’s classes in an EJB JAR
            file
          • Inserts the EJB JAR file into the application’s                   file
                                                                       ra e. p pA re t re vn oC
                                        CREATING THE ENTERPRISE BEAN                                   27


During the packaging process, you can view the deployment descriptor by
selecting Tools→Descriptor Viewer.
To start the New Enterprise Bean wizard, select File→New→Enterprise Bean.
The wizard displays the following dialog boxes.
   1. Introduction dialog box
      a. Read the explanatory text for an overview of the wizard’s features.
      b. Click Next.
   2. EJB JAR dialog box
      a. Select the Create New JAR File In Application button.
      b. In the combo box, select                  .
                                        p pA r et re v no C
      c. In the JAR Display Name field, enter                   .
                                                        R A Jr et re v no C
      d. Click Edit.
      e. In the tree under Available Files, locate the               ma xe / la ir o tu te e2 j
                                         directory. (If the
         re tr ev n oc /b j e/ dl iu b /s el p                         directory is
                                                                                  r et r ev no c
         many levels down in the tree, you can simplify the tree view by enter-
         ing all or part of the             directory’s path name in the Starting
                                   r et re v no c
         Directory field.)
      f. Select the following classes from the Available Files tree and click
         Add:                      ,                          , and
         s sa lc . na eB r et re vn o C s sa lc .r e tr ev n oC                        re tr e vn oC
                       . (You may also drag and drop these class files to the Con-
                                                        ss al c .e mo H
         tents text area.)
      g. Click OK.
      h. Click Next.
   3. General dialog box
      a. Under Bean Type, select the Session radio button.
      b. Select the Stateless radio button.
      c. In the Enterprise Bean Class combo box, select               na eB re t re vn o C    .
      d. In the Enterprise Bean Name field, enter             B JE re tr e vn oC   .
      e. In the Remote Home Interface combo box, select                 e m oH re t re vn oC      .
      f. In the Remote Interface combo box, select               re tr e vn oC.
      g. Click Next.
   4. Transaction Management dialog box
      Because you may skip the remaining dialog boxes, click Finish.
28                                         GETTING STARTED



     Creating the J2EE™ Application Client
       A J2EE application client is a program written in the Java™ programming lan-
       guage. At runtime, the client program executes in a different virtual machine
       than the J2EE server.
       The J2EE application client in this example requires two different JAR files. The
       first JAR file is for the J2EE component of the client. This JAR file contains the
       client’s deployment descriptor and its class files. When you run the New Appli-
       cation Client wizard, the               utility automatically creates the JAR file
                                       l o ot yo l pe d
       and stores it in the application’s EAR file. Defined by the J2EE Specification,
       the JAR file is portable across all compliant J2EE servers.
       The second JAR file contains stub classes that are required by the client program
       at run time. These stub classes enable the client to access the enterprise beans
       that are running in the J2EE server. Because this second JAR file is not covered
       by the J2EE Specification, it is implementation specific, intended only for the
       J2EE SDK.
       The J2EE application client source code is in                         m ax e /l ai r ot ut ee 2 j
                                                          . You already compiled this
       av a j. tn ei l Cr et r ev no C/ r et re v no c/ bj e /c rs /s e lp
       code along with the enterprise bean code in the section Compiling the Source
       Files, page (26).

       Coding the J2EE Application Client
       The                             source code illustrates the basic tasks performed
             a va j. tn e il Cr e tr ev no C
       by the client of an enterprise bean:
            • Locating the home interface
            • Creating an enterprise bean instance
            • Invoking a business method

       Locating the Home Interface
       The                  interface defines life-cycle methods such as
            e m oH re tr e vn oC                                                  . Before
                                                                                     e t ae rc
       the                    can invoke the
           tn ei l Cr et re v no C         e ta er c   method, it must locate and instan-
       tiate an object whose type is                 . This is a four-step process.
                                            e mo H re tr e vn oC
            1. Create an initial naming context.

             ;) (t xe t no Cl a it in I w en = la it in i t xe tn o C
                                                CREATING THE J2EE™ APPLICATION CLIENT                       29


        The           interface is part of the Java Naming and Directory Interface
              t xe tn oC
        (JNDI). A naming context is a set of name-to-object bindings. A name
        that is bound within a context is the JNDI name of the object.
        An                       object, which implements the
              tx et n oC la it i nI                                      interface,
                                                                                t xe t no C
        provides the starting point for the resolution of names. All naming opera-
        tions are relative to a context.
     2. Obtain the environment naming context of the application client.

     ; )" vn e /p mo c: a va j" ( pu ko ol . la it i ni )t xe t no C( = vn Ey m t xe tn o C

        The    vn e/ p mo c: av a jname is bound to the environment naming context of
        the  t ne il C re tr e vn oCcomponent.
     3. Retrieve the object bound to the name              re tr e vn oC el p mi S/ b je  .

     ; )" re tr e vn oC e lp mi S/ b je "( p uk oo l. v nE ym = fe rj b o tc ej b O

        The                          name is bound to an enterprise bean refer-
               r e tr ev no C el pm iS / bj e
        ence, a logical name for the home of an enterprise bean. In this case, the
                                name refers to the
        r et re v no Ce l pm iS /b j e                                object. The
                                                                              e mo Hr e tr ev n oC
        names of enterprise beans should reside in the                        sub-
                                                                    b j e/ vn e/ m oc :a va j
        context.
     4. Narrow the reference to a           e mo Hr e tr ev n oC   object.

                                                           = e mo h e mo H re tr ev n oC
      ,f er jb o (w or r an .t ce j bO et o me Re lb a tr oP ) e mo Hr e tr ev no C (
                                              ; )s sa lc . em oH r et re vn o C

Creating an Enterprise Bean Instance
To create the bean instance, the client invokes the         method on the
                                                                    e ta er c                        no C
             object. The
e m oH re tr e v                  method returns an object whose type is
                           e t ae rc                                                                 no C
       . The remote
       re tr e v                  interface defines the business methods of the
                           r et r ev no C
bean that the client may call. When the client invokes the          method, the            et ae r c
EJB container instantiates the bean and then invokes the                     bj e. n ae Br e tr ev no C
        method. The client invokes the
et ae r C                                       method as follows:
                                                    et ae rc

     ;) (e t ae rc .e m oh = re tr ev n oC yc ne r ru c r et re vn o C
;) " !n oi tp e cx e d et ce p xe nu na th gu aC " (n lt n ir p. rr e .m et sy S
                                             { ) xe n oi t pe cx E ( hc ta c }
                                                        ;) 0( t ix e. m et sy S
                                      ;) tn u om a( n lt ni rp . tu o. m et sy S
           ;) m ar ap (o r uE oT n ey .r et r ev no C yc ne rr u c = t nu om a
                                      ;) tn u om a( n lt ni rp . tu o. m et sy S
                 ; )m ar a p( ne Y oT ra ll o d. re t re vn oC y cn er r uc
                                                  = tn uo ma la mi c eD gi B
         ; )" 0 0. 00 1" ( l am i ce Dg iB we n = m ar ap la mi c eD gi B
           ;) ( et ae rc . em oh = re tr e vn oC y cn er ru c r et r ev no C
;) s sa lc .e m oH re t re vn oC
 ,f er j bo (w o rr an .t c ej bO et o me Re l ba tr oP ) em oH r et re vn o C(
                                                = e mo h em o Hr et r ev no C
               ;) "r et r ev no C el pm iS / bj e/ v ne /p mo c :a va j "(
                                p uk oo l. l ai ti n i = fe r jb o t ce jb O
                  ;) (t x et no C la it in I w en = la it i ni t x et no C
                                                                           { y rt
                             { ) sg ra ] [ gn ir t S( ni am di ov ci ta ts ci lb up
                                                  { tn ei lC r et re v no C ss a lc c il b up
                                                                ;e mo H re tr ev n oC t ro p mi
                                                                      ; re tr ev n oC t ro p mi
                                                     ;l am ic e Dg iB . ht am .a v aj   t ro p mi
                                     ;t ce j bO et o me Re lb a tr oP . im r. xa v aj   t ro p mi
                                         ; t xe tn o Cl ai ti n I. gn i ma n. xa v aj   t ro p mi
                                                     ;t xe tn o C. gn i ma n. xa v aj   t ro p mi
                   program follows.       t n ei lC re t re vn o C   The full source code for the
                                                    ConverterClient Source Code
        ;) ma r ap (n eY o Tr al l od .r et r ev no C yc ne rr u c = t nu om a l am ic eD g iB
                           ;) "0 0 .0 01 "( la mi c eD gi B w en = ma ra p l am ic eD g iB
          business method in the following lines of code.                                n eY oT r al
 l od           instance that is running on the server. The client invokes the     BJ E re tr ev n oC
        object. The EJB container will invoke the corresponding method on the               r et r ev
 n oC
Calling a business method is easy—you simply invoke the method on the
                                                       Invoking a Business Method
                                                GETTING STARTED                                         30
                                            CREATING THE J2EE™ APPLICATION CLIENT                         31


                      ;) (e c ar Tk ca t St ni rp . xe
              }
        }
    }

Compiling the Application Client
The application client files are compiled at the same time as the enterprise bean
files, as described in Compiling the Source Files, page (26).

Packaging the J2EE Application Client
To package an application client component, you run the New Application Client
wizard of the             . During this process the wizard performs the follow-
                  l oo ty ol p ed
ing tasks.
    • Creates the application client’s deployment descriptor
    • Puts the deployment descriptor and client files into a JAR file
    • Adds the JAR file to the application’s                     file
                                                         r ae .p pA r et re v no C
During the packaging process you can view the deployment descriptor by select-
ing Tools→Descriptor Viewer.
To start the New Application Client wizard, select File→New→Application Cli-
ent. The wizard displays the following dialog boxes.
    1. Introduction dialog box
       a. Read the explanatory text for an overview of the wizard’s features.
       b. Click Next.
    2. JAR File Contents dialog box
       a. In the combo box, select                .
                                            p pA r et re v no C
       b. Click Edit.
       c. In the tree under Available Files, locate the                   ma xe / la ir o tu te e2 j
                                      directory.
            re tr ev n oc /b j e/ dl iu b /s el p
       d. Select the                          file and click Add.
                          ss al c .t ne il C re tr e vn oC
       e. Click OK.
       f. Click Next.
    3. General dialog box
        a. In the Main Class combo box, select               tn e il Cr et r ev no C   .
        b. Verify that the entry in the Display Name field is               tn ei lC r et re v no C   .
32                                          GETTING STARTED



                 c. In the Callback Handler Class combo box, select container-managed
                    authentication.
                 d. Click Next.
                 e. Click Finish.

       Specifying the Application Client’s Enterprise Bean
       Reference
       When it invokes the      pu ko o l   method, the     t n ei lC r et re vn o C   refers to the home of
       an enterprise bean:

            ;) "r et r ev no C el pm iS / bj e" ( pu ko ol . vn Ey m = f er j bo t ce j bO

       You specify this reference as follows.
            1.   In the tree, select                 .
                                      tn ei lC r et re v no C
            2.   Select the EJB Refs tab.
            3.   Click Add.
            4.   In the Coded Name column, enter             re tr ev n oC el p mi S/ bj e     .
            5.   In the Type column, select Session.
            6.   In the Interfaces column, select Remote.
            7.   In the Home Interface column, enter            e m oH re tr e vn oC   .
            8.   In the Local/Remote Interface column, enter              r et r ev no C   .


     Creating the Web Client
       The Web client is contained in the JSP page                                m ax e /l ai r ot ut ee 2 j
                                               . A JSP page is a text-based document
       p sj . xe dn i/ r et re v no c/ bj e /c rs /s e lp
       that contains static template data, which can be expressed in any text-based for-
       mat such as HTML, WML, and XML; and JSP elements, which construct
       dynamic content.

       Coding the Web Client
       The statements (in bold in the following code) for locating the home interface,
       creating an enterprise bean instance, and invoking a business method are nearly
       identical to those of the J2EE application client. The parameter of the                       pu ko o l
       method is the only difference; the motivation for using a different name is dis-
       cussed in Specifying the JNDI Names, page (35).
                                             > " te se R "= eu la v " te se r "= ep y t tu pn i <
                                          > "t i mb uS " =e ul av "t im bu s "= ep y t tu pn i <
                                                                                              >p<
                                                                                             >r b <
                               > "5 2 "= ez is "t nu o ma "= em a n "t xe t "= ep y t tu pn i <
                                                                     > "t eg " =d oh t em m ro f <
                                             > p /< :t r ev no c o t tn uo m a na re tn E> p <
                                                                                             >r h <
                                            >1 h /< >r e tn ec /< r et re vn o C> re t ne c< >1 h <
                                                                > " et ih w" = ro lo c gb y do b <
                                                                                        > da eh / <
                                                       >e lt i t/ <r et r ev no C >e lt it <
                                                                                          >d ae h <
                                                                                          >l mt h <
                                                                                                >%
                                                                                         ...
                                                                                             }
                                                                                      }
                                                                            ...
                                         { ) xe n oi t pe cx Ee t om eR ( h ct ac }
                                        ; )( et a er c. em o h = r et re vn o c
                                   ; )s s al c. e mo Hr et r ev no C , fe Rj b o
             ( wo r ra n. tc e jb Oe to m eR el b at ro P) e mo Hr e tr ev no C (
                                                  = em oh em oH r et re vn o C
                      ; )" re tr e vn oC e hT /b je / vn e/ p mo c: av a j
                                      " ( pu ko o l. ci = fe Rj b o tc ej b O
                ; ) (t xe tn o Cl ai ti n I we n = c i t xe tn o Cl ai ti n I
                                                                                { yrt
                                                           { ) (t in Ip s j di o v ci lb u p
                                        ;l l un = re tr ev n oc r et r ev no C e ta vi r p
                                                                                               !%<
                                                        > % "n oi t pe cx Ee t om eR . im r. av a j
                          ,t c ej bO e to me Re l ba tr o P. im r. x av aj , * .g ni m an .x av a j
                , * .b je .x a va j, e mo Hr et r ev no C ,r et re v no C" =t r op mi eg ap @ % <
     stream of data returned to the client.
     invoke the enterprise bean’s business methods and insert the result into the
                 >% =%<
     it to a double. Finally, JSP expressions (enclosed within              characters)
     within the                                                                   > % %<
                       characters) retrieves a parameter from the request and converts
     HTML markup for creating a form with an input field. A scriptlet (enclosed
     method,           , of the JSP page. The declaration is followed by standardti nI p sj
     tion (enclosed within the                            >% !% <
                                            characters) that contains the initialization
     the enterprise bean are performed only once, this code appears in a JSP declara-
     within the                                                                  > % @ %<
                        characters). Because locating the home interface and creating
                          eg ap
     The classes needed by the client are declared with a JSP       directive (enclosed
33                              CREATING THE WEB CLIENT
34                                     GETTING STARTED


                                                                           >m ro f /<
                                                                                   %<
          ;) " tn uo m a" (r et e ma ra P te g. ts e uq er = tn uo m a gn ir t S
             { ) 0 > )( ht g ne l. t nu om a & & ll un =! t n uo ma ( fi
                 ; )t nu o ma ( l am ic eD g iB w en = d l am ic eD g iB
                                                                                   >%
                                          er a sr a ll od > % t nu o ma = %< > p<
                    . ne Y >% )d (n eY o Tr al lo d .r et r ev no c = %<
                                                er a n eY > % t nu o ma = %< > p<
                      .o r uE > % )d (o r uE oT ne y .r et r ev no c = %<
                                                                                   %<
                                                                               }
                                                                                   >%
                                                                           >y do b /<
                                                                           >l mt h /<

     Compiling the Web Client
     The J2EE server automatically compiles Web clients that are JSP pages. If the
     Web client were a servlet, you would have to compile it.

     Packaging the Web Client
     To package a Web client, you run the New Web Component wizard of the
                utility. During this process the wizard performs the following tasks.
     l oo ty ol p ed
          • Creates the Web application deployment descriptor
          • Adds the component files to a WAR file
          • Adds the WAR file to the application’s          r ae . pp Ar et r ev no C   file
     During the packaging process, you can view the deployment descriptor by
     selecting Tools→Descriptor Viewer.
     To start the New Web Component wizard, select File→New→Web Component.
     The wizard displays the following dialog boxes.
          1. Introduction dialog box
             a. Read the explanatory text for an overview of the wizard’s features.
             b. Click Next.
          2. WAR File dialog box
             a. Select Create New WAR File In Application.
             a. In the combo box, select             .
                                               pp A re tr e vn oC
             b. In the WAR Display Name field, enter           RA Wr e tr ev no C   .
                                             SPECIFYING THE JNDI NAMES                                 35


           c. Click Edit.
           d. In the tree under Available Files, locate the               ma xe / la ir o tu te e2 j
                                          directory.
              re tr ev n oc /b j e/ dl iu b /s el p
           e. Select           and click Add.
                      p sj .x ed n i
           f. Click OK.
           g. Click Next.
      3. Choose Component Type dialog box
         a. Select the JSP radio button.
         b. Click Next.
      4. Component General Properties dialog box
           a. In the JSP Filename combo box, select             p sj .x e dn i      .
           b. Click Finish.

  Specifying the Web Client’s Enterprise Bean
  Reference
  When it invokes the       p u ko ol   method, the Web client refers to the home of an
  enterprise bean:

      ; )" r et re v no Ce hT / bj e/ v ne /p mo c :a va j "( pu ko o l. ci = fe Rj b o tc ej b O

  You specify this reference as follows:
      1.   In the tree, select              .
                                RA Wr e tr ev n oC
      2.   Select the EJB Refs tab.
      3.   Click Add.
      4.   In the Coded Name column, enter            re tr e vn oC e hT /b je      .
      5.   In the Type column, select Session.
      6.   In the Interfaces column, select Remote.
      7.   In the Home Interface column, enter           em o Hr et re v no C   .
      8.   In the Local/Remote Interface column, enter             re tr ev n oC        .


Specifying the JNDI Names
  Although the J2EE application client and the Web client access the same enter-
  prise bean, their code refers to the bean’s home by different names. The J2EE
36                                GETTING STARTED



     application client refers to the bean’s home as                          , but the
                                                           re tr e vn oC el p mi S/ b je
     Web client refers to it as                   . These references are in the param-
                                     r e tr ev no C eh T/ b je
     eters of thep uk oo lcalls. In order for the
                              pu ko ol                   method to retrieve the home
     object, you must map the references in the code to the enterprise bean’s JNDI
     name. Although this mapping adds a level of indirection, it decouples the clients
     from the beans, making it easier to assemble applications from J2EE compo-
     nents.
     To map the enterprise bean references in the clients to the JNDI name of the
     bean, follow these steps.
         1. In the tree, select             .
                              p pA r et re v no C
         2. Select the JNDI Names tab.
         3. To specify a JNDI name for the bean, in the Application table locate the
            ConverterEJB component and enter                  in the JNDI Name col-
                                                     r e tr ev n oC yM
            umn.
         4. To map the references, in the References table enter              in the
                                                                         re tr ev n oC yM
            JNDI Name for each row.
     Figure 2–1 shows what the JNDI Names tab should look like after you’ve per-
     formed the preceding steps.
                                              DEPLOYING THE J2EE™ APPLICATION                           37


  Figure 2–1 ConverterApp JNDI Names



Deploying the J2EE™ Application
  Now that the J2EE application contains the components, it is ready for deploy-
  ment.
      1. Select the                   application.
                        p pA r et re vn o C
      2. Select Tools→Deploy.
      3. In the Introduction dialog box, confirm that                      is shown for
                                                                  p pA r et re vn o C
         the Object To Deploy and that                   is shown for the Target Server.
                                                ts o hl ac ol
      4. Select the checkbox labeled Return Client Jar.
      5. In the text field that appears, enter the full path name for the file
                                                                     tr ev n oC
                                so that it will reside in the
                    r aj .t n ei lC p pA re                          ma xe / la ir o tu te e2 j
                                        subdirectory. The
         r et re v no c/ bj e /c rs / se lp                        r aj .t n ei lC p pA re tr e vn oC
         file contains the stub classes that enable remote access toBJ Er e tr ev no C .
      6. Click Next.
      7. In the JNDI Names dialog box, verify the names you entered in the previ-
         ous section.
      8. Click Next.
      9. In the WAR Context Root dialog box, enter                       in the Context
                                                                  r e tr ev n oc
         Root field. When you run the Web client, the                  context root will
                                                                    re t re vn oc
         be part of the URL.
      10. Click Next.
      11. In the Review dialog box, click Finish.
      12. In the Deployment Progress dialog box, click OK when the deployment
         completes.


Running the J2EE™ Application Client
  To run the J2EE application client, perform the following steps.
      1. In a terminal window, go to the         no c/ b je /c r s/ se lp m ax e/ l ai ro tu t ee 2j
         r e tr evdirectory.
      2. Verify that this directory contains the          ra e. pp A re tr e vn oC   and   tr ev n oC
                              files.
         r aj .t n ei lC p pA re
      3. Set the             environment variable to
                     HT A PC PP A                               ra j. t ne il C pp Ar et r ev no C.
38                                        GETTING STARTED



           4. Type the following command (on a single line):

           tn ei lc n ur    r ae .p p Ar et re v no C t ne il c    t ne i lC re tr e vn oC em an
           ht ua tx e t

           5. The client container prompts you to log in. Enter        for the user name
                                                                             t se ug
              and            for the password.
                    3 21 t se ug
           6. In the terminal window, the client displays these lines:

              ’r e tr ev n oC el pm i S/ bj e /v ne /p m oc :a v aj ’: em a n gn id n iB
                                                                             0 0. 06 1 21
                                                                                   7 7 .0
           ’r et r ev no C el pm iS / bj e/ v ne /p mo c :a va j ’: em an gn id ni b nU


     Running the Web Client
       To run the Web client, point your browser at the following URL. Replace                     >t so h <
       with the name of the host running the J2EE server. If your browser is running on
       the same host as the J2EE server, you may replace          with>t so h <   .    t so h la co l

           re tr ev n oc /0 0 08 :> ts o h < // :p t th

       You should see the screen shown in Figure 2–2 after entering                    00 1   in the input
       field and clicking Submit.
                                                MODIFYING THE J2EE™ APPLICATION                        39




  Figure 2–2 Converter Web Client


Modifying the J2EE™ Application
  Since the J2EE SDK is intended for experimentation, it supports iterative devel-
  opment. Whenever you make a change to a J2EE application, you must redeploy
  the application.

  Modifying a Class File
  To modify a class file in an enterprise bean, you change the source code, recom-
  pile it, and redeploy the application. For example, suppose that you want to
  change the exchange rate in the                 business method of the
                                          n e Yo Tr al l od                              tr ev n oC
  na eB r eclass:
       1. Edit                       .
                 av aj . na eB re t re vn o C
       2. Recompile                        by typing
                          av aj . na eB re t re vn oC                  .
                                                                 r et re vn o c tn a
       3. In            , select Tools→Update Files.
               l o ot yo l pe d
       4. A dialog box appears reporting the changed file. Verify that                 re tr e vn oC
                      has been changed and then dismiss the dialog box.
            s sa lc . na eB
       5. Select Tools→Deploy. Make sure the checkbox labeled Save Object
          Before Deploying is checked.
40                                     GETTING STARTED



     You can also perform steps 4 and 5 by selecting Tools→Update And Redeploy.
     The              utility replaces the old JSP file in
         l oo ty o lp ed                                               with the
                                                                         ra e .p pA r et re vn o C
     new one and then redeploys the application.

     Adding a File
     To add a file to the EJB JAR or WAR of the application, perform these steps:
         1.   Select the JAR or WAR.
         2.   Select the General tab.
         3.   Click Edit.
         4.   In the tree of the Available Files field, locate the file and click Add.
         5.   Click OK.
         6.   From the main toolbar, select Tools→Update And Redeploy.

     Modifying the Web Client
     To modify the Web client, follow these steps:
         1. Edit           .
                   p s j. xe d ni
         2. Execute                  to copy the modified file to the build directory.
                       r et re v no c tn a
         3. In            , select Tools→Update Files.
                l oo ty o lp ed
         4. A dialog box appears reporting the changed file. Verify that                       ps j. x ed ni
            has been changed and then dismiss the dialog box.
         5. Select Tools→Deploy. Make sure the checkbox labeled Save Object
            Before Deploying is checked.
     You can also perform steps 4 and 5 by selecting Tools→Update And Redeploy.
     The              utility replaces the old JSP file in
         l oo ty o lp ed                                               with the
                                                                         ra e .p pA r et re vn o C
     new one and then redeploys the application.

     Modifying a Deployment Setting
     To modify a deployment setting of                 , you edit the appropriate field
                                                  p pA re t re vn o C
     in a tabbed pane and redeploy the application. For example, to change the JNDI
     name of the                   from
                     n ae Br et r ev no C       to  o py TA       , you would follow
                                                                  r et re v no Cy M
     these steps:
         1. In            , select
                l oo ty o lp ed             pp Ar et r ev no C   in the tree.
         2. Select the JNDI Names tab.
         3. In the JNDI Name field, enter            r et re vn o Cy M  .
                                              COMMON PROBLEMS AND THEIR SOLUTIONS                        41


       4. From the main toolbar, select File→Save.
       5. Select Tools→Update And Redeploy.


Common Problems and Their Solutions
  Cannot Start the J2EE Server

  Naming and Directory Service Port Conflict
  Symptom: When you start the J2EE server with the                   e so b re v   option, it displays
  these lines:
                                0 5 01 : tr o p ne ts i l re v re s EE 2 J
  . . . r ev re s e zi la i ti ni to n dl u oC : no i tp ec x Ee mi tn u R
  Solution: Another process is using port 1050. If the J2EE server is already run-
  ning, you can stop it by typing            . If some other program is using the
                                          e e2 j   po t s
  port, then you can change the default port number (1050) by editing the                       no c
                         file of your J2EE SDK installation.
  se it r ep or p .b ro /g i f
  For more information about default port numbers, see the Configuration Guide
  in the download bundle of the J2EE SDK.

  Web Service Port Conflict
  Symptom: When you start the J2EE server with the                   e so b re v   option, it displays
  these lines:

       : ne po . ]0 00 8[ r ot ce n no Cp tt H : no it p ec xE e lc yc ef i L
          . . .e su n i s se r dd A :n o it pe cx E dn iB . te n. av a j

  Solution: Another process is using port 8000. You can change the default port
  number (8000) by editing the                          file of your J2EE SDK
                                        se i tr ep or p .b ew / gi fn oc
  installation.

  Incorrect XML Parser
  Symptom: When you start the J2EE server with the                   e so b re v   option, it displays
  these lines:

                                            " ni am " d ae rh t n i n oi tp ec x E
                :r or r En oi ta r ug if n oC yr ot c aF .s re s ra p. l mx .x av a j
       . . . t a l pm I yr ot ca F re sr a PX AS .p x aj .s ec r ex .e h ca pa .g r o
42                                      GETTING STARTED



     :n oi tu l oS   Remove the    se i tr ep or p .p xa j/ b il /e r j   file from your J2SE instal-
     lation.

     Compilation Errors
     ant Cannot Locate the Build File
     Symptom: When you type          re tr ev n oc t n a  , these messages appear:

         !t s ix e t on s eo d l mx . dl iu b : el if dl i uB
                                          . de l ia f dl i uB

     Solution: Before running    , go to the
                                    t na                                 directory.
                                                      c rs /s e lp ma x e/ la ir o tu te e 2j
     If you want to run     from your current directory, you must specify the build
                            tn a
     file on the command line. For example, on Windows you would type this com-
     mand on a single line:

         l mx .d li u b\ cr s \s el pm a xe \l a ir ot ut e e2 j\ : C el if d li ub t na
                                                                              re tr ev n oc

     The Compiler Cannot Resolve Symbols
     Symptom: When you type            re tr ev n oc tn a  , the compiler reports many errors,
     including these:

                                                   lo bm y s ev lo s er t on n ac
                                                                          . . .
                                                                DE L IA F DL I UB
                                                                          . . .
         de di v or p n ee b ev a h dl u oh s se g as se m , de li a f el ip m oC

     Solution: Make sure that you’ve set the J2EE_HOME environment variable cor-
     rectly. See Checking the Environment Variables, page (23).

     ant 1.4 Will Not Compile the Example after You Run the Client
     Symptom: ant 1.4 displays this error:

         si xa tn ys le ba l e mu lo v r o , em an y r ot ce r id , em a ne li f e hT
                                                                       . tc er ro c ni

     Solution: Use version 1.3 of    . The 1.4 version of the
                                           tn a                      script and the
                                                                             ta b. t na
     scripts of the J2EE SDK all use the          environment variable. The SDK’s
                                                   DM CA V AJ
                                             COMMON PROBLEMS AND THEIR SOLUTIONS                     43


                     script, for example, sets
  ta b. t ne il cn u r                               D M CA VA J   to a value that causes prob-
lems for
t a b. tn a           .

Deployment Errors
The Incorrect XML Parser Is in Your Classpath
Symptom: The error displayed has the following text:

                                                                     . . .
     gn i ne po / gn iv as ro rr E :n oi tp e cx Ee to m eR .i m r. av aj ] [

                       ,} 1{ s sa lc } 0{ ye k f o g ni pp am da B: ro r rE t n em yo lp e D
     e do N no it a ci lp pA . lm x. t ne my ol p ed .e s ir pr et n e. mu s. m oc : d nu of t o n

Solution: Remove the              file from the
                             r aj .p xa j                     directory of your
                                                             tx e/ b il /e rj
J2SE installation. This JAR file contains XML parsing routines that are incom-
patible with the J2EE server. If you do not have a            file, then perhaps
                                                                   r aj .p x aj
your classpath refers to the XML routines of a Tomcat installation. In this case,
you should remove that reference from your classpath.

The Remote Home Interface Was Specified as a Local Home
Interface
Symptom: An error such as the following is displayed:

                            . tc ar ts b a de r al ce d e b ts um lp mI e mo Hl ac o L
     ) (e l dn aH em o Ht eg el dn aH e mo H. b je .x av a j en if e d to n s eo d t I
                                       . em oH B JE .b je . xa va j e ca fr e tn i mo r f

Solution: Remove the enterprise bean from the EAR file (Edit→Delete) and cre-
ate a new bean with the New Enterprise Bean wizard. In the General dialog box
of the wizard, select values from the Remote Home Interface and Remote Inter-
face combo boxes.

J2EE Application Client Runtime Errors
The Client Throws a NoClassDefFoundError
Symptom: The client reports this exception:

     em o Hr et re v no C. r et re vn o c: ro r rE dn uo F fe Ds sa l Co N. g na l. av a j
44                                         GETTING STARTED



     Solution: This error occurs if the client cannot find the classes in the               r et r ev no C
                      file. Make sure that you’ve correctly followed the steps outlined
     r aj . tn ei lC p pA
     in Running the J2EE™ Application Client, page (37).

     The Client Cannot Find ConverterApp.ear
     Symptom: The client reports this exception:

          t si x e to n s eo d r ae .p pA r et re v no C :n o it pe cx E OI

     Solution: Ensure that the          ra e .p pA r et re vn o C   file exists and that you’ve speci-
     fied it with the        option:
                            t ne il c

          tn ei lc n ur      r ae .p p Ar et re v no C t ne il c     t ne i lC re tr e vn oC em an

     You created the                      file in the section, Creating the J2EE™
                             r a e. pp Ar e tr ev n oC
     Application, page (24). See also the section Running the J2EE™ Application
     Client, page (37).

     The Client Cannot Find the ConverterClient Component
     Symptom: The client displays this line:

          . . . : ro f d en if ed sr ot p ir cs ed tn ei l c no it a ci lp pa oN

     Solution: Verify that you’ve created the                    component and that
                                                            t ne il Cr e tr ev n oC
     you’ve specified it for the       option of the
                                           e m an                command. You cre-
                                                            t ne il cn u r
     ated the                    component in the section, Packaging the J2EE Appli-
               tn e il Cr et r ev no C
     cation Client, page (31).

     The Login Failed
     Symptom: After you log in, the client displays this line:

          dr o ws sa p r o/ dn a n ig ol tc er ro c nI

     Solution: At the login prompts, enter               t se ug   as the user name and    32 1t se u g   as
     the password.

     The J2EE Application Has Not Been Deployed
     Symptom: The client reports the following exception:

          . . .g ni ma N so C. g mo .g ro si no i tp ec xe to o R . no it p ec xE dn u oF to Ne m aN
                                           COMMON PROBLEMS AND THEIR SOLUTIONS                       45


Solution: Deploy the application. For instructions, see Deploying the J2EE™
Application, page (37).

The JNDI Name Is Incorrect
Symptom: The client reports the following exception:

    . . . gn im aN s oC .g m o. gr o s i n oi t pe cx e t oo R . n oi tp ec x Ed nu o Ft oN em a N

Solution: In the JNDI Names tabbed pane of the                , make sure that
                                                                       p pA re t re vn o C
the JNDI names for the                  and the
                             n a eB re t re vn oC                       match.
                                                            r e tr ev n oC el pm i S/ bj e
Edit the appropriate JNDI Name field and then redeploy the application.

Web Client Runtime Errors
The Web Context in the URL Is Incorrect
Symptom: The browser reports that the page cannot be found (HTTP 404).
Solution: Verify that the Web context (          ) in the URL matches the one
                                               r e tr ev n oc
you specified in the Component General Properties dialog box (See the section
Packaging the Web Client, page (34)). The case (upper or lower) of the Web con-
text is significant.

The J2EE Application Has Not Been Deployed
Symptom: The browser reports that the page cannot be found (HTTP 404).
Solution: Deploy the application.

The JNDI Name Is Incorrect
Symptom: When you click Submit on the Web page, the browser reports

    . de rr u cc O sa H n oi tp e cx E t el vr eS A

Solution: In the JNDI Names tabbed pane of the                 , make sure that
                                                           p pA re t re vn o C
the JNDI names for the                 and the
                             n a eB re tr e vn oC               match. Edit the
                                                           R AW re t re vn oC
appropriate JNDI Name field and then redeploy the application.

Detecting Problems With the Verifier Tool
The verifier tool (       ) can detect inconsistencies in deployment descrip-
                     r e if ir ev
tors and method signatures. These inconsistencies often cause deployment or
runtime errors. From            , you can run the GUI version of
                         lo ot yo l pe d                                  by      r ei f ir ev
46                               GETTING STARTED



     selecting Tools→Verifier. You can also run a stand-alone GUI or command-line
     version of        . For more information, see Appendix B.
                 r e if ir ev


     Comparing Your EAR Files with Ours
     For most of the examples, the download bundle of the tutorial includes J2EE
     application EAR files, which are located in the sr ae / se lp m ax e/ la i ro tu t ee 2j
     directory.

     When All Else Fails
     If none of these suggestions fixes the problem, you can uninstall the application
     and clean out the server’s repository by running the          script. You’ll also
                                                          pu na e lc
     need to shut down and restart the server:

              p ot s e e 2j
                   pu na e lc
         e so b re v e e 2j
                               3
                Enterprise Beans
                                                                 Dale Green



E   NTERPRISE beans are the J2EE™ components that implement Enterprise
JavaBeans™ (EJB™) technology. Enterprise beans run in the EJB container, a
runtime environment within the J2EE server (see Figure 1–5). Although trans-
parent to the application developer, the EJB container provides system-level ser-
vices such as transactions to its enterprise beans. These services enable you to
quickly build and deploy enterprise beans, which form the core of transactional
J2EE applications.

In This Chapter
          What Is an Enterprise Bean? 48
             Benefits of Enterprise Beans 48
             When to Use Enterprise Beans 49
             Types of Enterprise Beans 49
          What Is a Session Bean? 49
             State Management Modes 50
             When to Use Session Beans 51
          What Is an Entity Bean? 51
             What Makes Entity Beans Different from Session Beans? 52
             Container-Managed Persistence 53
             When to Use Entity Beans 56
          What Is a Message-Driven Bean? 56
             What Makes Message-Driven Beans Different from Session and Entity
             Beans? 57
             When to Use Message-Driven Beans 57


                                                                                    47
48                                    ENTERPRISE BEANS


                 Defining Client Access with Interfaces 58
                     Remote Access 58
                     Local Access 59
                     Local Interfaces and Container-Managed Relationships 59
                     Deciding on Remote or Local Access 60
                     Performance and Access 61
                     Method Parameters and Access 61
                 The Contents of an Enterprise Bean 62
                 Naming Conventions for Enterprise Beans 63
                 The Life Cycles of Enterprise Beans 63
                     The Life Cycle of a Stateful Session Bean 64
                     The Life Cycle of a Stateless Session Bean 65
                     The Life Cycle of an Entity Bean 65
                     The Life Cycle of a Message-Driven Bean 67


     What Is an Enterprise Bean?
       Written in the Java™ programming language, an enterprise bean is a server-side
       component that encapsulates the business logic of an application. The business
       logic is the code that fulfills the purpose of the application. In an inventory con-
       trol application, for example, the enterprise beans might implement the business
       logic in methods called                            and
                                l ev e Ly ro t ne vn Ik c eh c                . By invoking
                                                                 tc u do rP re d ro
       these methods, remote clients can access the inventory services provided by the
       application.

       Benefits of Enterprise Beans
       For several reasons, enterprise beans simplify the development of large, distrib-
       uted applications. First, because the EJB container provides system-level ser-
       vices to enterprise beans, the bean developer can concentrate on solving business
       problems. The EJB container—not the bean developer—is responsible for sys-
       tem-level services such as transaction management and security authorization.
       Second, because the beans—and not the clients—contain the application’s busi-
       ness logic, the client developer can focus on the presentation of the client. The
       client developer does not have to code the routines that implement business rules
       or access databases. As a result, the clients are thinner, a benefit that is particu-
       larly important for clients that run on small devices.
       Third, because enterprise beans are portable components, the application assem-
       bler can build new applications from existing beans. These applications can run
       on any compliant J2EE server.
                                        WHAT IS A SESSION BEAN?                                     49


  When to Use Enterprise Beans
  You should consider using enterprise beans if your application has any of the fol-
  lowing requirements:
      • The application must be scalable. To accommodate a growing number of
        users, you may need to distribute an application’s components across mul-
        tiple machines. Not only can the enterprise beans of an application run on
        different machines, but their location will remain transparent to the clients.
      • Transactions are required to ensure data integrity. Enterprise beans sup-
        port transactions, the mechanisms that manage the concurrent access of
        shared objects.
      • The application will have a variety of clients. With just a few lines of code,
        remote clients can easily locate enterprise beans. These clients can be thin,
        various, and numerous.

  Types of Enterprise Beans
  Table 3–1 summarizes the three different types of enterprise beans. The follow-
  ing sections discuss each type in more detail.


  Table 3–1 Summary of Enterprise Bean Types

   Enterprise Bean Type     Purpose

   Session                  Performs a task for a client

   Entity                   Represents a business entity object that exists in persistent storage

                            Acts as a listener for the Java™ Message Service API, processing
   Message-Driven
                            messages asynchronously




What Is a Session Bean?
  A session bean represents a single client inside the J2EE server. To access an
  application that is deployed on the server, the client invokes the session bean’s
  methods. The session bean performs work for its client, shielding the client from
  complexity by executing business tasks inside the server.
  As its name suggests, a session bean is similar to an interactive session. A ses-
  sion bean is not shared—it may have just one client, in the same way that an
50                                 ENTERPRISE BEANS



     interactive session may have just one user. Like an interactive session, a session
     bean is not persistent. (That is, its data is not saved to a database.) When the cli-
     ent terminates, its session bean appears to terminate and is no longer associated
     with the client.
     For code samples, see Chapter 4.

     State Management Modes
     There are two types of session beans: stateful and stateless.

     Stateful Session Beans
     The state of an object consists of the values of its instance variables. In a stateful
     session bean, the instance variables represent the state of a unique client-bean
     session. Because the client interacts (“talks”) with its bean, this state is often
     called the conversational state.
     The state is retained for the duration of the client-bean session. If the client
     removes the bean or terminates, the session ends and the state disappears. This
     transient nature of the state is not a problem, however, because when the conver-
     sation between the client and the bean ends there is no need to retain the state.

     Stateless Session Beans
     A stateless session bean does not maintain a conversational state for a particular
     client. When a client invokes the method of a stateless bean, the bean’s instance
     variables may contain a state, but only for the duration of the invocation. When
     the method is finished, the state is no longer retained. Except during method
     invocation, all instances of a stateless bean are equivalent, allowing the EJB con-
     tainer to assign an instance to any client.
     Because stateless session beans can support multiple clients, they can offer better
     scalability for applications that require large numbers of clients. Typically, an
     application requires fewer stateless session beans than stateful session beans to
     support the same number of clients.
     At times, the EJB container may write a stateful session bean to secondary stor-
     age. However, stateless session beans are never written to secondary storage.
     Therefore, stateless beans may offer better performance than stateful beans.
                                      WHAT IS AN ENTITY BEAN?                           51


  When to Use Session Beans
  In general, you should use a session bean if the following circumstances hold:
      • At any given time, only one client has access to the bean instance.
      • The state of the bean is not persistent, existing only for a short period of
        time (perhaps a few hours).
  Stateful session beans are appropriate if any of the following conditions are true:
      • The bean’s state represents the interaction between the bean and a specific
        client.
      • The bean needs to hold information about the client across method invo-
        cations.
      • The bean mediates between the client and the other components of the
        application, presenting a simplified view to the client.
      • Behind the scenes, the bean manages the work flow of several enterprise
        beans. For an example, see the                             session bean in
                                          BJ Er el l or tn o Ct nu oc c A
        Chapter 18.
  To improve performance, you might choose a stateless session bean if it has any
  of these traits:
      • The bean’s state has no data for a specific client.
      • In a single method invocation, the bean performs a generic task for all cli-
        ents. For example, you might use a stateless session bean to send an e-mail
        that confirms an online order.
      • The bean fetches from a database a set of read-only data that is often used
        by clients. Such a bean, for example, could retrieve the table rows that rep-
        resent the products that are on sale this month.


What Is an Entity Bean?
  An entity bean represents a business object in a persistent storage mechanism.
  Some examples of business objects are customers, orders, and products. In the
  J2EE SDK, the persistent storage mechanism is a relational database. Typically,
  each entity bean has an underlying table in a relational database, and each
  instance of the bean corresponds to a row in that table. For code examples of
  entity beans, please refer to chapters 5 and 6.
52                                ENTERPRISE BEANS



     What Makes Entity Beans Different from Session
     Beans?
     Entity beans differ from session beans in several ways. Entity beans are persis-
     tent, allow shared access, have primary keys, and may participate in relation-
     ships with other entity beans.

     Persistence
     Because the state of an entity bean is saved in a storage mechanism, it is persis-
     tent. Persistence means that the entity bean’s state exists beyond the lifetime of
     the application or the J2EE server process. If you’ve worked with databases,
     you’re familiar with persistent data. The data in a database is persistent because
     it still exists even after you shut down the database server or the applications it
     services.
     There are two types of persistence for entity beans: bean-managed and con-
     tainer-managed. With bean-managed persistence, the entity bean code that you
     write contains the calls that access the database. If your bean has container-man-
     aged persistence, the EJB container automatically generates the necessary data-
     base access calls. The code that you write for the entity bean does not include
     these calls. For additional information, see the section Container-Managed
     Persistence, page (53).

     Shared Access
     Entity beans may be shared by multiple clients. Because the clients might want
     to change the same data, it’s important that entity beans work within transac-
     tions. Typically, the EJB container provides transaction management. In this
     case, you specify the transaction attributes in the bean’s deployment descriptor.
     You do not have to code the transaction boundaries in the bean—the container
     marks the boundaries for you. See Chapter 14 for more information.

     Primary Key
     Each entity bean has a unique object identifier. A customer entity bean, for
     example, might be identified by a customer number. The unique identifier, or
     primary key, enables the client to locate a particular entity bean. For more infor-
     mation see the section Primary Keys for Bean-Managed Persistence, page (113).
                                     WHAT IS AN ENTITY BEAN?                                 53


Relationships
Like a table in a relational database, an entity bean may be related to other entity
beans. For example, in a college enrollment application,                 and
                                                               BJ E tn ed ut S     ru oC
       would be related because students enroll in classes.
B JE e s
You implement relationships differently for entity beans with bean-managed per-
sistence and those with container-managed persistence. With bean-managed per-
sistence, the code that you write implements the relationships. But with
container-managed persistence, the EJB container takes care of the relationships
for you. For this reason, relationships in entity beans with container-managed
persistence are often referred to as container-managed relationships.

Container-Managed Persistence
The term container-managed persistence means that the EJB container handles
all database access required by the entity bean. The bean’s code contains no
database access (SQL) calls. As a result, the bean’s code is not tied to a specific
persistent storage mechanism (database). Because of this flexibility, even if you
redeploy the same entity bean on different J2EE servers that use different data-
bases, you won’t need to modify or recompile the bean’s code. In short, your
entity beans are more portable.
In order to generate the data access calls, the container needs information that
you provide in the entity bean’s abstract schema.

Abstract Schema
Part of an entity bean’s deployment descriptor, the abstract schema defines the
bean’s persistent fields and relationships. The term abstract distinguishes this
schema from the physical schema of the underlying data store. In a relational
database, for example, the physical schema is made up of structures such as
tables and columns.
You specify the name of an abstract schema in the deployment descriptor. This
name is referenced by queries written in the Enterprise JavaBeans™ Query Lan-
guage (EJB™ QL). For an entity bean with container-managed persistence, you
must define an EJB QL query for every finder method (except              am ir P yB dn i f
      ). The EJB QL query determines the query that is executed by the EJB
y eK y r
container when the finder method is invoked. To learn more about EJB QL, see
Chapter 8.
You’ll probably find it helpful to sketch the abstract schema before writing any
code. Figure 3–1 represents a simple abstract schema that describes the relation-
54                                   ENTERPRISE BEANS



     ships between three entity beans. These relationships are discussed further in the
     sections that follow.




     Figure 3–1 A High-Level View of an Abstract Schema

     Persistent Fields
     The persistent fields of an entity bean are stored in the underlying data store.
     Collectively, these fields constitute the state of the bean. At runtime, the EJB
     container automatically synchronizes this state with the database. During
     deployment, the container typically maps the entity bean to a database table and
     maps the persistent fields to the table’s columns.
     A                  entity bean, for example, might have persistent fields such as
                     B JE re m ot su C
                  ,           ,       , and
     en o hp e ma N ts al em aN ts r if                   . In container-managed persis-
                                            ss e rd dA l ia me
     tence, these fields are virtual. You declare them in the abstract schema, but you
     do not code them as instance variables in the entity bean class. Instead, the per-
     sistent fields are identified in the code by access methods (getters and setters).

     Relationship Fields
     A relationship field is like a foreign key in a database table—it identifies a
     related bean. Like a persistent field, a relationship field is virtual and is defined
                                            WHAT IS AN ENTITY BEAN?                                   55


in the enterprise bean class with access methods. But unlike a persistent field, a
relationship field does not represent the bean’s state. Relationship fields are dis-
cussed further in Direction in Container-Managed Relationships, page (55).

Multiplicity in Container-Managed Relationships
There are four types of multiplicities:
One-to-one: Each entity bean instance is related to a single instance of another
entity bean. For example, to model a physical warehouse in which each storage
bin contains a single widget,                and
                                     B J En iB e ga ro tS     would have a one-
                                                                B JE te gd i W
to-one relationship.
One-to-many: An entity bean instance may be related to multiple instances of the
other entity bean. A sales order, for example, can have multiple line items. In the
order application,               would have a one-to-many relationship with
                         BJ Er ed r O
              .
BJ E me tI en i L
Many-to-one: Multiple instances of an entity bean may be related to a single
instance of the other entity bean. This multiplicity is the opposite of a one-to-
many relationship. In the example mentioned in the previous item, from the per-
spective of               the relationship to
              BJ E me tI en i L                         is many-to-one.
                                                       BJ Er e dr O
Many-to-many: The entity bean instances may be related to multiple instances of
each other. For example, in college each course has many students, and every
student may take several courses. Therefore, in an enrollment application,                    ru oC
      and
B JE e s               would have a many-to-many relationship.
             BJ Et ne d ut S

Direction in Container-Managed Relationships
The direction of a relationship may be either bidirectional or unidirectional. In a
bidirectional relationship, each entity bean has a relationship field that refers to
the other bean. Through the relationship field, an entity bean’s code can access
its related object. If an entity bean has a relative field, then we often say that it
“knows” about its related object. For example, if                      knows what
                                                                       BJ Er e dr O
                instances it has and if
BJ E me tI en i L                                         knows what
                                                 BJ E me tI e ni L                 it B JE re d rO
belongs to, then they have a bidirectional relationship.
In a unidirectional relationship, only one entity bean has a relationship field that
refers to the other. For example,                  would have a relationship field
                                         BJ Em e tI en iL
that identifies
B J Et cu do r P            , but              would not have a relationship field
                                              BJ Et c ud or P
for               . In other words,
            BJ E me tI en i L                       knows about
                                        BJ E me tI en i L                      , but
                                                                                 BJ E tc ud or P
              doesn’t know which
                  B J Et cu do r P                instances refer to it.
                                         BJ Em e tI en iL
56                                   ENTERPRISE BEANS



       EJB QL queries often navigate across relationships. The direction of a relation-
       ship determines whether a query can navigate from one bean to another. For
       example, a query can navigate from                    to
                                               B JE me tI e ni L             , but cannot
                                                                       BJ Et c ud or P
       navigate in the opposite direction. For B JE re dr O  and                , a query
                                                                    BJ Em e tI en iL
       could navigate in both directions, since these two beans have a bidirectional rela-
       tionship.

       When to Use Entity Beans
       You should probably use an entity bean under the following conditions:
           • The bean represents a business entity, not a procedure. For example,
                               would be an entity bean, but
              BJ E dr aC t id er C                                 BJ Er e if ir e Vd ra Ct i de rC
             would probably be a session bean.
           • The bean’s state must be persistent. If the bean instance terminates or if
             the J2EE server is shut down, the bean’s state still exists in persistent stor-
             age (a database).


     What Is a Message-Driven Bean?
         Note: This section contains text from the Java™ Message Service Tutorial.
         Because message-driven beans rely on Java Message Service (JMS) technology, to
         fully understand how these beans work you should consult the tutorial at this URL:

         lmth.xedni/lairotut/smj/stcudorp/moc.nus.avaj//:ptth


       A message-driven bean is an enterprise bean that allows J2EE applications to
       process messages asynchronously. It acts as a JMS message listener, which is
       similar to an event listener except that it receives messages instead of events.
       The messages may be sent by any J2EE component—an application client,
       another enterprise bean, or a Web component—or by a JMS application or sys-
       tem that does not use J2EE technology.
       Message-driven beans currently process only JMS messages, but in the future
       they may be used to process other kinds of messages.
       For a code sample, see Chapter 7.
                                    WHAT IS A MESSAGE-DRIVEN BEAN?                  57


What Makes Message-Driven Beans Different from
Session and Entity Beans?
The most visible difference between message-driven beans and session and
entity beans is that clients do not access message-driven beans through inter-
faces. Interfaces are described in the section Defining Client Access with
Interfaces, page (58). Unlike a session or entity bean, a message-driven bean has
only a bean class.
In several respects, a message-driven bean resembles a stateless session bean:
     • A message-driven bean’s instances retain no data or conversational state
       for a specific client.
     • All instances of a message-driven bean are equivalent, allowing the EJB
       container to assign a message to any message-driven bean instance. The
       container can pool these instances to allow streams of messages to be pro-
       cessed concurrently.
     • A single message-driven bean can process messages from multiple clients.
The instance variables of the message-driven bean instance can contain some
state across the handling of client messages—for example, a JMS API connec-
tion, an open database connection, or an object reference to an enterprise bean
object.
When a message arrives, the container calls the message-driven bean’s    se Mn o
eg a smethod to process the message. The              method normally casts the
                                           e ga ss e Mn o
message to one of the five JMS message types and handles it in accordance with
the application’s business logic. The             method may call helper meth-
                                      e ga s se Mn o
ods, or it may invoke a session or entity bean to process the information in the
message or to store it in a database.
A message may be delivered to a message-driven bean within a transaction con-
text, so that all operations within the             method are part of a single
                                        e g as se M no
transaction. If message processing is rolled back, the message will be redeliv-
ered. For more information, see Chapter 7.

When to Use Message-Driven Beans
Session beans and entity beans allow you to send JMS messages and to receive
them synchronously, but not asynchronously. To avoid tying up server resources,
you may prefer not to use blocking synchronous receives in a server-side compo-
nent. To receive messages asynchronously, use a message-driven bean.
58                                    ENTERPRISE BEANS



     Defining Client Access with Interfaces
          Note: The material in this section applies only to session and entity beans, not to
          message-driven beans. Because they have a different programming model, mes-
          sage-driven beans do not have interfaces that define client access.


       A client may access a session or an entity bean only through the methods defined
       in the bean’s interfaces. These interfaces define the client’s view of a bean. All
       other aspects of the bean—method implementations, deployment descriptor set-
       tings, abstract schemas, and database access calls—are hidden from the client.
       Well-designed interfaces simplify the development and maintenance of J2EE
       applications. Not only do clean interfaces shield the clients from any complexi-
       ties in the EJB tier, but they also allow the beans to change internally without
       affecting the clients. For example, even if you change your entity beans from
       bean-managed to container-managed persistence, you won’t have to alter the cli-
       ent code. But if you were to change the method definitions in the interfaces, then
       you might have to modify the client code as well. Therefore, to isolate your cli-
       ents from possible changes in the beans, it is important that you design the inter-
       faces carefully.
       When you design a J2EE application, one of the first decisions you make is the
       type of client access allowed by the enterprise beans: remote or local.

       Remote Access
       A remote client of an enterprise bean has the following traits:
            • It may run on a different machine and a different Java™ 2 virtual machine
              (JVM) than the enterprise bean it accesses. (It is not required to run on a
              different JVM.)
            • It can be a Web component, a J2EE application client, or another enter-
              prise bean.
            • To a remote client, the location of the enterprise bean is transparent.
       To create an enterprise bean with remote access, you must code a remote inter-
       face and a home interface. The remote interface defines the business methods
       that are specific to the bean. For example, the remote interface of a bean named
                           might have business methods named
       BJ Et n uo cc Ak n aB                                             and credit. The
                                                                    ti be d
       home interface defines the bean’s life cycle methods—            and
                                                                    et ae r c       . For
                                                                                  ev om er
       entity beans, the home interface also defines finder methods and home methods.
                                     DEFINING CLIENT ACCESS WITH INTERFACES          59


Finder methods are used to locate entity beans. Home methods are business
methods that are invoked on all instances of an entity bean class. Figure 3–2
shows how the interfaces control the client’s view of an enterprise bean.




Figure 3–2 Interfaces for an Enterprise Bean With Remote Access


Local Access
A local client has these characteristics:
    • It must run in the same JVM as the enterprise bean it accesses.
    • It may be a Web component or another enterprise bean.
    • To the local client, the location of the enterprise bean it accesses is not
      transparent.
    • It is often an entity bean that has a container-managed relationship with
      another entity bean.
To build an enterprise bean that allows local access, you must code the local
interface and the local home interface. The local interface defines the bean’s
business methods, and the local home interface defines its life cycle and finder
methods.

Local Interfaces and Container-Managed
Relationships
If an entity bean is the target of a container-managed relationship, then it must
have local interfaces. The direction of the relationship determines whether or not
60                                    ENTERPRISE BEANS



     a bean is the target. In Figure 3–1, for example,
                                               B J Et cu d or P            is the target of a
     unidirectional relationship withBJ Em e tI en i L . Because   BJ E me tI e ni Laccesses
                   locally,
     B JE tc ud o rP     BJ Em e tI en i L must have the local interfaces.         B JE tc u do rP
     also needs local interfaces—not because of its relationship with
                            BJ Et cu d or P                                               —
     but because it is the target of a relationship with
                                                      B JE re d rO  . And because the rela-
     tionship between                    and             is bidirectional, both beans must
                                                                   B JE re d rO       B JE me t Ie ni L
     have local interfaces.
     Because they require local access, entity beans that participate in a container-
     managed relationship must reside in the same EJB JAR file. The primary benefit
     of this locality is increased performance—local calls are usually faster than
     remote calls.

     Deciding on Remote or Local Access
     The decision regarding whether to allow local or remote access depends on the
     following factors.
     Container-managed relationships: If an entity bean is the target of a container-
     managed relationship, it must use local access.
     Tight or loose coupling of related beans: Tightly coupled beans depend on one
     another. For example, a completed sales order must have one or more line items,
     which cannot exist without the order to which they belong. The               andB JE re d rO
                     entity beans that model this relationship are tightly coupled.
     B J Em et Ie n iL
     Tightly coupled beans are good candidates for local access. Since they fit
     together as a logical unit, they probably call each other often and would benefit
     from the increased performance that is possible with local access.
     Type of client: If an enterprise bean is accessed by J2EE application clients, then
     it should allow remote access. In a production environment, these clients almost
     always run on different machines than the J2EE server. If an enterprise bean’s
     clients are Web components or other enterprise beans, then the type of access
     depends on how you want to distribute your components.
     Component distribution: J2EE applications are scalable because their server-side
     components can be distributed across multiple machines. In a distributed appli-
     cation, for example, the Web components may run on a different server than the
     enterprise beans they access. In this distributed scenario, the enterprise beans
     should allow remote access.
     If you aren’t sure which type of access an enterprise bean should have, then
     choose remote access. This decision gives you more flexibility—in the future
                                    DEFINING CLIENT ACCESS WITH INTERFACES            61


you can distribute your components to accommodate growing demands on your
application.
Although uncommon, it is possible for an enterprise bean to allow both remote
and local access. Such a bean would require both remote and local interfaces.

Performance and Access
Because of factors such as network latency, remote calls may be slower than
local calls. On the other hand, if you distribute components among different
servers, you might improve the application’s overall performance. Both of these
statements are generalizations; actual performance can vary in different opera-
tional environments. Nevertheless, you should keep in mind how your applica-
tion design might affect performance.

Method Parameters and Access
The type of access affects the parameters of the bean methods that are called by
clients. The following topics apply not only to method parameters, but also to
method return values.

Isolation
An argument in a remote call is passed by value; it is a copy of an object. But an
argument in a local call is passed by reference, just like a normal method call in
the Java programming language.
The parameters of remote calls are more isolated than those of local calls. With
remote calls, the client and bean operate on different copies of a parameter
object. If the client changes the value of the object, the value of the copy in the
bean does not change. This layer of isolation can help protect the bean if the cli-
ent accidentally modifies the data.
In a local call, both the client and the bean may modify the same object. In gen-
eral, you should not rely on this side effect of local calls. Perhaps some day you
will want to distribute your components, replacing the local calls with remote
ones.

Granularity of Accessed Data
Because remote calls are likely to be slower than local calls, the parameters in
remote methods should be relatively coarse-grained. Since a coarse-grained
object contains more data than a fine-grained one, fewer access calls are
required.
62                                       ENTERPRISE BEANS



       For example, suppose that a                   entity bean is accessed remotely. This
                                         B J Er em o ts uC
       bean would have a single getter method that returns a                        object,
                                                                        sl ia t eD re mo t su C
       which encapsulates all of the customer’s information. But if  B JE r em ot su C is to
       be accessed locally, it could have a getter method for each instance variable:
                        ,              ,                    , and so forth. Because local
       r eb m uN en oh P te g e m aN ts aL t eg em a Nt sr iF t eg
       calls are fast, the multiple calls to these finer-grained getter methods would not
       significantly degrade performance.


     The Contents of an Enterprise Bean
       To develop an enterprise bean, you must provide the following files:
           • Deployment descriptor: An XML file that specifies information about the
             bean such as its persistence type and transaction attributes. The            y ol p ed
                   utility creates the deployment descriptor when you step through the
               l oo t
             New Enterprise Bean wizard.
           • Enterprise bean class: Implements the methods defined in the following
             interfaces.
           • Interfaces: The remote and home interfaces are required for remote access.
             For local access, the local and local home interfaces are required. See the
             section Defining Client Access with Interfaces, page (58). (Please note
             that these interfaces are not used by message-driven beans.)
           • Helper classes: Other classes needed by the enterprise bean class, such as
             exception and utility classes.
       You package the files in the preceding list into an EJB JAR file, the module that
       stores the enterprise bean. An EJB JAR file is portable and may be used for dif-
       ferent applications. To assemble a J2EE application, you package one or more
       modules—such as EJB JAR files—into an EAR file, the archive file that holds
       the application. When you deploy the EAR file that contains the bean’s EJB JAR
       file, you also deploy the enterprise bean onto the J2EE server.
                                       NAMING CONVENTIONS FOR ENTERPRISE BEANS         63


Naming Conventions for Enterprise Beans
  Because enterprise beans are composed of multiple parts, it’s useful to follow a
  naming convention for your applications. Table 3–2 summarizes the conventions
  for the example beans of this tutorial.


  Table 3–2 Naming Conventions for Enterprise Beans

   Item                          Syntax                     Example

   Enterprise bean name (DD)     BJE>eman<                  BJEtnuoccA

   EJB JAR display name (DD)     RAJ>eman<                  RAJtnuoccA

   Enterprise bean class         naeB>eman<                 naeBtnuoccA

   Home interface                emoH>eman<                 emoHtnuoccA

   Remote interface              >eman<                     tnuoccA

   Local home interface          emoH>eman<lacoL            emoHtnuoccAlacoL

   Local interface                      <
                                 eman lacoL   >             tnuoccAlacoL

   Abstract schema (DD)          <      >
                                     eman                   tnuoccA



  DD means that the item is an element in the bean’s deployment descriptor.


The Life Cycles of Enterprise Beans
  An enterprise bean goes through various stages during its lifetime, or life cycle.
  Each type of enterprise bean—session, entity, or message-driven—has a differ-
  ent life cycle.
  The descriptions that follow refer to methods that are explained along with the
  code examples in the next two chapters. If you are new to enterprise beans, you
  should skip this section and try out the code examples first.
64                                 ENTERPRISE BEANS



     The Life Cycle of a Stateful Session Bean
     Figure 3–3 illustrates the stages that a session bean passes through during its life-
     time. The client initiates the life cycle by invoking the         method. The EJB et ae r c
     container instantiates the bean and then invokes the                             and
                                                                      t xe tn oC n oi ss e St es
                 methods in the session bean. The bean is now ready to have its busi-
     et ae rC b je
     ness methods invoked.
     While in the ready stage, the EJB container may decide to deactivate, or passi-
     vate, the bean by moving it from memory to secondary storage. (Typically, the
     EJB container uses a least-recently-used algorithm to select a bean for passiva-
     tion.) The EJB container invokes the bean’s                   method immediately
                                                      et av i ss aP b je
     before passivating it. If a client invokes a business method on the bean while it is
     in the passive stage, the EJB container activates the bean, moving it back to the
     ready stage, and then calls the bean’s                 method.
                                              e t av it cA b je




     Figure 3–3 Life Cycle of a Stateful Session Bean

     At the end of the life cycle, the client invokes the       method and the EJB
                                                                  e vo m er
     container calls the bean’s              method. The bean’s instance is ready for
                                 ev o me Rb je
     garbage collection.
     Your code controls the invocation of only two life-cycle methods—the                   et ae r c
     and          methods in the client. All other methods in Figure 3–3 are invoked
          e v om er
     by the EJB container. The                method, for example, is inside the bean
                                  e ta er Cb j e
     class, allowing you to perform certain operations right after the bean is instanti-
                                     THE LIFE CYCLES OF ENTERPRISE BEANS                       65


ated. For instance, you may wish to connect to a database in the              e ta er C bj e
method. See Chapter 16 for more information.

The Life Cycle of a Stateless Session Bean
Because a stateless session bean is never passivated, its life cycle has just two
stages: nonexistent and ready for the invocation of business methods. Figure 3–4
illustrates the stages of a stateless session bean.




Figure 3–4 Life Cycle of a Stateless Session Bean


The Life Cycle of an Entity Bean
Figure 3–5 shows the stages that an entity bean passes through during its life-
time. After the EJB container creates the instance, it calls the        no Cy t it nE t es
tx e tmethod of the entity bean class. The                     method passes the
                                            t xe tn oC y ti tn E te s
entity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. While
in the pooled stage, the instance is not associated with any particular EJB object
identity. All instances in the pool are identical. The EJB container assigns an
identity to an instance when moving it to the ready stage.
There are two paths from the pooled stage to the ready stage. On the first path,
the client invokes the      method, causing the EJB container to call the
                       e ta e rc                                                     bj e
66                                       ENTERPRISE BEANS



             and
     e ta e rC                   methods. On the second path, the EJB container
                     e t ae rC ts o Pb je
     invokes the               method. While in the ready stage, an entity bean’s
                         et a vi tc A bj e
     business methods may be invoked.
     There are also two paths from the ready stage to the pooled stage. First, a client
     may invoke the            method, which causes the EJB container to call the
                          e vo me r
                 method. Second, the EJB container may invoke the
     ev om eR b je                                                     et av i ss aP b je
     method.
     At the end of the life cycle, the EJB container removes the instance from the
     pool and invokes the                       method.
                                tx et n oC yt i tn Et es n u




     Figure 3–5 Life Cycle of an Entity Bean
                                             THE LIFE CYCLES OF ENTERPRISE BEANS           67


In the pooled state, an instance is not associated with any particular EJB object
identity. With bean-managed persistence, when the EJB container moves an
instance from the pooled state to the ready state, it does not automatically set the
primary key. Therefore, the               and
                                     e ta er C bj e           methods must set the
                                                       et av i tc Ab j e
primary key. If the primary key is incorrect, the           and
                                                        d a oL bj e        methods
                                                                            er o tS bj e
cannot synchronize the instance variables with the database. In the The Sav-
ingsAccountEJB Example, page (84), the                     method assigns the pri-
                                                                  et a er Cb je
mary key from one of the input parameters. The                     method sets the
                                                      et av it c Ab je
primary key ( ) as follows:
                di

     ;) (y e Ky ra m ir Pt eg . tx et no c )g ni r tS ( = d i

In the pooled state, the values of the instance variables are not needed. You can
make these instance variables eligible for garbage collection by setting them to
ll u nin the                 method.
              e t av is s sa Pb je


The Life Cycle of a Message-Driven Bean
Figure 3–6 illustrates the stages in the life cycle of a message-driven bean.




Figure 3–6 Life Cycle of a Message-Driven Bean
68                                    ENTERPRISE BEANS



     The EJB container usually creates a pool of message-driven bean instances. For
     each instance, the EJB container instantiates the bean and performs these tasks:
         1. It calls thetx e tn oC n ev ir De g as se M te s   method to pass the context object
            to the instance.
         2. It calls the instance’s   e ta er C bj e   method.
     Like a stateless session bean, a message-driven bean is never passivated, and it
     has only two states: nonexistent and ready to receive messages.
     At the end of the life cycle, the container calls the            ev o me Rb j e   method. The
     bean’s instance is then ready for garbage collection.
                                  4
                     A Session Bean
                           Example
                                                                  Dale Green



SESSION beans are powerful because they extend the reach of your clients into
remote servers—yet they’re easy to build. In Chapter 2, you built a stateless ses-
sion bean named                . This chapter examines the source code of a
                      B JE r et re v no C
stateful session bean called
                  BJ Et r aC       .

In This Chapter
          The CartEJB Example 70
              Session Bean Class 70
              Home Interface 75
              Remote Interface 76
              Helper Classes 76
              Running the CartEJB Example 76
          Other Enterprise Bean Features 78
              Accessing Environment Entries 78
              Comparing Enterprise Beans 80
              Passing an Enterprise Bean’s Object Reference 80




                                                                                     69
70                                              A SESSION BEAN EXAMPLE



     The CartEJB Example
       The           session bean represents a shopping cart in an online bookstore. The
            BJ E tr aC
       bean’s client may add a book to the cart, remove a book, or retrieve the cart’s
       contents. To construct         , you need the following code:
                                       BJ E tr aC
            • Session bean class (          n ae Bt ra C     )
            • Home interface (           em oH t ra C   )
            • Remote interface (           t r aC   )
       All session beans require a session bean class. All enterprise beans that permit
       remote access must have a home and remote interface. To meet the needs of a
       specific application, an enterprise bean may also need some helper classes. The
       BJ Et r aCsession bean uses two helper classes,                and             ,
                                                                           n oi tp e cx Ek o oB        r e if ir eV d I
       which are discussed in the section Helper Classes, page (76).
       The source code for this example is in the                                          m ax e /l ai r ot ut ee 2 j
                         directory. To compile the code, go
                                    t ra c/ bj e /c rs /s e lp                                               to    the
                            directory and type            . A sample
                              se lp m ax e/ la i ro tu te e 2j            tr ac tn a                  ra e. p pA tr a C
       file is in the j
       sr ae / se lp ma x e/ la i ro tu te e 2 directory.

       Session Bean Class
       The session bean class for this example is called                         n ae B tr aC   . Like any session
       bean, the          class must meet these requirements:
                    n a eB tr a C
            •   It implements the                interface.
                                          n ae B no is se S
            •   The class is defined as        . ci lb u p
            •   The class cannot be defined as             or     .
                                                                 t ca r ts ba   l a ni f
            •   It implements one or more               methods.
                                                        e ta er C bj e
            •   It implements the business methods.
            •   It contains a         constructor with no parameters.
                                    ci l bu p
            •   It must not define the            method.
                                                ez il a ni f
       The source code for the           n ae Bt r aC       class follows.

            ;* . li tu .a v aj t ro p mi
            ;* . bj e. xa v aj t ro p mi

            { n ae B no is se S s tn e me lp mi na eB t ra C ss a lc c il b up

                ; e ma Nr e mo ts uc gn ir tS
                                                                                      }
            ; )" .t r ac n i t on " + e lt it ( no it p ec xE ko o B we n w or ht
                                                          { ) es la f = = tl u se r( fi
                  ; ) el ti t( t ne me l Ee vo me r .s tn e tn oc = tl us er na el o ob
     { n oi t pe cx E ko oB s w or ht )e lt it gn ir t S( ko oB e vo me r d io v c il bu p
                                                                                             }
                                                ; )e lt i t( tn em e lE dd a. s tn et n oc
                                        { ) el t it g n ir tS (k o oB dd a d io v c il bu p
                                                                                             }
                                                    ;) ( ro tc eV we n = s tn et n oc
                                                                                       }
               ; )d i + " :d i d il a vn I" (n o it pe c xE et ae r C we n w or ht
                                                                                { e s le
                                                                                       }
                                                            ;d i = d Ir em o ts uc
                                             { ) )d i( e ta di la v .r ek ce h Cd i( fi
                           ; ) (r ei f ir eV dI we n = r ek ce h Cd i re i fi re V dI
                                                                                     }
                                                  ; no s re p = e ma Nr em o ts uc
                                                                              { e s le
                                                                                     }
     ; )" .d e wo ll a t on n o sr ep ll uN "( n oi tp e cx Ee ta e rC w e n wo rh t
                                                         { )l lu n = = no s re p( fi
                                                   { no it pe c xE et ae r C sw o rh t
                      ) di g n ir tS ,n os re p g ni r tS (e ta e rC bj e d io v c il bu p
                                                                                             }
                                                    ;) ( ro tc eV we n = s tn et n oc
                                                               ;" 0 " = dI r em ot s uc
                                                                                     }
                                                  ; no s re p = e ma Nr em o ts uc
                                                                              { e s le
                                                                                     }
     ; )" .d e wo ll a t on n o sr ep ll uN "( n oi tp e cx Ee ta e rC w e n wo rh t
                                                         { )l lu n = = no s re p( fi
     { n oi t pe cx E et ae rC sw or h t )n os r ep g ni r tS (e t ae rC bj e d io v c il bu p
                                                                     ; st ne t no c r ot ce V
                                                                  ; dI re mo t su c g ni rt S
71                                  THE CARTEJB EXAMPLE
                                                   ;n os re p = e m aN re mo t su c
                                                                               { es le
                                                                                     }
    ; ) ". de w ol la t o n no s re p ll u N" (n o it pe cx E et ae r C we n w or ht
                                                         { ) ll un == n os r ep ( fi
                                                     { n oi t pe cx E et ae rC sw or ht
                       )d i g ni r tS , no s re p g ni rt S( e ta er C bj e di o v ci lb u p
                                     :                                                 n ae B
 t ra C   method in     e ta e rC bj e
                              3. The EJB container invokes the appropriate
                              2. The EJB container instantiates the enterprise bean.
               ; )" 32 1" , "l ra E eD e ku D "( et a er c. em o h = t ra Cg ni p po hs t r aC
                      method on the home object:          et ae rc   1. The client invokes a
During instantiation, the example program performs the following steps.
instantiate the bean. Only the EJB container can instantiate an enterprise bean.
Because an enterprise bean runs inside an EJB container, a client cannot directly
                                                                The ejbCreate Methods
might use these methods.
methods are empty in the                               n a eB tr a C
                                        class. Later sections explain when you
because they’re declared in the            n ae Bn o is se S
                                                  interface. Consequently, these
ods. The           class doesn’t use these methods, but it must implement them  n ae Bt r aC
the       t xe tn o Cn oi s se St es
               ,              ,              et av i ss aP bj e et av i tc Ab je e vo me R bj e
                                               , and                        meth-
turn extends the         n ae B no is se S
                                 interface. The                e lb a zi la i re S
                                                                interface declares
The                         n a eB es i rp re tn E
                   interface extends the                      interface, which inna eB n oi ss e S
                                                           The SessionBean Interface
                                                                                                }
             } { ) cs t x et no C no is se S (t xe t no Cn oi s se St e s di ov    ci lb up
                                              } { ) (e ta vi s sa Pb j e di ov     ci lb up
                                                }{ )( et av i tc Ab j e di ov      ci lb up
                                                   } { )( ev o me Rb j e di ov     ci lb up
                                                            } { ) (n a eB tr aC    ci lb up
                                                                                        }
                                                               ; st ne t no c nr u te r
                                                { ) ( st ne tn o Ct eg ro tc eV ci lb up
                                                                                           }
                                         A SESSION BEAN EXAMPLE                                      72
                                           THE CARTEJB EXAMPLE                                      73


         }

                    ; )( r ei fi re V dI w e n = re k ce hC di re if i re Vd I
                                      { )) d i( et ad i la v. re k ce hC d i( f i
                                                    ; d i = dI r em ot s uc
                                                                                }
                                                                         { e sl e
         ; )d i +" :d i d il av nI " (n oi t pe cx Ee t ae rC w e n wo r ht
                                                                                }

         ;) (r ot c eV w en = st n et no c
     }

Typically, an
e ta er Cb j e                method initializes the state of the enterprise bean. The
preceding
   et ae rC b je           method, for example, initializes the                    and
                                                                         e ma N re mo ts u c
                 variables with the arguments passed by the
               d I re mo ts u c                                       method.           e ta er c
An enterprise bean must have one or more             methods. The signatures
                                                        e ta er Cb j e
of the methods must meet the following requirements:
     • The access control modifier must be         .    c il bu p
     • The return type must be       . di ov
     • If the bean allows remote access, the arguments must be legal types for the
       Java™ Remote Method Invocation (RMI) API.
     • The modifier cannot be          or
                                       ci ta ts  .    la ni f
The          clause may include the
      sw or ht                                                                         and other
                                                  n oi t pe cx E et ae rC . bj e. xa v aj
exceptions that are specific to your application. The    et ae rC b je             method usually
throws a                     if an input parameter is invalid.
             no it p ec xE et a er C

Business Methods
The primary purpose of a session bean is to run business tasks for the client. The
client invokes business methods on the remote object reference that is returned
by the           method. From the client’s perspective, the business methods
         et a er c
appear to run locally, but they actually run remotely in the session bean. The fol-
lowing code snippet shows how the                   program invokes the business
                                               t ne il Ct r aC
methods:

     ;) " 32 1" , " lr aE e D ek uD " (e ta e rc .e mo h = t ra C gn ip p oh s tr a C
                                                                               . . .
               ;) " se lc i no rh C n ai tr a M eh T" ( ko oB dd a .t ra C gn ip po h s
               ;) " dn al r ed no W n I ec i lA "( ko o Be vo me r .t ra C gn ip po h s
                             ; )( st n et no C te g. tr a Cg ni pp o hs = ts iL ko o b
74                                       A SESSION BEAN EXAMPLE



     The   na eB tr a C   class implements the business methods in the following code:

           { )e lt i t gn ir t S( ko o Bd da d i ov c il b up

               ; ) )e lt it ( gn ir t S we n( t ne me l Ed da .s t ne tn oc
           }

           { no it p ec xE ko o B sw o rh t )e l ti t g ni rt S( k oo Be v om er d i ov c il b up

                      ;) el t it (t n em el Ee v om er . st ne tn o c = t lu se r n ae lo ob
                                                             { ) e sl af == t lu s er ( fi
               ; ) ". tr ac ni t o n" + e l ti t( n oi tp ec x Ek oo B w en w o rh t
                                                                                           }
           }

           { ) (s tn e tn oC t eg r ot c eV c il b up
                          ;s t ne tn oc nr ut er
                                                    }

     The signature of a business method must conform to these rules:
           • The method name must not conflict with one defined by the EJB architec-
             ture. For example, you cannot call a business method                  or       et ae r Cb je
                           .
               e ta vi t cA bj e
           • The access control modifier must be          .   ci lb u p
           • If the bean allows remote access, the arguments and return types must be
             legal types for the Java RMI API.
           • The modifier must not be          or
                                              c it at s .     l an i f
     The          clause may include exceptions that you define for your application.
                 s w or ht
     The               method, for example, throws the
           k oo Be v om er                                             if the book is
                                                                         no it p ec xE k oo B
     not in the cart.
     To indicate a system-level problem, such as the inability to connect to a data-
     base, a business method should throw the                                 . When a
                                                              n o it pe c xE BJ E. b je .x a va j
     business method throws an                   , the container wraps it in a
                                        n o it pe cx E BJ E                                         e to m eR
                , which is caught by the client. The container will not wrap applica-
     no it pe c xE
     tion exceptions such as                 . Because
                                   no i tp ec xE k oo B                is a subclass of
                                                                       no it p ec xE B JE
                        , you do not need to include it in the
     no it pe c xE em it n uR                                             clause of the
                                                                     s wo rh t
     business method.
       (But an              method returns     d io v
                                                 .)                          e ta er C bj e
     • A           method returns the remote interface type of the enterprise bean.      e ta er c
       types.
                                         e ta er c
     • The arguments and return type of the            method must be valid RMI
       of its corresponding             method.             e ta er C bj e
                                      e ta er c
     • The number and types of arguments in a            method must match those
     home interface follow.
                      e ta e rc
     important ways. The rules for defining the signatures of the       methods of a
     The signatures of the             and        e ta e rc        e ta e rC bj e
                                                    methods are similar, but differ in
                                                                                                }
                 ; no it pe c xE et a er C ,n o it pe c xE et om e R
                          s wo r ht ) d i gn ir t S ,n o sr ep g n ir tS (e t ae rc tr aC
                 ; no it pe c xE et a er C ,n o it pe c xE et om e R
                                           sw or h t )n o sr ep g n ir tS (e t ae rc tr aC
                                  { e m oH BJ E s dn et x e em oH t ra C ec a fr et n i ci lb u p
                                                                  ;e mo H BJ E. bj e .x av a j   tr op m i
                                                     ; no it p ec xE et a er C. bj e .x av a j   tr op m i
                                                       ;n oi t pe cx Ee t om eR .i m r. av a j   tr op m i
                                                             ; el ba zi l ai re S. o i. av a j   tr op m i
                                                                                                   em oH tr a C
                                                                                             interface:
     methods in the      et ae r c   signatures with those of the             e t ae rC bj e
                                                                                     Compare the
                                                            no it p ec xE et a er C s wo rh t
                            )d i g ni r tS , no s re p g ni rt S( e ta er Cb j e di o v ci lb u p
                                                                                          . . .
         no i tp ec x Ee ta er C s wo r ht ) no s re p g ni rt S( e ta er Cb j e di o v ci lb u p
                  class follow:                                                                          na e B
       tr aC                      et ae rC b je
             method in the bean class. The signatures of the       methods in the
     e ta er C bj e
             Every           method in the home interface corresponds to an                et a er c
                 ;) ” 32 1" , " lr aE e D ek uD " (e ta e rc .e mo h = t ra C gn ip p oh s tr a C
     method:
     e ta er c
     client may invoke. The                                   t ne i lC tr aC
                                          program, for example, invokes this
                                   e t ae rc
     the purpose of the home interface is to define the        methods that a remote
     A home interface extends the          e mo H BJ E. bj e .x av a j
                                                        interface. For a session bean,
                                                                               Home Interface
75                                     THE CARTEJB EXAMPLE
76                                        A SESSION BEAN EXAMPLE



           • The                  clause of the
                                   s wo r ht                              method must include the
                                                                                               e ta er c
             j                               and the
               n o it pe cx E et om e R. im r. a va                                          .
                                                            n o it pe c xE et ae r C. bj e. x av aj


     Remote Interface
     The remote interface, which extends                        , defines the busi-
                                                         tc e jb OB J E. bj e. x av aj
     ness methods that a remote client may invoke. Here is the source code for the
          remote interface:
     t r aC

                                ;* . li tu .a v aj t ro p mi
                   ; tc ej b OB JE . bj e. xa v aj t ro p mi
           ; no i tp ec xE e to me R .i mr .a v aj t ro p mi

           { t ce jb O BJ E s dn et xe tr aC ec af re t ni c il b up

                ;n o it pe c xE et om e R sw o rh t )e l ti t g ni rt S( k oo Bd d a di ov ci lb up
                                      s wo rh t ) el ti t g ni r tS (k oo B ev om e r di ov ci lb up
               ;n oi t pe cx E et om eR ,n oi t pe cx Ek o oB
                         ; n oi tp ec x Ee to m eR s wo r ht ) ( st ne tn o Ct eg ro tc eV ci lb up
           }

     The method definitions in a remote interface must follow these rules:
           • Each method in the remote interface must match a method implemented
             in the enterprise bean class.
           • The signatures of the methods in the remote interface must be identical to
             the signatures of the corresponding methods in the enterprise bean class.
           • The arguments and return values must be valid RMI types.
           • The          clause must include the
                    s w or ht                                                  .
                                                               n oi tp e cx Ee to m eR .i mr . av aj


     Helper Classes
     The            session bean has two helper classes:
                                B JE tr a C                               and
                                                                n oi tp e cx Ek oo B               i re V dI
          . The                  is thrown by the
               n o it pe c xE ko oB        r e if              method and the k oo B ev om e r     r eV d I
             validates the
     d Ir em o ts uc                     in one of the
                                         re i fi                      methods. Helper
                                                                      e t ae rC bj e
     classes must reside in the EJB JAR file that contains the enterprise bean class.

     Running the CartEJB Example
           1. Start the J2EE server and             lo ot y ol pe d   . For instructions, see the section
              Setting Up, page (22).
                                         THE CARTEJB EXAMPLE                                            77


    2. In l oo t yo lp edopen the      r ae .p p At ra C /s ra e/ s el pm a xe /l ai r ot ut e e2 j
       file (File→Open). You should see the application that is displayed in Fig-
       ure 4–1.
    3. Deploy the            application (Tools→Deploy). In the Introduction dia-
                     p p At ra C
       log box, make sure that you select the Return Client JAR checkbox. For
       detailed instructions, see Deploying the J2EE™ Application, page (37).
    4. Run the application.
       a. In a terminal window, go to the        sr ae / se lp ma x e/ la i ro tu te e 2j      direc-
          tory.
       b. Set the           environment variable to
                    HT AP CP P A                                 r aj . tn ei l Cp pA tr a C.
       c. Type the following command:

        t ne il cn u r   r a e. pp At r aC t ne i lc     t n ei lC t ra C em a n   ht ua t xe t

       d. At the login prompts, enter       ts e ug    for the user name and       3 21 ts eu g   for
          the password.




Figure 4–1 General Tabbed Pane of the       pp A tr aC   Application
78                                  A SESSION BEAN EXAMPLE



     Other Enterprise Bean Features
       The topics that follow apply to both session and entity beans.

       Accessing Environment Entries
       Stored in an enterprise bean’s deployment descriptor, an environment entry is a
       name-value pair that allows you to customize the bean’s business logic without
       changing its source code. An enterprise bean that calculates discounts, for exam-
       ple, might have an environment entry named                         . Before deploy-
                                                           t n ec re P t n uo cs iD
       ing the bean’s application, you could run                    and assign
                                                                    l oo ty o lp ed   tn uo c si D
       tn ec r ePa value of .05 on the Env. Entries tab. (See Figure 4–2.) When you run
       the application, the enterprise bean fetches the .05 value from its environment.




       Figure 4–2 Env. Entries Tab of   na eB re k ce hC
                                                                                                  }
                                                                                      }
                                                     ; )) ( eg as se M te g. xe
                   +" :n oi tp e cx Eg n im aN "( n oi tp e cx EB JE we n wo r ht
                                             { ) x e no i tp ec xE g ni ma N( hc ta c }
                                     ; )t n uo cs id     00 . 1( * t n uo ma n r ut er
                                                                                   }
                                                            ; 00 .0 = tn uo cs i d
                                                                             { es le
                                                                                   }
                    ; ) (e ul aV e lb uo d .t ne cr e Pt nu o cs id = tn uo cs i d
                    { )) (e ul a Ve lb u od .l ev e Lt nu o cs id = > t nu om a ( fi
         ;) " tn ec r eP t nu o cs iD " (p uk oo l .t ne m no ri vn e )e lb uo D (
                                                 = t ne c re Pt nu o cs id e l bu oD
            ; )" le v eL t nu o cs iD " (p uk oo l .t ne m no ri vn e )e lb uo D (
                                                    = l e ve Lt nu o cs id e l bu oD
                     ; )" vn e/ p mo c: a va j" (p u ko ol . la it in i )t xe tn o C(
                                                        = t ne mn or i vn e tx e tn oC
                           ; )( t xe tn o Cl ai ti n I we n = l ai t in i tx e tn oC
                                                                 ;t nu o cs id e l bu od
                                                                                       { y rt
                                   { )t n uo ma e l bu od ( tn uo cs i Dy lp pa el bu o d ci lb u p
               file is in the j           sr ae /s e lp ma x e/ la ir o tu te e 2
                                                            directory.                             r ae .p p A
      re kc e hC
     example is in                r e kc eh c /b je /c r s/ se l pm ax e/ l ai ro t ot ee 2j
                                                                 . A sample
     method, which follows, is in the             n ae B re kc eh C
                                                      class. The source code for this
     t nu oc s iD yl p pa
     code will assign .05 to the                 tn ec r eP tn u oc si d
                                                       variable. The
           l o ot yo lp e d
     you assign a value of .05 to the     t n ec re P t n uo cs iD
                                                            name in             , the
     values for the                    t ne c re P t nu o cs iD
                                       and                            le v eL tn uo c si D
                                                               names. For example, if
                                                pu ko ol
                         parameter. Then it calls      on the environment to get the      vn e/ p mo c: av a j
                    pu ko o l
     locates the environment naming context by invoking                     with the
     entries to calculate a discount based on the purchase amount. First, the method
     In the following code example, the  tn uo c si Dy l pp a
                                                            method uses environment
79                            OTHER ENTERPRISE BEAN FEATURES
80                                        A SESSION BEAN EXAMPLE



     Comparing Enterprise Beans
     A client can determine if two stateful session beans are identical by invoking the
                   method:
     l a ci tn ed I si

          ;) " er ae ps e ka hS ll iB "( e ta er c .e mo h = t ra Ck o ob
                   ; )" e eL y t fe L" (e t ae rc . em oh = tr aC oe d iv
                                                                       . ..
                   { ) ) tr aC k oo b( la c it ne d Is i. tr a Ck oo b( fi
                                                    } .. . e ur t //
                  { )) t ra Co e di v( la c it ne d Is i. tr a Ck oo b( fi
                                                  } . .. e s la f //

     Because stateless session beans have the same object identity, the                  la ci t ne dI s i
     method always returns       when used to compare them.
                                  eu rt
     To determine if two entity beans are identical, the client can invoke the                 n ed I si
           method, or it can fetch and compare the beans’s primary keys:
     la c it

          ; )( y eK yr am i rP te g .a tc ca ) gn ir t S( = 1 y ek g ni r tS
          ; )( y eK yr am i rP te g .b tc ca ) gn ir t S( = 2 y ek g ni r tS

           ) 0 = = )2 y ek (o T er ap mo c .1 ye k( fi
          ;) ” la uq e“ ( nl tn i rp .t uo . me ts yS

     Passing an Enterprise Bean’s Object Reference
     Suppose that your enterprise bean needs to pass a reference to itself to another
     bean. You might want to pass the reference, for example, so that the second bean
     can call the first bean’s methods. You can’t pass the         reference because it
                                                                       si h t
     points to the bean’s instance, which is running in the EJB container. Only the
     container may directly invoke methods on the bean’s instance. Clients access the
     instance indirectly by invoking methods on the object whose type is the bean’s
     remote interface. It is the reference to this object (the bean’s remote reference)
     that the first bean would pass to the second bean.
     A session bean obtains its remote reference by calling the              method     tc ej b OB JE te g
     of the                   interface. An entity bean would call the
                        tx e tn oC no i ss eS                                 tc ej b OB JE t eg
     method of the
               tx et no C yt it n E   interface. These interfaces provide beans with
     access to the instance contexts maintained by the EJB container. Typically, the
                                                                                       .. .
                                                                                          }
                      ;) ) (t ce j bO BJ Et e g. tx e tn oc (s m et Iy po c .t ek s ab
                                                                                      ...
                                 { ) te ks a b te k sa B( nO t Is sa p d io v c il bu p
                                                                                       .. .
                                                                                          }
                                                          ; cs = tx et n oc .s i ht
               { )c s tx e tn oC n oi ss eS ( tx et n oC no is s eS te s d io v c il bu p
                                                                                       .. .
                                                       ; tx et n oc t xe t no Cn o is se S
                        { n ae Bn o is se S s tn em e lp mi n a eB no ga W s sa l c ci lb u p
     fragment shows how a session bean might use these methods.
     bean saves the context in the   t xe tn o Cn oi s se St es
                                                      method. The following code
81                    OTHER ENTERPRISE BEAN FEATURES
82   A SESSION BEAN EXAMPLE
                   5
      Bean-Managed
Persistence Examples
                                                                   Dale Green



 D   ATA is at the heart of most business applications. In J2EE™ applications,
 entity beans represent the business objects that are stored in a database. For
 entity beans with bean-managed persistence, you must write the code for the
 database access calls. Although writing this code is an additional responsibility,
 you will have more control over how the entity bean accesses a database.
 This chapter discusses the coding techniques for entity beans with bean-man-
 aged persistence. For conceptual information on entity beans, please see What Is
 an Entity Bean?, page (51).

 In This Chapter
           The SavingsAccountEJB Example 84
               Entity Bean Class 85
               Home Interface 94
               Remote Interface 96
               Running the SavingsAccountEJB Example 97
           deploytool Tips for Entity Beans With Bean-Managed Persistence 99
           Mapping Table Relationships for Bean-Managed Persistence 99
               One-to-One Relationships 99
               One-to-Many Relationships 103
               Many-to-Many Relationships 110


                                                                                      83
84                                            BEAN-MANAGED PERSISTENCE EXAMPLES


                    Primary Keys for Bean-Managed Persistence 113
                        The Primary Key Class 113
                        Primary Keys in the Entity Bean Class 114
                        Getting the Primary Key 115
                    Handling Exceptions 116



     The SavingsAccountEJB Example
       The entity bean illustrated in this section represents a simple bank account. The
       state of                        is stored in the
                              BJ Et n uo cc A sg ni va S                  table of a rela-
                                                                       t nu o cc as g ni va s
       tional database. The
                  t nu o cc as gn i va s         table is created by the following SQL
       statement:

                                      t nu oc c as gn i va s EL B AT E TA E RC
                                                      ) 3( RA HC R AV d i(
             ,Y EK YR AM IR P t nu o cc as gn i va s_ k p TN IA R TS NO C
                                        ,) 42 ( RA HC R AV e ma n ts ri f
                                        ,) 42 ( RA HC R AV em a nt sa l
                                   ; )) 2, 01 ( CI RE M UN     e c na la b

       The   B JE t nu oc c As gn iv a S   example requires the following code:
             • Entity bean class (         n ae Bt n uo cc As g ni va S    )
             • Home interface (       em o Ht nu o cc As gn i va S     )
             • Remote interface (          tn uo c cA sg ni v aS   )
       This example also makes use of the following classes:
             • A utility class named           no i tp ec x Ee cn al a Bt ne i ci ff us n I
             • A client class called         t ne il Ct n uo cc A sg ni va S
       The source code for this example is in the                                    m ax e /l ai r ot ut ee 2 j
                                     directory. To compile the code, go to the
       t nu oc c as gn i va s/ bj e /c rs /s e lp
                            directory and type
                 se lp m ax e/ la i ro tu te e 2j                   . A sample
                                                             tn u oc ca sg n iv as tn a
                           file is in the j
                 ra e. p pA tn uo c cA sg ni v aS                     directory.
                                                            sr ae / se lp ma x e/ la ir o tu te e 2
                                               THE SAVINGSACCOUNT EJB EXAMPLE          85


Entity Bean Class
The sample entity bean class is called                            . As you look
                                                        n ae B tn uo c cA sg ni v aS
through its code, note that it meets the requirements of any entity bean with
bean-managed persistence. First of all, it implements the following:
    •              interface
         n ae By t it nE
    • Zero or more             and
                             et ae r Cb je      methods
                                                 e ta er C ts oP b je
    • Finder methods
    • Business methods
    • Home methods
In addition, an entity bean class with bean-managed persistence has these
requirements:
     •   The class is defined as        .
                                       c il bu p
     •   The class cannot be defined as            tc ar t sb a   or   la n if   .
     •   It contains an empty constructor.
     •   It does not implement the           ez i la ni f   method.

The EntityBean Interface
The               interface extends the
                       na e By ti t nE                   interface, which extends
                                               n a eB es i rp re tn E
the                  interface. The
                    e lb a zi la i re S         interface declares a number of
                                                          na eB y ti tn E
methods, such as
     e ta vi t cA bj e           and        , which you must implement in your
                                                              da oL b je
entity bean class. These methods are discussed in later sections.

The ejbCreate Method
When the client invokes a        method, the EJB container invokes the corre-
                                   e ta er c
sponding             method. Typically, an
            e ta er Cb j e                          method in an entity bean
                                                            et ae r Cb je
performs the following tasks:
     • Inserts the entity state into the database
     • Initializes the instance variables
     • Returns the primary key
The            method of
     e ta er C bj e                                inserts the entity state into the
                                    na eB t nu oc c As gn iv a S
database by invoking the private                method, which issues the SQL
                                       wo Rt r es ni
        statement. Here is the source code for the
TR ES N I                                                       method:
                                                                   et a er Cb je
                      , it should assume that the entity was not created.       no it pe c xE ye Ke t ac
 i lp u D            n o it pe cx E et ae r C
                    ). If a client receives a                          or a      n oi tp e cx Ee ta e rC
                     n o it pe cx E ye Ke t ac il pu D .b je . xa va j
exists, it should throw a                                             (a subclass of
cannot create an entity because another entity with the same primary key already
a            et a er Cb je
                         if an input parameter is invalid. If an               n oi tp ec x Ee ta e rC
                                                                             method
                               et a er Cb je
tions that are specific to your application. An               method usually throws
The              no i tp ec xE e ta er C .b je .x a va j
              clause may include the                                      and excep-      sw or h t
                               .c i ta ts
                The method modifier cannot be la n if or                                          •
                The arguments must be legal types for the Java™ 2 RMI API.                        •
                The return type must be the primary key.                                          •
                                      ci lb u p
                The access control modifier must be         .                                     •
                                                                                    rules:
method for an entity bean, be sure to follow these                  et ae r Cb je   When writing an
directory.
tr ac / bj e/ c rs /s el p ma xe / la ir ot u te e2 j
the               source code in the                                             a va j. B JE tr aC
enterprise bean may contain multiple   e ta e rC bj e
                                                methods. For an example, see
Although the     et a er Cb je      class has just one     n a eB tn uo c cA sg n iv aS
                                                                 method, an
                                                                                                  }
                                                                               ; di nr ut er
                                                          ;e cn a la b = e cn al a b. si ht
                                                       ;e ma Nt s al = em aN ts a l. si ht
                                                   ; e ma Nt sr i f = e ma Nt sr i f. si ht
                                                                        ;d i = d i. si ht
                                                                                       }
                                                      ; )) (e g as se M te g. xe
                            + " : et ae rC b je "( n oi tp ec x EB JE we n wo r ht
                                                      { ) xe no it p ec xE ( h ct ac }
                    ;) ec n al ab ,e ma Nt s al , e ma Nt sr i f ,d i (w oR tr e sn i
                                                                                  { y rt
                                                                                      }
            ; )" . de wo ll a t on si e cn a la b l ai ti ni ev it a ge n A" (
                                                no i tp ec xE e ta er C w en w o rh t
                                               { ) 1 == ) ( mu ng i s. ec na l ab ( fi
                                                      { n oi t pe cx E et ae rC sw or ht
                                    ) ec na l ab l a mi ce Dg i B ,e m aN ts al gn ir tS
                 ,e ma Nt s ri f g ni rt S , di g n ir tS (e t ae rC b je g ni r tS c il b up
                           BEAN-MANAGED PERSISTENCE EXAMPLES                                               86
                                                 THE SAVINGSACCOUNT EJB EXAMPLE                                87


The state of an entity bean may be directly inserted into the database by an appli-
cation that is unknown to the J2EE server. For example, a SQL script might
insert a row into the                    table. Although the entity bean for this
                              tn u oc ca sg n iv as
row was not created by an              method, the bean can be located by a cli-
                               e ta er Cb j e
ent program.

The ejbPostCreate Method
For each                method, you must write an
                             e ta e rC ts oP b je                method in the        et a er Cb je
entity bean class. The EJB container invokes
                                  e ta er Ct s oP bj e       immediately after
it calls             . Unlike the
                     e ta er C ts oP b je   method, the               method
                                                           e ta e rC bj e                 e t ae rC bj e
can invoke the
            no Cy t it nE         and               methods of the
                                                tc e jb OB J Et eg       ye K yr am ir P te g
tx e t interface. For more information on the
                                     t ce j bO BJ Et e g  method, see the sec-
tion Passing an Enterprise Bean’s Object Reference, page (80). Often, your
                   methods will be empty.
et ae r Ct so Pb j e
The signature of an          et ae rC t so Pb j e    method must meet the following require-
ments:
     • The number and types of arguments must match a corresponding                              er Cb j e
           method.
         e ta
     • The access control modifier must be      .           c il bu p
     • The method modifier cannot be       or        .l an i f    ci t at s
     • The return type must be      .      di ov
The           clause may include the
      s wo rh t                                     n oi t pe cx Ee t ae rC . bj e. xa v aj   and excep-
tions that are specific to your application.

The ejbRemove Method
A client deletes an entity bean by invoking the        method. This invocation
                                                                 ev om er
causes the EJB container to call the            method, which deletes the entity
                                                             e vo m eR bj e
state from the database. In the                           class, the
                                                 n ae Bt n uo cc A sg ni va S                 e vo me R bj e
method invokes a private method named                   , which issues a SQL
                                                 w oR et e le d
        statement. The
ET EL E D                           method is short:
                                e vo me R bj e

                                    { )( e vo me Rb j e di o v ci lb u p
                                                             { y rt
                                        ; ) di (w oR e te le d
                                  { ) xe no it pe c xE ( h ct ac
     + " :e v om eR bj e "( no i tp ec xE B JE w en wo rh t
                                    ;) )( e ga ss eM t eg .x e
                                                                  }
                                                                       }
88                                           BEAN-MANAGED PERSISTENCE EXAMPLES



     If the              method encounters a system problem, it should throw the
                        ev om e Rb je
                                 . If it encounters an application error, it should throw
            n oi tp e cx EB JE . bj e. xa v aj
     a                                   . For a comparison of system and application
     no it p ec xE ev o me R. b je .x av a j
     exceptions, see the section Handling Exceptions, page (116).
     An entity bean may also be removed directly by a database deletion. For exam-
     ple, if a SQL script deletes a row that contains an entity bean state, then that
     entity bean is removed.

     The ejbLoad and ejbStore Methods
     If the EJB container needs to synchronize the instance variables of an entity bean
     with the corresponding values stored in a database, it invokes the             and      d a oL bj e
                methods. The
     e ro tS b je                       method refreshes the instance variables from
                                         d ao Lb j e
     the database, and the            method writes the variables to the database. The
                                            er ot S bj e
     client may not call          and
                              e ro tS b je      .da o Lb je
     If a business method is associated with a transaction, the container invokes                      b je
     d a oL before the business method executes. Immediately after the business
     method executes, the container calls             . Because the container invokes
                                                      e ro tS bj e
     da oL b jeand           , you do not have to refresh and store the instance vari-
                       er o tS bj e
     ables in your business methods. The                            class relies on the
                                                       na eB tn u oc cA sg n iv aS
     container to synchronize the instance variables with the database. Therefore, the
     business methods of                           should be associated with transac-
                                 n ae B tn uo cc A sg ni v aS
     tions.
     If the          and             methods cannot locate an entity in the underlying
                                                                    e ro t Sb je       da oL b je
     database, they should throw the
            no it pe c xE yt it n Eh cu S oN .b je . xa va j                     . This
     exception is a subclass of
                    n oi tp e cx EB JE           . Because
                                                     n oi t pe cx EB J E  is a subclass
     of                    , you do not have to include it in the
                     s w or ht                                           clause. When
                                                                             n oi tp e cx Ee mi t nu R
     x Ee t om eR               is thrown, the EJB container wraps it in a
                                                                         no it p ec xE yt i tn Eh cu S oN
              before returning it to the client.                                               no it p ec
     In the                        class,
              n ae B tn uo c cA sg ni v aS        invokes the
                                                   da o Lb je          method, which
                                                                               w o Rd ao l
     issues a SQL            statement and assigns the retrieved data to the instance
                      TC E LE S
     variables. The
                  e ro t Sb je  method calls the            method, which stores the
                                                                w oR e ro ts
     instance variables in the database with a SQL         statement. Here is the code
                                                                 ET AD P U
     for the          and
               da oL bj e            methods:
                                er o tS bj e

          { )( da o Lb je d i ov c il b up

                                            { y rt
                                ;) (w oR d ao l
               { )x e n oi tp e cx E( h c ta c }
     y eK yr a mi rP y Bd ni Fb j e
                               and                                e gn aR n Id ni F bj e
                                                   , are optional—but the                      em aN ts a L
       yB dn i Fb je The finder methods that are specific to your application, such as
                                                                                                      }
                                                                        ;t lu s er n r ut er
                                                                                           }
                                                        ; )) (e ga s se Mt eg . xe
                   + " em aN t sa Ly B dn iF bj e "( no i tp ec xE B JE w en wo rh t
                                                        { ) xe n o it pe cx E ( hc t ac }
                                  ;) e ma Nt sa l (e ma N ts aL yB t ce le s = t lu s er
                                                                                       { yr t
                                                                      ; tl us er no it c el lo C
                                                           { no it p ec xE re d ni F s wo rh t
                    ) em aN ts a l gn i rt S( em a Nt sa L yB dn iF b je n oi t ce ll o C ci lb u p
     method as follows:
     e ma Nt s aL yB d ni Fb je
                        class, for example, implements the                          n a eB tn u oc cA sg n i
      va S         d ni Fb j e
     ment a corresponding method that begins with the prefix              . The
     For every finder method available to a client, the entity bean class must imple-
                             ; ) 00 .9 9 , 00 .0 2 (e gn a Rn Id ni f .e mo h = c n o it ce ll o C
                                                                                              ...
                                 ;) "h t im S" (e m aN ts a Ly Bd ni f .e mo h = c n o it ce ll o C
                                                                                              ...
                    ; )" 63 8" ( ye Ky r am ir Py B dn if . em oh = se no j t nu oc c As gn iv a S
                                 program locates entity beans with three finder methods:            tn ei l C
      tn uo c cA sg n iv aS
                          The finder methods allow clients to locate entity beans. The
                                                                           The Finder Methods
                                                                                                      }
                                                                                              }
                                                           ; )) (e ga s se Mt eg . xe
                                  + " : e ro tS bj e "( no i tp ec xE B JE w en wo rh t
                                                           { ) xe n o it pe cx E ( hc t ac }
                                                                            ; )( w oR er o ts
                                                                                           { yr t
                                                                 { ) ( er ot Sb j e di o v ci lb u p
                                                                                                      }
                                                                                              }
                                                          ; )) (e ga s se Mt eg . xe
                                   + " : da oL bj e "( no i tp ec xE B JE w en wo rh t
89                        THE SAVINGSACCOUNT EJB EXAMPLE
90                                         BEAN-MANAGED PERSISTENCE EXAMPLES



     method is required. As its name implies, the                              method
                                                                y eK y ra mi rP y Bd ni F bj e
     accepts as an argument the primary key, which it uses to locate an entity bean. In
     the                       class, the primary key is the
                     n a eB tn u oc cA sg n iv aS                variable. Here is the
                                                                            di
     code for the
         ye Ky r am ir Py B dn iF b je   method:

          )y eK yr a mi rp gn ir tS ( ye Ky r am ir Py B dn iF b je g ni r tS c il b up
                                               { n oi t pe cx E re dn iF sw or ht

              ; t lu se r n ae lo ob

                                                                                      { y rt
                           ; )y eK y ra mi rp ( ye Ky r am ir Py B tc el e s = tl u se r
                                                        { )x e n oi tp e cx E( h c ta c }
              + " :y eK yr a mi rP y Bd ni Fb j e" (n o it pe cx E BJ E w en w or h t
                                                        ;) )( eg a ss eM t eg .x e
                                                                                          }

                                                                        { )t lu s er ( fi
                                                           ;y e Ky ra m ir p nr u te r
                                                                                        }
                                                                                  { es le
                                   n oi tp e cx Ed n uo Ft oN t ce jb O w en w o rh t
              ; ) ". dn uo f t on " + ye K yr am i rp + " di r o f wo R" (
                                                                                        }
          }

     The                           method may look strange to you, because it uses a
          y eK yr a mi rP yB d ni Fb j e
     primary key for both the method argument and return value. However, remember
     that the client does not call                         directly. It is the EJB con-
                                ye Ky ra m ir Py B dn iF bj e
     tainer that calls the                          method. The client invokes the
                                       y eK y ra mi rP y Bd ni F bj e
                          method, which is defined in the home interface.
     ye Ky ra m ir Py Bd n if
     The following list summarizes the rules for the finder methods that you imple-
     ment in an entity bean class with bean-managed persistence:
          • The                         method must be implemented.
                   ye K yr am ir P yB dn i Fb je
          • A finder method name must start with the prefix            . d ni Fb j e
          • The access control modifier must be         .  ci lb u p
          • The method modifier cannot be         or  la n if.  c i ta ts
          • The arguments and return type must be legal types for the Java 2 RMI API.
            (This requirement applies only to methods defined in a remote—not
            local—home interface.)
          • The return type must be the primary key or a collection of primary keys.
     program invokes the business methods as follows:              t ne il Ct n uo cc A sg ni va S    The
                                                                                                  }
                                                                       ;e cn a la b n ru te r
                                                 { )( e cn al aB t eg l am i ce Dg i B ci lb u p
                                                                                                  }
                                                                     ; em aN t sa l n ru te r
                                                      { )( em aN t sa Lt eg gn ir t S ci lb u p
                                                                                                  }
                                                                    ;e ma Nt s ri f n ru te r
                                                    { ) (e ma Nt s ri Ft eg gn ir t S ci lb u p
                                                                                                  }
                                                ; )t nu o ma (d da . ec na la b = e c na la b
                                      { )t nu o ma l a mi ce Dg i B( ti de r c di o v ci lb u p
                                                                                                  }
                                         ; )t nu o ma (t c ar tb us . ec na la b = e c na la b
                                                                                             }
                         ; )( n oi tp e cx Ee cn a la Bt n ei ci ff u sn I we n w or h t
                                    { )1 == )t nu o ma (o Te r ap mo c. e cn al a b( f i
                                     { n oi tp e cx Ee c na la Bt n ei ci ff u sn I s wo rh t
                                          ) tn u om a l am ic eD g iB (t ib e d di o v ci lb u p
                             class contains the following business methods: na eB t nu oc c As gn iv a S
     allowing you to separate the business logic from the database access code. The
     within the entity bean. Usually, the business methods do not access the database,
     The business methods contain the business logic that you want to encapsulate
                                                                    The Business Methods
     objects, it should return an empty collection.
     finder method returns a collection of primary keys and it does not find any
           no i tp ec xE r ed ni F                   n oi tp e cx Ed nu o Ft oN tc e jb O. b je .x av a j
                                                 (a subclass of                    ). If a
     mary key and the requested entity does not exist, the method should throw the
     tions that are specific to your application. If a finder method returns a single pri-
     The          n oi t pe cx Er e dn iF . bj e. xa v aj
                   clause may include the                                     and excep- s wo rh t
91                      THE SAVINGSACCOUNT EJB EXAMPLE
92                                        BEAN-MANAGED PERSISTENCE EXAMPLES


                       ; ) "0 0. 0 "( la mi c eD gi B w en = tn uo m Ao re z l am ic eD g iB
          , "l r aE " ," e ku D" ," 32 1" ( et ae r c. em oh = ek u d tn uo c cA sg ni v aS
                                                                         ;) tn uo m Ao re z
                                                                                          . . .
                                       ; )) " 05 .8 8 "( la mi c eD gi B w en (t i de rc .e k ud
                                         ;) ) "5 2. 0 2" (l am i ce Dg i B we n( t ib ed .e k ud
                                    ; )( ec n al aB t eg .e ku d = e c na la b l am ic eD g iB

     The requirements for the signature of a business method are the same for both
     session and entity beans:
          • The method name must not conflict with a method name defined by the
            EJB architecture. For example, you cannot call a business method                             b je
                   or
              e ta er C             .
                           et av it c Ab je
          • The access control modifier must be       .       ci lb u p
          • The method modifier cannot be         or       .
                                                        la n if    c i ta ts
          • The arguments and return types must be legal types for the Java 2 RMI
            API. This requirement applies only to methods defined in a remote—not
            local—home interface.
     The           clause may include the exceptions that you define for your applica-
                        s w or ht
     tion. The         method, for example, throws the
                   t i be d                                         p ec x Ee cn a la Bt ne i ci ff u sn I
           . To indicate a system-level problem, a business method should throw the
                                 n o it
                                 .
     n oi tp e cx EB JE . bj e. xa v aj

     The Home Methods
     A home method contains the business logic that applies to all entity beans of a
     particular class. In contrast, the logic in a business method applies to a single
     entity bean, an instance with a unique identity. During a home method invoca-
     tion, the instance has neither a unique identity nor a state that represents a busi-
     ness object. Consequently, a home method must not access the bean’s
     persistence state (instance variables). (For container-managed persistence, a
     home method also must not access relationships.)
     Typically, a home method locates a collection of bean instances and invokes
     business methods as it iterates through the collection. This approach is taken by
     the                                   method of the
          e cn al a Bw oL r oF eg ra h Ce mo H bj e                              class.
                                                                          na e Bt nu oc c As gn i va S
     The                                    method applies a service charge to all sav-
         e cn al a Bw oL ro F eg ra h Ce mo Hb j e
     ings accounts with balances less than a specified amount. The method locates
     these accounts by invoking the                 method. As it iterates through the
                                               e g na Rn I dn if
     collection of                     instances, the
                       tn u oc cA sg n iv aS                       ec na l aB wo L ro Fe gr a hC em o Hb je
                                                  ci ta t s
                                          • The method modifier cannot be       .
                                             c il bu p
                                          • The access control modifier must be      .
                        .   e mo Hb j e   • A home method name must start with the prefix
     these rules:
     In the entity bean class, the implementation of a home method must adhere to
                                                            ; )) "0 0. 1 "( la mi c eD gi B w en
                            ,) "0 0 .0 1" ( la mi ce D gi B w en (e cn a la Bw oL r oF eg r ah c. em o h
                                                                                                . . .
                                                                  ; em o h em oH t nu oc c As gn iv a S
     follows:
     client view, the                                      tn ei lC t nu oc c As gn iv a S
                                             program invokes the home method as
           (see Home Method Definitions, page (96)). Since the interface provides the                 ec n a
      la Bw o Lr oF e gr ah c
     The home interface defines a corresponding method named
                                                                                                      }
                                                                                            }
                                                       ;) ) (e ga ss e Mt eg .x e +
        " : e cn al a Bw oL ro F eg ra h Ce mo Hb j e" (n o it pe cx E BJ E we n w or h t
                                                            { )x e n oi tp ec x E( h c ta c }
                                                                                        }
                                                                                   }
                                               ;) e gr ah c (t ib ed . tn uo cc a
        { ) 1 = = ) eg ra hc ( oT er a pm oc .) ( ec na l aB te g. t nu oc ca ( f i
        ; )( t xe n. i )t nu oc c As gn i va S( = tn uo c ca t nu o cc As gn i va S
                                                          { ) )( tx e Ns ah .i ( e li h w
                                                     ; )( ro t ar et i. c = i r o ta re t I
        ; )) ) "1 0. 0 "( la mi c eD gi B w en (t c ar tb u s. ec na l aB mu mi n im
     , )" 00 . 0" (l a mi ce Dg i B we n (e gn aR n Id ni f .e mo h = c n o it ce ll o C
                           ; )( e mo HB J Et eg .t x et no c )e mo Ht n uo cc As g ni va S (
                                                     = em o h em oH t nu oc cA s gn iv a S
                                                                                           { yr t
                                       { no it pe c xE ec n al aB tn e ic if fu s nI s w or ht
                            )e gr a hc l a mi ce Dg i B ,e c na la Bm u mi ni m l am ic e Dg iB
                                           (e cn al a Bw oL r oF eg ra h Ce mo Hb j e di o v ci lb u p
     method:                                 e cn a la Bw o Lr oF eg r ah Ce m oH bj e
                                                         source code of the
     business method. Here is the            t i be d    method checks the balance and invokes the
93                          THE SAVINGSACCOUNT EJB EXAMPLE
94                                    BEAN-MANAGED PERSISTENCE EXAMPLES



     The s wo r ht clause may include exceptions that are specific to your application;
     it must not throw the                              .
                            no i tp ec x Ee to me R .i mr . av aj

     Database Calls
     Table 5–1summarizes the database access calls in the                     na eB t nu oc c As gn iv a S
     class. The business methods of the                        class are absent from
                                               n ae B tn uo c cA sg ni v aS
     the preceding table because they do not access the database. Instead, these busi-
     ness methods update the instance variables, which are written to the database
     when the EJB container calls            . Another developer might have chosen
                                        e ro t Sb je
     to access the database in the business methods of the                    na eB t nu oc c As gn iv a S
     class. This choice is one of those design decisions that depend on the specific
     needs of your application.


     Table 5–1 SQL Statements in        n ae Bt n uo cc A sg ni va S

      Method                     SQL Statement

      etaerCbje                  TRESNI

      yeKyramirPyBdniFbje        TCELES

      emaNtsaLyBdniFbje          TCELES

      egnaRnIdniFbje             TCELES

      daoLbje                    TCELES

      evomeRbje                  ETELED

      erotSbje                   ETADPU



     Before accessing a database, you must connect to it. For more information, see
     Chapter 16.

     Home Interface
     The home interface defines the methods that allow a client to create and find an
     entity bean. The                     interface follows:
                       em oH t nu oc cA s gn iv a S
          , whereas the corresponding name in the entity bean class begins with                          dn i f
     entity bean class. The name of a finder method in the home interface begins with
     Every finder method in the home interface corresponds to a finder method in the
                                                                    Finder Method Definitions
                            no it p ec xE e to me R. i mr .a v aj
                clause includes the                                .                       s w or ht
     • If the method is defined in a remote—not local—home interface, then the
     • The      . no it pe c xE et a er C. bj e .x av aj
                     clause includes the                                             sw o rh t
       of the corresponding     et a er Ct so P bj e
                                          and              e t ae rC bj e
                                                               methods.
     • The   sw or htclause includes the exceptions specified by the    clause       s wo r ht
     • It returns the remote interface type of the enterprise bean.
       method in the enterprise bean class.
     e ta er C bj e
     • It has the same number and types of arguments as its matching
     requirements:
     Each          method in the home interface must conform to the following               e ta er c
                                                                    create Method Definitions
                                                                                                        }
        ; no i tp ec x Ee to me R , no i tp ec xE e cn al a Bt ne ic i ff us nI sw or h t
                                                               )e gr a hc l am i ce Dg i B
      , ec na la B mu mi ni m l a mi ce Dg i B( ec n al aB wo L ro Fe g ra hc di ov ci lb u p
                             ; no i tp ec x Ee to me R , no i tp ec xE r ed ni F s wo rh t
                                                                  ) hg i h la mi c eD gi B
                            ,w ol la mi c eD gi B( e gn aR n Id ni f n oi tc el l oC c i lb up
                              ; no i tp ec x Ee to me R , no i tp ec xE r ed ni F s wo rh t
                      ) e ma Nt sa l g ni r tS (e ma N ts aL y Bd ni f n oi tc el l oC c i lb up
                             ; no i tp ec x Ee to me R , no i tp ec xE r ed ni F s wo rh t
                      ) d i gn ir t S( ye K yr am ir P yB dn i f tn uo c cA sg ni v aS c i lb up
                         ; no i tp ec x Ee ta er C , no i tp ec xE e to me R s wo rh t
                                )e cn a la b la m ic eD g iB , em a Nt sa l g ni rt S
      ,e ma N ts ri f g ni rt S , di gn ir tS ( et ae r c tn uo c cA sg n iv aS c i lb up
                      { em oH BJ E s dn e tx e em o Ht nu o cc As gn i va S ec a fr et n i ci lb u p
                                                                           ; *. bj e .x av a j   tr op m i
                                                       ;n oi t pe cx Ee t om eR .i m r. av a j   tr op m i
                                                             ; la mi ce D gi B. ht a m. av a j   tr op m i
                                                             ; no it ce l lo C. li t u. av a j   tr op m i
95                          THE SAVINGSACCOUNT EJB EXAMPLE
96                                         BEAN-MANAGED PERSISTENCE EXAMPLES



             . For example, the
       dn iF b je                                      class defines the
                                    e mo Ht n uo cc As g ni va S                             t sa L yB dn i f
          method, and the
           e m aN                                  class implements the
                                         na eB t nu oc cA s gn iv a S                        y Bd n iF bj e
               method. The rules for defining the signatures of the finder methods of
     e ma Nt s aL
     a home interface follow.
          • The number and types of arguments must match those of the correspond-
            ing method in the entity bean class.
          • The return type is the entity bean’s remote interface type, or a collection
            of those types.
          • The exceptions in the           clause include those of the corresponding
                                             s wo rh t
            method in the entity bean class.
          • The          clause contains the
                    s w or ht                                               .
                                                         n oi tp e cx Er e dn iF .b j e. xa va j
          • If the method is defined in a remote—not local—home interface, then the
            throws clause includes the                           .
                                                  n oi t pe cx Ee t om eR . im r. av a j

     Home Method Definitions
     Each home method definition in the home interface corresponds to a method in
     the entity bean class. In the home interface, the method name is arbitrary, pro-
     vided that it does not begin with        or
                                      e ta er c        . In the bean class, the matching
                                                              dn i f
     method name begins with             . For example, in the
                                            e mo Hb j e                           na eB t nu oc c As gn iv a S
     class the name is                              , but in the
                               ec na la B wo Lr o Fe gr ah C bj e                 em oH t nu oc c As gn iv a S
     interface the name is                        .
                                e cn a la Bw oL r oF eg r ah c
     The home method signature must follow the same rules specified for finder
     methods in the previous section (except that a home method does not throw a
                      ).
     n oi tp e cx Er ed n iF


     Remote Interface
     The remote interface extends                         and defines the business
                                              t ce j bO BJ E .b je .x a va j
     methods that a remote client may invoke. Here is the                  remote
                                                                               t nu o cc As gn i va S
     interface:

                  ; tc ej b OB JE . bj e. xa v aj t ro p mi
          ; no i tp ec xE e to me R .i mr .a v aj t ro p mi
                 ;l am ic e Dg iB . ht am .a v aj t ro p mi

          { t ce j bO BJ E s dn et x e tn u oc cA sg n iv aS ec af re t ni c il b up

                                                 )t nu om a l am i ce Dg iB ( ti be d d io v c il bu p
                ; no i tp ec x Ee to me R , no i tp ec xE e cn al a Bt ne ic i ff us n I sw or h t
                                             THE SAVINGSACCOUNT EJB EXAMPLE                    97


         ) t nu om a l am ic e Dg iB (t i de rc d i ov c i lb up
                        ; no i tp ec xE e to me R s wo rh t

         )( em a Nt sr iF t eg g ni r tS c i lb up
          ; no i tp ec xE e to me R s wo rh t

         ) (e m aN ts aL t eg g ni r tS c i lb up
         ; no i tp ec xE e to me R s wo rh t

         ) ( ec na l aB te g l am ic eD g iB c i lb up
              ; no i tp ec xE e to me R s wo rh t
    }

The requirements for the method definitions in a remote interface are the same
for both session and entity beans:
    • Each method in the remote interface must match a method in the enterprise
      bean class.
    • The signatures of the methods in the remote interface must be identical to
      the signatures of the corresponding methods in the enterprise bean class.
    • The arguments and return values must be valid RMI types.
    • The          clause must include
            sw o rh t                            . no i tp ec xE e to me R .i mr .a v aj
A local interface has the same requirements, with the following exceptions:
    • The arguments and return values are not required to be valid RMI types.
    • The       clause does not include
            sw o rh t                                . n oi tp ec x Ee to m eR .i mr . av aj


Running the SavingsAccountEJB Example
Setting Up the Database
The instructions that follow explain how to use the                  exam-
                                                                 B JE t nu oc c As gn iv a S
ple with a Cloudscape database. The Cloudscape software is included with the
J2EE SDK download bundle.
    1. From the command-line prompt, run the Cloudscape database server by
       typing                      (When you are ready to shut down the
                 . tr a ts e pa cs du o lc
       server, type                .)
               p o ts ep a cs du o lc
    2. Create the               database table.
                    t n uo cc as g ni va s
        a. Go to the    s e lp ma x e/ la ir o tu te e 2j   directory
        b. Type  e lb a t tn uo c ca sg n iv as e t ae rc t n a    .
98                                         BEAN-MANAGED PERSISTENCE EXAMPLES



     You may also run this example with databases other than Cloudscape. (See the
     Release Notes of the J2EE SDK for a list of supported databases.) If you are
     using one of these other databases, you may run the                    m ax e /l ai r ot ut ee 2 j
                                    script to create the
     l qs .t n uo cc a sg ni va s /l qs /s e lp                         table.         t nu o cc as gn i va s

     Deploying the Application
          1. In
              l oo ty o lp ed       , open the     c As g ni va S /s ra e/ s el pm a xe /l ai r ot ut e e2 j
               r a e. pp A tn uo c  file (File→Open).
          2. Deploy the                        application (Tools→Deploy). In the
                                 p pA tn uo c cA sg n iv aS
             Introduction dialog box, make sure that you select the Return Client JAR
             checkbox. For detailed instructions, see Deploying the J2EE™
             Application, page (37).

     Running the Client
          1. In a terminal window, go to the                 s ra e/ s el pm ax e /l ai r ot ut ee 2 j   direc-
             tory.
          2. Set the            environment variable to
                            H TA PC P PA                                      i lC p pA tn u oc cA sg n iv aS
                     .
              r a j. tn e
          3. Type the following command on a single line:

          r ae .p p At nu o cc As gn i va S tn e il c tn ei lc n ur                em an
                             h t ua tx et t ne i lC tn uo c cA sg ni v aS

          4. At the login prompts, enter        for the user name and
                                                  t se u g                               3 2 1t se u g   for the
             password.
          5. The client should display the following lines:

          5 2. 86 = ec na l ab
          3 5. 23 = ec na l ab
                  7 7. 44 : 6 54
                  4 5. 91 : 0 37
                7 0 .0 01 : 8 62
                  5 5. 23 : 6 38
                  7 7. 44 : 6 54
                          0 0 .4
                          0 0 .7
                                      DEPLOYTOOL   TIPS FOR ENTITY BEANS WITH BEAN-MANAGED PERSISTENCE



deploytool Tips for Entity Beans With Bean-
Managed Persistence
  Chapter 4 gave step-by-step instructions for creating and packaging a session
  bean. To build an entity bean, you follow the same procedures, but with the fol-
  lowing exceptions.
      1. In the New Enterprise Bean wizard, specify the bean’s type and persistent
         management.
         a. In the General dialog box, select the Entity radio button.
         b. In the Entity Settings dialog box, select the radio button for Bean-Man-
             aged Persistence.
      2. In the Resource Refs tab, specify the resource factories referenced by the
         bean. These settings enable the bean to connect to the database. For
         instructions, see the section deploytool Tips for Resource
         References, page (354).
      3. Before you deploy the bean, verify that the JNDI names are correct.
         a. Select the application from the tree.
         b. Select the JNDI Names tab.


Mapping Table Relationships for Bean-
Managed Persistence
  In a relational database, tables can be related by common columns. The relation-
  ships between the tables affect the design of their corresponding entity beans.
  The entity beans discussed in this section are backed up by tables with the fol-
  lowing types of relationships:
      • One-to-one
      • One-to-many
      • Many-to-many

  One-to-One Relationships
  In a one-to-one relationship, each row in a table is related to a single row in
  another table. For example, in a warehouse application, a                  table
                                                                     ni be g ar ot s
  might have a one-to-one relationship with a             table. This application
                                                      te g di w
100                                        BEAN-MANAGED PERSISTENCE EXAMPLES



      would model a physical warehouse in which each storage bin contains one type
      of widget and each widget resides in one storage bin.
      Figure 5–1 illustrates the                 and          tables. Because the
                                                                 t e gd iw       ni be ga r ot s e ga r ot s
      di n ib uniquely identifies a row in the                   table, it is that table’s pri-
                                                              n ib e ga ro t s
      mary key. The               is the primary key of the
                                                      t e gd iw        table. The two tables     di te g di w
      are related because the               is also a column in the
                                      n ib e ga ro t s                               table. By
                                                                                      di te gd i w
      referring to the primary key of the
                          e g ar ot s                 table, the
                                               d it eg d iw                  in the
                                                                           t eg di w
      n ib table identifies which widget resides in a particular storage bin in the ware-
      house. Because the               of the
                                d i te gd i w                table refers to the primary key
                                                      ni be ga r ot s
      of another table, it is called a foreign key. (The figures in this chapter denote a
      primary key with PK and a foreign key with FK.)




      Figure 5–1 One-to-One Table Relationship

      A dependent (child) table includes a foreign key that matches the primary key of
      the referenced (parent) table. The values of the foreign keys in the                    ni be g ar ot s
      (child) table depend on the primary keys in the         (parent) table. For exam-
                                                                     t e gd iw
      ple, if the             table has a row with a
                    n i be ga ro t s                            of 344, then the widget
                                                                    di t eg di w
      table should also have a row whose             is 344.
                                                     d it e gd iw
      When designing a database application, you may choose to enforce the depen-
      dency between the parent and child tables. There are two ways to enforce such a
      dependency: by defining a referential constraint in the database or by performing
      checks in the application code. The               table has a referential constraint
                                                    n ib eg a ro ts
      named                :
                d it eg di w _k f

                                        n i be ga r ot s EL B AT E TA E RC
                                  ) 3( RA H CR AV di ni be g ar ot s(
             , YE K YR A MI RP ni be ga r ot s_ k p TN IA R TS NO C
                                       ,) 3 (R AH C RA V di t eg di w
                                            ,R EG E TN I yt i tn au q
                                    di te g di w_ k f TN IA R TS NO C
                                    )d it e gd iw ( Y EK N G IE RO F
                       ; )) di t eg di w( t eg di w S EC NE R EF ER
                                                                       ;d I ni Be ga r ot s g ni rt S
                                                                   { n o it pe cx E LQ S s wo rh t
                              ) dI t eg di w g ni rt S (d It e gd iW yB t ce le s g ni rt S e ta vi r p
                                                       method:                d I te gd i Wy Bt ce l es in the
          by querying the database      d It e gd iw   method locates the     d I te gd iW y Bd ni F bj e
                                                                                                        The
                                                                                                        }
                                                                                              }
                                                             ; dI ni B eg ar ot s n ru t er
                                                                                       { e sl e
                                                                                              }
               ; ) ". dn u of t on " + d It eg di w + " dI te gd i w ro f w oR "(
                                         no it pe c xE dn u oF to Nt c ej bO w e n wo r ht
                                                       { ) ll un = = d In iB e ga ro t s( f i
                                                                                            }
                                                            ; )) (e ga s se Mt eg . xe
                     + " : dI te g di Wy B dn iF bj e "( no i tp ec xE B JE w en wo rh t
                                                            { ) xe n o it pe cx E ( hc t ac }
                            ; )d I te gd i w( dI te g di Wy B tc el es = dI ni B eg ar o ts
                                                                                         { yr t
                                                                       ;d I ni Be ga r ot s g ni rt S
                                                               { no it p ec xE re d ni F s wo rh t
                              ) dI t eg di w g ni rt S (d It e gd iW yB d ni Fb je gn ir t S ci lb u p
                                                            d It eg di w
                                                            that matches a given          :        dI ni Be g a
           ro ts   class returns the    n ae Be g ar ot S                      dI t eg di W yB dn iF b je
                                                                            method of the                   The
                                                                          ; yt it na u q tn i e ta vi r p
                                                                     ; dI t eg di w g ni rt S e ta vi r p
                                                               ; dI ni Be g ar ot s g ni rt S e ta vi r p
                                                                               :               dI te gd i w
                                                   ni b eg ar o ts
                   table, including the foreign key,                 variables for each column in the
          tables. The       n ae B eg ar o tS
                                       class contains         t e gd iw     ni be g ar ot s
                                                                     ship of the              and
           classes illustrate the one-to-one relation-      na e Bt eg di W
                                                                     The        na eB ni B eg ar ot S
                                                                                           and
                                 s ra e/ s el pm ax e /l ai r ot ut ee 2
                        file is in the j                           directory.            ra e. p pA ni Be g a
           ro tS               ni be ga r ot s t na
                                    directory and type                      s el pm ax e /l ai r ot ut ee 2 j
                                                                    . A sample
                                                                         ni b eg ar ot s /b je / cr s/ se l p
                                         directory. To compile the code, go to the
           ma xe / la ir o tu te e2 j
          The source code for the following example is in the
MAPPING TABLE RELATIONSHIPS FOR BEAN-MANAGED PERSISTENCE101
                      c. Type the following command on a single line:
                                 .                                               r aj .t n e
 i lC p pA ni B eg ar ot S
                      b. Set the                                  HT AP CP P A
                                             environment variable to
                      a. Go to the   s ra e /s el pm a xe /l ai r ot ut e e2 j
                                                                  directory.
                                                                  3. Run the client.
                                                                                   s ra e /s el p
                                                                                 directory).
 m ax e /l ai r ot ut ee 2 j   file (located in the   ra e. pp A ni Be g ar ot S   2. Deploy the
                                   .    e lb at ni be g ar ot s e ta er c t na      b. Type
                                directory.   s el pm a xe /l ai r ot ut e e2 j      a. Go to the
                                             database table.     n i be ga ro t s1. Create the
                                           Running the StorageBinEJB Example
                                   ;) (y ti t na uQ t eg .n iB e ga ro t s = yt i tn au q t ni
        ;) (y e Ky ra mi r Pt eg . ni Be ga r ot s) g ni rt S( = dI n iB eg ar o ts g ni r tS
                              ;) d It eg di w (d It e gd iW yB d ni f. e mo Hn iB e ga ro ts
                                                             = ni Be g ar ot s n iB eg ar o tS
                                                            ;" 7 77 " = d It eg d iw g ni r tS
                                   gram calls the              d I te gd iW y Bd ni f
                                                                  method:
pro-   t ne il C ni Be ga r ot S   To find out in which storage bin a widget resides, the
                                                                                                    }
                                                              ; d In iB e ga ro ts nr ut er
                                                                   ; )( e so lc .t m tS pe rp
                                                                                         }
                                                          ;l lu n = d I ni Be ga r ot s
                                                                                   { es le
                                                                                         }
                                        ; )1 ( gn ir t St eg .s r = d I ni Be ga r ot s
                                                                   { ) )( tx en . sr ( fi
                                 ; ) (y re uQ e tu ce x e. tm tS p er p = s r te S tl us eR
                                           ; ) dI te g di w ,1 ( gn ir t St es .t m tS pe rp
                        ; ) tn em e ta tS tc e le s( t ne me ta t Se ra p er p. no c
                                                  = t mt Sp er p t ne m et at Sd e ra pe rP
                        ; " ? = di te gd i w er e hw n ib e ga ro t s mo rf "
                                               + " d in ib eg a ro ts tc el es "
                                                        = t ne m et at S tc el es gn ir tS
                          BEAN-MANAGED PERSISTENCE EXAMPLES                                             102
                                          MAPPING TABLE RELATIONSHIPS FOR BEAN-MANAGED PERSISTENCE103


         t ne il cn u r   ra e .p pA n iB eg ar o tS t ne i lc   t n ei lC n iB eg ar o tS e m an
         h tu at xe t

         d. At the login prompts, enter      ts e ug   for the user name and      3 21 ts eu g   for
            the password.

One-to-Many Relationships
If the primary key in a parent table matches multiple foreign keys in a child
table, then the relationship is one-to-many. This relationship is common in data-
base applications. For example, an application for a sports league might access a
ma e ttable and a          table. Each team has multiple players, and each player
                    r ey a lp
belongs to a single team. Every row in the child table (        ) has a foreign key
                                                                      r ey al p
identifying the player’s team. This foreign key matches the         table’s primary
                                                                  m a et
key.
The sections that follow describe how you might implement one-to-many rela-
tionships in entity beans. When designing such entity beans, you must decide
whether both tables are represented by entity beans, or just one.

A Helper Class for the Child Table
Not every database table needs to be mapped to an entity bean. If a database
table doesn’t represent a business entity, or if it stores information that is con-
tained in another entity, then the table should be represented with a helper class.
In an online shopping application, for example, each order submitted by a cus-
tomer can have multiple line items. The application stores the information in the
database tables shown by Figure 5–2.




Figure 5–2 One-to-Many Relationship: Order and Line Items
                                             { )( e ci rP ti n Ut eg el bu od ci lb up
                                                                                        }
                                                               ; yt it n au q nr u te r
                                                     { ) (y ti t na uQ t eg t ni ci lb up
                                                                                      }
                                                           ; d It cu d or p nr u te r
                                             { )( d It cu do r Pt eg gn ir tS ci lb up
                                                                                         }
                                                   ; dI re dr o = d I re dr o. s ih t
                                                      ; oN me t i = o Nm et i. s ih t
                                             ;e ci r Pt in u = e ci r Pt in u. s ih t
                                                ;y t it na uq = yt i tn au q. s ih t
                                             ;d It c ud or p = d It c ud or p. s ih t
                { )d Ir e dr o g ni rt S , oN me t i tn i , ec ir P ti nu e l bu od
                  ,y ti t na uq tn i ,d I tc ud o rp g ni r tS (m e tI en iL ci lb up
                                                                    ; d Ir ed ro gn ir tS
                                                                           ;o Nm e ti t ni
                                                                 ; ec i rP ti nu el bu od
                                                                        ;y ti tn a uq t ni
                                                                 ; dI t cu do rp gn ir tS
            { e lb az il a ir eS . oi .a va j s tn e me lp mi me tI e ni L ss a lc c il b up
class:
me tI e ni L
able represents the table’s foreign key. Here is the source code for the
      d Ir ed r o                   s m et ie ni l
variable matches the primary key for the               table, and the       vari-
oN me t i               sm et i en il
           class correspond to the columns in the                table. The             m et Ie n iL
relationship with a helper class (         m et Ie n iL
                                                ). The instance variables in the
The             and                                           n ae Br ed r O
                                  classes show how to implement a one-to-many     m e tI en iL
              file is in the j   s ra e/ s el pm a xe /l ai r ot ut e e2
                                                       directory.                          ra e. p pA
 r ed r O                 r ed ro t na
                               directory and type                   se lp m ax e/ la i ro tu te e 2j
                                                            . A sample
the                            directory. To compile the code, go to     r e dr o/ bj e /c rs /s e lp
 m ax e /l ai r ot ut ee 2 j
      The source code for the following example is in the
resources than an entity bean.
doing so might improve performance because a helper class uses fewer system
and not with an entity bean. Using a helper class in this case is not required, but
order. Therefore, the                                        sm e ti en il
                                 table should be represented with a helper class
Not only does a line item belong to an order, it also does not exist without the
                         BEAN-MANAGED PERSISTENCE EXAMPLES                                              104
              method:                                                                                         eta
           er c
          The program passes this                                 t si L ya rr A
                                             to the entity bean when it invokes the
          The         me tI e ni L   t s iL ya rr A
                           program creates and loads an            of            objects.t ne i lC re dr O
                                                                                                          }
                                                                             ; dI re d ro n r ut er
                                                         ; sm e tI en il = sm et I en il . si ht
                                                       ; ec ir P la to t = e ci rP l at ot . si ht
                                                                    ;s ut a ts = s u ta ts . si ht
                                                       ; dI re m ot su c = d Ir em o ts uc . si ht
                                                                 ;d Ir ed r o = dI r ed ro . si ht
                                                                                                  }
                                                                ; )) (e ga s se Mt eg . xe
                                   + " :e t ae rC bj e "( no i tp ec xE B JE w en wo rh t
                                                                { ) xe n o it pe cx E ( hc t ac }
                                                                                              }
                                                                  ;) me ti ( me tI tr e sn i
                        ; ) i( te g. s me tI e ni l) me t Ie ni L ( = me t i me tI e ni L
                            { )+ +i ;) (e z is .s me t Ie ni l < i ; 0 = i t n i( r o f
             ; )e c ir Pl a to t ,s u ta ts ,d Ir em o ts uc ,d Ir ed r o( re dr O tr es n i
                                                                                             { y rt
                                                                { n oi tp e cx Ee ta e rC s w or ht
                  ) s me tI e ni l ts i Ly ar r A ,e ci r Pl at o t el bu o d ,s ut a ts g n ir tS
                  , d Ir em o ts uc g n ir tS ,d Ir ed r o gn i rt S( et a er Cb je gn ir t S ci lb u p
          code for the              method follows:                                et a er Cb j e
          into the       sr ed r o
                                table. It also inserts a single row into the            s me ti en i l
                                                                                    table. The
                     object in the    et ae r Cb je
                                                 variable, the       sm e tI en il
                                                                          method inserts a row      me tI en i L
          able is passed to the      et ae r Cb je
                                                 class in the        na e Br ed r O
                                                                            method. For every
                  s me t Ie ni l
          element in the                         m et Ie ni L
                                        variable is a             object. The sm et Ie n il
                                                                                          vari-
          The      s me t Ie ni l
                           class contains an           ts iL y ar rA
                                                             variable named                  na eB re d rO
                                                                                        . Each
                                                                                                          }
                                                                                                   }
                                                                          ; dI re dr o n ru t er
                                                           { ) ( dI re dr O te g gn i rt S c il bu p
                                                                                                 }
                                                                           ;o Nm et i n ru t er
                                                                 { )( oN m et It eg tn i c il bu p
                                                                                                      }
                                                                       ;e c ir Pt in u n ru t er
MAPPING TABLE RELATIONSHIPS FOR BEAN-MANAGED PERSISTENCE105
                                                                                    ht ua tx e t
                tn e il Cr e dr O em a n     r a e. pp Ar e dr O tn e il c          tn ei lc n ur
                     c. Type the following command on a single line:
     r aj . tn ei l Cp pA re d rO
     .               b. Set the          environment variable to       H TA PC P PA
                     a. Go to the   s ra e /s el pm a xe /l ai r ot ut e e2 j
                                                                 directory.
                                                                     3. Run the client.
                                                                                     s ra e /s el p
                                                                                    directory).
 m ax e /l ai r ot ut ee 2 j   file (located in the           r ae . pp Ar ed r O   2. Deploy the
                                                 .   e lb at re dr o e ta er c t na    b. Type
                        directory.    cr s /s el pm a xe /l ai r ot ut e e2 j          a. Go to the
                                                      database table:.    sr ed r o 1. Create the
                                                       Running the OrderEJB Example
                                                                                             }
                                                        ;) di ( nl tn i rp .t uo . me ts yS
                          ;) (y e Ky ra mi r Pt eg . re dr o) g ni rt S ( = di gn ir tS
                                             ;) (t x en .i )r e dr O( = re dr o r ed rO
                                                                { )) ( tx eN sa h .i ( el i hw
                                                           ;) ( ro ta r et i. c= i r ot ar e tI
                             ;) " 76 p" (d I tc ud o rP yB dn i f. em o h = c n oi tc el l oC
the primary key of each order:
objects. The no it ce l lo C program iterates through the               tn ei l Cr ed rO
                                                                          and prints
gn ir t S d It c ud or p
particular                  no it c el lo C
                       . The method returns a               of                d It cu d or p
                             s m et ie n il
particular line item. This method queries the             table for all rows with a
The                                                                     d It cu do r Py Bd n iF bj e
                             method enables clients to locate all orders that have a
                                s me ti e ni l
                         , with the       and           s re d ro
                                                         tables.                ts i Ly ar r A sm et Ie n il
                               BJ E re dr O
           methods synchronize the state of an             instance, including the              e ro tS b je
     da oL bj e                s m et ie ni l
but also deletes all corresponding rows in the            table. The           and
       sr e dr o
            method, for example, deletes not only a row from the             table,           ev om eR b je
Other methods in the                                           n ae B re dr O
                                     class also access both database tables. The
                                     ; )s m et Ie n il , )s m et Ie n il (s me t Il at ot
                        , "n ep o " ," 44 c " ," 3 21 "( et a er c. e mo h = e ku d re d rO
                                                                                       . . .
         ; )) " 32 1" , 3 , 00 . 14 , 82 ," 11 p "( me tI e ni L w en (d da . sm et Ie n il
         ; )) " 32 1" , 2 , 00 . 98 , 74 ," 76 p "( me tI e ni L w en (d da . sm et Ie n il
         ; )) " 32 1" , 1 , 00 . 21 , 31 ," 32 p "( me tI e ni L w en (d da . sm et Ie n il
                                    ;) (t s iL ya r rA w en = sm e tI en il ts iL ya r rA
                         BEAN-MANAGED PERSISTENCE EXAMPLES                                                     106
                                                MAPPING TABLE RELATIONSHIPS FOR BEAN-MANAGED PERSISTENCE107



         d. At the login prompts, enter           ts e ug   for the user name and        3 21 ts eu g   for
            the password.

An Entity Bean for the Child Table
You should consider building an entity bean for a child table under the following
conditions:
      • The information in the child table is not dependent on the parent table.
      • The business entity of the child table could exist without that of the parent
        table.
      • The child table might be accessed by another application that does not
        access the parent table.
These conditions exist in the following scenario. Suppose that each sales repre-
sentative in a company has multiple customers and that each customer has only
one sales representative. The company tracks its sales force with a database
application. In the database, each row in the              table (parent) matches
                                                                pe rs e la s
multiple rows in the            table (child). Figure 5–3 illustrates this relation-
                           r e mo ts uc
ship.
.




Figure 5–3 One-to-Many Relationship: Sales Representative and Customers

The                and
      na eB p eR se la S                            entity bean classes implement the one-to-
                                       na eB r em ot su C
many relationship of the      r em ot su cand   se la s     tables.
The source code for this example is in the                                     ma xe / la ir o tu te e2 j
                           directory. To compile the code, go to the
                                          p er se la s /b je / cr s/ se l p
pe r se la s t n a       directory and type           . A sample
                                          s el pm ax e /l ai r ot ut ee 2 j                   eR se l aS
        file is in the j
      s ra e/ se l pm ax e /l ai ro t ut ee 2     directory.   ra e. pp A p
The
  n a eB pe R se la S      class contains a variable named               , which is an
                                                                        s dI re m ot su c
              of
gn i rt S t si Ly ar r A     elements. These          elements identify which custom-
                                                    gn ir t S
108                                       BEAN-MANAGED PERSISTENCE EXAMPLES



      ers belong to the sales representative. Because the               variable reflects
                                                                        sd I re mo ts u c
      this relationship, the                class must keep the variable up to date.
                                 na e Bp eR se l aS
      The
      n ae Bp eR s el aS    class instantiates the               variable in the
                                                            s dI re m ot su c                i tn E te s
                   method, not in
                tx et no C yt                    . The container invokes
                                         e ta er C bj e                                      n oC y ti tn E te s
            just once—when it creates the bean instance—ensuring that
                        t x et                                                              sd Ir e mo ts u c
      is instantiated just once. Because the same bean instance can assume different
      identities during its life cycle, instantiating                in          might
                                                                          et a er Cb je     s dI re m ot su c
      cause multiple and unnecessary instantiations. Therefore, the
                                                                 na eB p eR se l aS
      class instantiates the                variable in
                                 s dI re m ot su c                          :      t x et no C yt it nE t es

            { ) tx et n oc t x et no Cy t it nE ( tx et no C yt it n Et es d i ov c il b up

                           ;t xe t no c = t xe tn o c. si ht
                ;) (t s iL ya rr A w en = sd Ir e mo ts uc

                                                                                      { y rt
                                                              ; ) (n oi t ce nn oC e ka m
                            ;) (t x et no Cl a it in I w en = la it i ni t xe t no C
                                                                  = fe r jb o tc e jb O
                ;) "r e mo ts uC / bj e/ v ne /p mo c :a va j" ( pu ko o l. la it i ni

                                                                          = e m oH re mo t su c
                ,f er j bo (w or r an .t c ej bO et o me Re l ba tr oP ) em oH r em ot su C (
                                                            ; )s sa lc . em oH r em ot su C
                                                               { ) xe no it p ec xE ( h ct ac }
                        + " :t x et no C yt it nE t es "( n oi tp ec x EB JE we n wo r ht
                                                               ; )) (e g as se M te g. xe
                                                                                                }
            }

      Invoked by the              method,        da o Lb je      is a private method that
                                                      sd Ir e mo ts uC d ao l
      refreshes the                variable. There are two approaches when coding a
                                              s dI r em ot su c
      method such as                      : fetch the identifiers from the
                                     s d Ir em o ts uC da o l                         data- re mo t su c
      base table or get them from the
                       B JE r em ot su C                entity bean. Fetching the identifi-
      ers from the database might be faster, but exposes the code in the                     na eB p eR se l aS
      class to the                bean’s underlying database table. In the future, if you
                               BJ Er em o ts uC
      were to change the
                     BJ Er e mo ts uC     bean’s table (or move the bean to a different
      J2EE server), you might need to change the                          code. But if the
                                                                       n ae Bp eR s el aS
                      class gets the identifiers from the
      na e Bp eR se l aS                                                   entity bean, no
                                                                     B JE r em ot su C
      coding changes would be required. The two approaches present a trade-off: per-
      formance versus flexibility. The                  example opts for flexibility, load-
                                                                                          B JE pe R se la S
      ing the               variable by calling the
                     s dI re m ot su c         ye Ky r am ir P te g   andp e Rs el aS d ni f
      methods of                . Here is the code for the
                B JE r em ot su C                                               method:
                                                             sd I re mo ts u Cd ao l
                                                                      = re mo ts u c re m ot su C
                                           ; )( tx en . i) gn i rt S( = dI re mo t su c g ni rt S
                                                                       { ) )( tx e Ns ah . i( e li h w
                                                                               ; )( r ot ar e ti .a = i
                                              ; )( sd I re mo t su Ct eg . ec in aj = a t si Ly ar r A
                        ; )" 34 5" ( ye Ky r am ir Py B dn if . em oH se l as = e c in aj pe Rs el a S
                    y eK y ra mi r Py Bd ni f
          locates each                  entity bean by calling its              BJ Er e mo ts uC
                                                                                      method:
                                   t si Ly a rr A
                               method, iterates through the                                s dI re m ot su Ct e g
                                                                           of identifiers, and
                                     t ne i lC pe R se la S
          tin. To list all of Janice’s customers, the                   program invokes the
          The                 value 543 identifies a sales representative named Janice Mar-dI pe R se la s
                                                                  ; )" 34 5 "( dI pe R se la S te s. yr a m
                       ; ) "7 89 "( y eK yr a mi rP yB d ni f. e mo Hr em o ts uc = yr am re mo ts u C
          follows:
                program changes the                           dI pe R se la s
                                                   for a customer named Mary Jackson as                       tne
           il Cp e Rs el a S
          attributes of the business methods to Required.) For example, the
          ensure that                                                                da o Lb je
                                is invoked before each business method, set the transaction
          invokes           s dI re m ot su c
                                       , which refreshes the               s d Ir em o ts uC da o l
                                                                               variable. (To
                   da o Lb je
          time a business method of the               na e Bp eR s el aS
                                                         class is called, the         method
          base by calling thena eB r em ot su Cmethod of the      d Ip eR se l aS te s
                                                                              class. The next
          If a customer’s sales representative changes, the client program updates the data-
                                                                                                          }
                                                                                             }
                                                              ;) )( eg a ss eM te g .x e
          + " :s dI re m ot su C da ol n i n oi t pe cx E" ( no it p ec xE BJ E we n wo rh t
                                                             { ) x e no it p ec xE ( h ct ac }
                                                                                             }
                                                            ; ) di (d da . sd Ir em o ts uc
                     ;) ( ye Ky ra m ir Pt e g. re mo t su c) g ni rt S( = di g n ir tS
                              ; )( t xe n. i )r em ot s uC ( = r em ot s uc r em o ts uC
                                                                { )) (t x eN sa h. i ( el i hw
                                                            ;) ( ro ta re t i. c= i r ot ar e tI
           ;) dI p eR se l as (p eR s el aS y Bd ni f. e mo Hr e mo ts uc = c no i tc el l oC
                                                                                              { yr t
                                                                      ;) ( ra el c. s dI re m ot su c
                                                        { )( s dI re mo t su Cd ao l d io v e ta vi r p
MAPPING TABLE RELATIONSHIPS FOR BEAN-MANAGED PERSISTENCE109
110                                        BEAN-MANAGED PERSISTENCE EXAMPLES


                    ; ) dI re mo t su c( y eK yr am i rP yB d ni f. em o Hr em ot s uc
                              ;) ( em aN t eg .r em o ts uc = em an gn ir tS
           ;) e ma n + " : " + d Ir e mo ts uc ( nl tn i rp .t uo . me ts yS
                                                                                     }

      Running the SalesRepEJB Example
           1. Create the database tables.
              a. Go to the       cr s /s el pm a xe /l ai r ot ut e e2 j   directory.
              b. Type     e l ba t pe r se la s e ta er c t na        .
           2. Deploy the        ra e .p pA pe R se la S   file (located in the     m ax e /l ai r ot ut ee 2 j
                          directory).
               s ra e /s el p
           3. Run the client.
               a. Go to the                                directory.
                                 s ra e /s el pm a xe /l ai r ot ut e e2 j
               b. Set the          environment variable to
                            H TA P CP PA                                     r aj .t n ei lC pp A pe Rs e la S   .
               c. Type the following command on a single line:

                tn ei lc n ur     ra e. p pA pe Rs e la S tn e il c        t n ei lC pe R se la S e ma n
                ht ua tx e t

               d. At the login prompts, enter             t s eu g   for the user name and    32 1t se u g   for
                  the password.

      Many-to-Many Relationships
      In a many-to-many relationship, each entity may be related to multiple occur-
      rences of the other entity. For example, a college course has many students and
      each student may take several courses. In a database, this relationship is repre-
      sented by a cross reference table containing the foreign keys. In Figure 5–4, the
      cross reference table is the
               t ne m ll or ne                  table. These tables are accessed by the
                    ,
      n ae B re ll o rn E         , and                classes.
                               na eB e sr uo C n a eB tn ed u tS
                                               MAPPING TABLE RELATIONSHIPS FOR BEAN-MANAGED PERSISTENCE111




Figure 5–4 Many-to-Many Relationship: Students and Courses

The source code for this example is in the                                  ma xe / la ir o tu te e2 j
                            directory. To compile the code, go to the
                                              r el lo rn e /b je / cr s/ se l p
r e ll or n e tn a         directory and type           . A sample
                                              s el pm ax e /l ai r ot ut ee 2 j                   lo rn E
          file is in the j
      sr a e/ se lp m ax e/ l ai ro tu t ee 2       directory. r a e. pp Ar e l
The                and
        na eB t ne du t S           classes are complementary. Each class con-
                                na e Be sr u oC
tains an
      t si Ly a rr Aof foreign keys. The                 class, for example, con-
                                                        n ae B tn ed u tS
tains an
      t si Ly ar r Anamed              , which identifies the courses the student
                                           s dI e sr uo c
is enrolled in. Likewise, the              class contains an
                                      n a eB es ru o C                     named  ts i Ly ar rA
             .
s d It ne du t s
The
da oL b je   method of the               class adds elements to the
                                na eB tn e du tS                                     s dI es r uo c
           by calling
  t si Ly ar r A                     , a private method. The
                                   s dI e sr uo Cd a ol                              s dI es r uo Cd a ol
method gets the course identifiers from the                session bean. The
                                                              B JE re ll o rn E
source code for the               method follows:
                            sd Ie s ru oC da o l

      { ) (s dI es r uo Cd ao l d io v e ta vi r p

          ; )( ra el c .s dI e sr uo c

          { yr t
                              directory.   s el pm a xe /l ai r ot ut e e2 j
                                                              a. Go to the
                                                           1. Create the database tables.
                                                 Running the EnrollerEJB Example
belong to the same transaction. See Chapter 14 for more information.
class. To ensure that both deletes are executed as a single operation, they should
na eB t ne du t S                    e v om eR bj e
table. That action is performed by the               method of the
tn ed u ts
The                  class does not delete the matching row from the           n ae B re ll or n E
                                                                         ? = t ne d ut s er e hw
                                                                 t ne ml l or ne m o rf e te l ed
                                                      in the table for that student:
method deletes all rows        t ne d ut Se te l ed   And if a student leaves the school, the
                                        ? = d ie s ru oc d n a ? = d it ne d ut s er e hw
                                                           t ne ml l or ne m o rf e te l ed
                     method deletes a row:        l lo rn E nu   If a student drops a course, the
                                                      )d ie sr u oc , d it ne du t s( s eu l av
                                                               t ne ml l or ne o t ni t re s ni
business method, which inserts a row:                                                     l lo rn e  the
 table. If a student enrolls in a course, for example, the client calls                 t ne ml lo r ne
    class manages the student-course relationship represented in the                na e Br el lo r nE
                            tn e ml lo r ne
                class accesses the               table. Therefore, the  na e Br el lo r nE  Only the
                                                                   ? = d it ne d ut s er e hw
                                                 tn e ml lo rn e m or f d ie sr u oc t ce l es
                                                      t ne ml lo r ne
                                                    table:                                   na eB r el
                                                                               class queries the
 l or n E   method of the    se sr uo C te g   method, the    sd I es ru oC d ao l
                                                                       Invoked by the
                                                                                                 }
                                                                                  }
                                                  ; )) (e g as se M te g. xe
+ " : sd Ie s ru oC da o l ni no it pe c xE "( n oi tp ec x EB JE we n wo r ht
                                                  { ) xe n oi t pe cx E ( hc ta c }
                                                         ;) a( l lA dd a .s dI es r uo c
              ; )d It ne d ut s( s dI es ru o Ct eg . re ll or n e = a t si Ly a rr A
                      ;) ( et ae r c. em oH r el lo r ne = r e ll or n e re ll o rn E
                         BEAN-MANAGED PERSISTENCE EXAMPLES                                                 112
                                                  PRIMARY KEYS FOR BEAN-MANAGED PERSISTENCE                           113


             b. Type   el ba t r el l or ne e t ae rc t n a         .
       2. Deploy the          r ae . pp Ar el l or nE   file (located in the        ma xe / la ir o tu te e2 j
                      directory).
             sr ae / se lp
       3. Run the client.
             a. Go to the                                directory.
                               sr ae /s e lp ma x e/ la ir o tu te e 2j
             b. Set the          environment variable to
                         HT AP C PP A                                         r a j. tn e il Cp pA r el lo r nE   .
             c. Type the following command on a single line:

             t ne il cn u r     r ae .p p Ar el lo r nE t ne i lc        tn e il Cr el l or nE em an
             h tu at xe t

             d. At the login prompts, enter             ts e ug   for the user name and        3 21 ts eu g   for
                the password.


Primary Keys for Bean-Managed
Persistence
  You specify the primary key class in the entity bean’s deployment descriptor. In
  most cases, your primary key class will be a         , an         , or some other
                                                                  g ni rt S       re ge t nI
  class that belongs to the J2SE or J2EE standard libraries. For some entity beans,
  you will need to define your own primary key class. For example, if the bean has
  a composite primary key (that is, one composed of multiple fields), then you
  must create a primary key class.

  The Primary Key Class
  The following primary key class is a composite key—the                             dI tc ud o rp   and   ne v
        fields together uniquely identify an entity bean.
  d Ir o d

       { e lb az il a ir eS . oi .a va j s tn e me lp mi ye Km et I s sa l c ci lb u p

             ;d It cu d or p gn i rt S c il bu p
              ; dI ro d ne v gn i rt S c il bu p

             ; } { ) (y eK m et I c il bu p

             { ) dI ro dn e v gn i rt S ,d I tc ud o rp g ni r tS (y eK m et I c il bu p

                ;d It c ud or p = d It cu d or p. s ih t
                   ;d I ro dn ev = dI ro d ne v. s ih t
eters to instance variables and then returns the primary key class:
With bean-managed persistence, the           et a er Cb j e
                                                  method assigns the input param-
                                 Primary Keys in the Entity Bean Class
                                            • The class is serializable.
                                              ods.
meth-   ) re ht o t ce jb O( s la uq e          ) ( ed oC hs a h
                                              The class implements the               and            •
                                              The class has a public default constructor.           •
                                                      c i lb up
                                              All fields are declared as       .                    •
                            .   c i lb up     The access control modifier of the class is           •
ments:
For bean-managed persistence, a primary key class must meet these require-
                                                                                                    }
                                                                                                }
                 ; )( ed o Ch sa h .) dI ro d ne v( t ac no c. d It cu d or p nr u te r
                                                              { )( e do Ch s ah t ni ci lb up
                                                                                                }
                                                                    ;e s la f nr u te r
                                                                                      }
;) ) dI ro dn e v. )r eh t o) ye K me tI (( ( sl au q e. dI ro d ne v & &
 ) d It cu do r p. )r eh t o) ye K me tI (( ( sl au q e. dI tc u do rp ( n ru te r
                                       { ) y eK me t I fo ec n at sn i r eh to ( f i
                                    { )r eh t o tc e jb O( sl a uq e n ae lo ob ci lb up
                                                                                                }
                                                                    ; dI ro d ne v nr u te r
                                                  { ) ( dI ro dn e Vt eg gn ir tS ci lb up
                                                                                                }
                                                                   ; d It cu d or p nr u te r
                                                { )( d It cu do r Pt eg gn ir tS ci lb up
                                                                                                }
                         BEAN-MANAGED PERSISTENCE EXAMPLES                                              114
                             method of the             class:    tc e jb OB J E                    y eK y r
       am ir P te g   A client can fetch the primary key of an entity bean by invoking the
                                                            Getting the Primary Key
                                                                                                    }
                                                                          ; tl u se r n ru te r
                                                                      ;) (e so l c. tm t Sp er p
                                                      ;) ( tx en .s r = t lu s er n a el oo b
                                   ;) ( yr eu Qe t uc ex e .t mt Sp e rp = s r t eS t lu se R
                     ;) )( dI r od ne V te g. ye K yr am i rp , 2( g ni rt St e s. tm t Sp er p
                   ; )) (d It c ud or P te g. ye K yr am i rp , 1( g ni rt St e s. tm t Sp er p
                           ;) t ne me t at St ce l es (t n em et at S er ap er p .n oc
                                                    = t m tS pe rp tn em et a tS de r ap er P
           ; " ? = d ir od ne v d na ? = di t cu do r p er eh w m et i m or f"
                                                      + " d it cu d or p tc e le s"
                                                           = tn em e ta tS tc e le s g ni rt S
                                                               { n o it pe cx E LQ S s wo rh t
                 )y e Ky ra mi r p ye K me tI (y e Ky ra m ir Py Bt c el es n a el oo b e ta vi r p
                                                                                                    }
                                                                                           .. .
                                                            ;y eK yr a mi rp n r ut er
                                     ) ) ye Ky ra m ir p( y eK yr am i rP yB tc e le s( fi
                                                                                        { yr t
                                                           { no it p ec xE re d ni F s wo rh t
                 )y e Ky ra mi r p ye K me tI (y e Ky ra m ir Py Bd n iF bj e y eK me t I ci lb u p
                                                                                  given primary key:
      verifies the existence of the database row for the              y eK yr a mi rP yB d ni Fb j e
                                                                                  The
                                                                                                    }
                                  ; )d I ro dn ev ,d It c ud or p( y eK me tI we n n ru te r
                                                ; n oi tp i rc se d = n oi tp i rc se d .s ih t
                                                          ; dI ro dn e v = dI r od ne v .s ih t
                                                       ;d I tc ud or p = d It c ud or p .s ih t
                                                                                         }
        ; )" . de ri u qe r er a d Ir o dn ev d n a dI t cu do rp eh T"
                                                  (n oi t pe cx Ee t ae rC w e n wo r ht
                            { ) ll un == d Ir o dn ev || l lu n = = dI t cu do r p( f i
                            { n oi tp e cx Ee ta e rC s w or ht ) n oi tp ir c se d g ni rt S
          ,d I ro dn e v gn ir t S ,d I tc ud or p g ni r tS (e ta e rC bj e y eK me t I ci lb u p
115           PRIMARY KEYS FOR BEAN-MANAGED PERSISTENCE
116                                        BEAN-MANAGED PERSISTENCE EXAMPLES


                                              ; t nu oc c a tn uo c cA sg ni v aS
                                                                             . ..
             ; )( y eK yr am i rP te g .t nu oc c a) gn i rt S( = di g ni r tS

        The entity bean retrieves its own primary key by calling the                     ye Ky r am ir P te g
        method of the                  class:
                          tx et no C yt it nE

                                                 ; tx et n oc t xe t no Cy ti t nE
                                                                              . ..
             ;) (y e Ky ra mi r Pt eg . tx et no c ) gn i rt S( = di g ni r tS


      Handling Exceptions
        The exceptions thrown by enterprise beans fall into two categories: system and
        application.
        A system exception indicates a problem with the services that support an applica-
        tion. Examples of these problems include the following: a database connection
        cannot be obtained, a SQL insert fails because the database is full, or a                   pu ko o l
        method cannot find the desired object. If your enterprise bean encounters a sys-
        tem-level problem, it should throw a
                                      n oi tp e cx EB J E. bj e. x av aj   . The container
        will wrap the                  in a                   , which it passes back to the
                                                      n oi tp ec x Ee to m eR       n o it pe cx E BJ E
        client. Because the                 is a subclass of the
                         n oi t pe cx Ee m it nu R                                    , you
                                                                             n oi tp e cx EB J E
        do not have to specify it in the        clause of the method declaration. If a sys-
                                                                        s w or ht
        tem exception is thrown, the EJB container might destroy the bean instance.
        Therefore, a system exception cannot be handled by the bean’s client program; it
        requires intervention by a system administrator.
        An application exception signals an error in the business logic of an enterprise
        bean. There are two types of application exceptions: customized and predefined.
        A customized exception is one that you’ve coded yourself, such as the                    i f fu sn I
                                   thrown by the
        n oi t pe cx Ee c na la Bt n ec         t ib ed   business method of the                 v aS
                          example. The
                  BJ Et n uo cc As g ni             package includes several predefined
                                                      b je .x a va j
        exceptions that are designed to handle common problems. For example, an                           b je
        e ta e rCmethod should throw a                       to indicate an invalid input
                                                 n o it pe cx E et ae r C
        parameter. When an enterprise bean throws an application exception, the con-
        tainer does not wrap it in another exception. The client should be able to handle
        any application exception it receives.
        If a system exception occurs within a transaction, the EJB container rolls back
        the transaction. However, if an application exception is thrown within a transac-
        tion, the container does not roll back the transaction.
                                          HANDLING EXCEPTIONS                                      117


Table 5–2 summarizes the exceptions of the                          package. All of these
                                                                                   bj e. x av aj
exceptions are application exceptions, except for then oi tp e cx Ey t it nE hc u So N
and the               , which are system exceptions.
         n oi t pe cx E BJ E


Table 5–2 Exceptions

 Method Name                   Exception It Throws                 Reason for Throwing

                                                                   An input parameter is
 etaerCbje                     noitpecxEetaerC
                                                                   invalid.

  yeKyramirPyBdniFbje                                              The database row for the
                                  noitpecxEdnuoFtoNtcejbO
   and other finder methods
                    (                                              requested entity bean
                                subclass of
                               )noitpecxEredniF         (
 that return a single object
 )                                                                 cannot be found.

                                                                   The entity bean’s row
 evomeRbje                     noitpecxEevomeR                     cannot be deleted from
                                                                   the database.

                                                                   The database row to be
 daoLbje                       noitpecxEytitnEhcuSoN
                                                                   loaded cannot be found.

                                                                   The database row to be
 erotSbje                      noitpecxEytitnEhcuSoN
                                                                   updated cannot be found.

                                                                   A system problem has
 (all methods   )              noitpecxEBJE
                                                                   been encountered.
118   BEAN-MANAGED PERSISTENCE EXAMPLES
                   6
 Container-Managed
Persistence Examples
                                                                     Dale Green



 A   N entity bean with container-managed persistence offers important advan-
 tages to the bean developer. First, the EJB™ container handles all database stor-
 age and retrieval calls. Second, the container manages the relationships between
 the entity beans. Because of these services, you don’t have to code the database
 access calls in the entity bean. Instead, you specify settings in the bean’s deploy-
 ment descriptor. Not only does this approach save you time, but it makes the
 bean portable across various database servers.
 This chapter focuses on the source code and deployment settings for an example
 called            , an application that features entity beans with container-man-
        p pA re t so R
 aged persistence. If you are unfamiliar with the terms and concepts mentioned in
 this    chapter,     please    consult     the     section    Container-Managed
 Persistence, page (53).

 In This Chapter
            Overview of the RosterApp Application 120
            The PlayerEJB Code 121
                Entity Bean Class 122
                Local Home Interface 126
                Local Interface 128



                                                                                        119
120                                        CONTAINER-MANAGED PERSISTENCE EXAMPLES


                     A Guided Tour of the RosterApp Settings 128
                         RosterApp 128
                         RosterClient 130
                         RosterJAR 130
                         TeamJAR 131
                     Method Invocations in RosterApp 136
                         Creating a Player 137
                         Adding a Player To a Team 138
                         Removing a Player 139
                         Dropping a Player From a Team 140
                         Getting the Players Of a Team 141
                         Getting a Copy of a Team’s Players 142
                         Finding the Players By Position 144
                         Getting the Sports of a Player 145
                     Running the RosterApp Example 147
                         Setting Up 147
                         Deploying the Application 147
                         Running the Client 147
                     Deploytool Tips for Entity Beans With Container-Managed Persistence 148
                         Specifying the Bean’s Type 148
                         Selecting the Persistent Fields and Abstract Schema Name 148
                         Defining EJB QL Queries for Finder and Select Methods 149
                         Generating SQL and Specifying Table Creation 149
                         Specifying the Database JNDI Name, User Name, and Password 150
                         Defining Relationships 150
                     Primary Keys for Container-Managed Persistence 150
                         The Primary Key Class 151
                         Primary Keys in the Entity Bean Class 152
                         Generating Primary Key Values 153


      Overview of the RosterApp Application
        The             application maintains the team rosters for players in sports
             p pA r et so R
        leagues. The application has five components. The                       compo-
                                                                           tn ei l Cp pA r et so R
        nent is a J2EE™ application client that accesses the               session bean
                                                                                 B JE r et so R
        through the bean’s remote interfaces.           accesses three entity beans—
                                                          B J Er et s oR
                   ,        , and
        BJ Em a eT BJ Er ey a lP             —through their local interfaces.
                                         B JE eu ga e L
        The entity beans use container-managed persistence and relationships. The
        BJ Em a eTand               entity beans have a bidirectional, many-to-many rela-
                        B JE re y al P
        tionship. In a bidirectional relationship, each bean has a relationship field whose
        value identifies the related bean instance. The multiplicity of the             y al P B JE m ae T
                                                 THE PLAYEREJB CODE                                     121


  B JE r erelationship is many-to-many: Players who participate in more than one
  sport belong to multiple teams, and each team has multiple players. The
  B JE eu ga e Land          entity beans also have a bidirectional relationship, but
                        BJ Em ae T
  the multiplicity is one-to-many: A league has many teams, but a team can belong
  to just one league.
  Figure 6–1 shows the components and relationships of the              applica-
                                                                             pp Ar e ts oR
  tion. The dotted lines represent the access gained through invocations of the
  JNDI          method. The solid lines represent the container-managed relation-
         pu ko o l
  ships.




  Figure 6–1 RosterApp J2EE™ Application



The PlayerEJB Code
  The            entity bean represents a player in a sports league. Like any entity
       B JE re y al P
  bean with container-managed persistence,               needs the following code:
                                                           BJ Er e ya lP
       • Entity bean class (         n ae Br e ya lP   )
       • Local home interface (           e m oH re y al Pl ac o L   )
       • Local interface (      r ey al Pl a co L   )
  The source code for this example is in the                               ma xe / la ir o tu te e2 j
                        directory. To compile the code, go to the
  r e ts or pm c /b je / cr s/ se l p
122                                       CONTAINER-MANAGED PERSISTENCE EXAMPLES



      r et s or pm c tn a              directory and type                        . A sample
                                                   se lp m ax e/ la i ro tu te e 2j              r et s oR
                 file is in the j
                s ra e/ s el pm a xe /l ai r ot ut e e2                    directory.
                                                                         ra e. p pA


      Entity Bean Class
      For container-managed persistence, the code of the entity bean class must meet
      the syntax requirements. First, the class must be defined as               and       c il bu p
               . Also, the class must implement the following:
      t ca rt s ba
           • The               interface
                     n ae By t it nE
           • Zero or more              and
                                e ta e rC bj e            methods
                                                    et ae r Ct so P bj e
           • The      and
                     teg       access methods, defined as
                               tes                                , for the persistent
                                                                        t ca r ts ba
             and relationship fields
           • Any select methods, defining them as               t ca r ts ba
           • The home methods
           • The business methods
      The entity bean class must not implement these methods:
           • The finder methods
           • The           method
                     e zi l an if

      Differences between Container-Managed and Bean-
      Managed Code
      Because it contains no calls to access the database, an entity bean with container-
      managed persistence requires a lot less code than one with bean-managed persis-
      tence. For example, the                      source file discussed in this chapter is
                                                     av aj . na eB re y al P
      much smaller than the                                        code documented in
                                    av a j. na eB t nu oc c As gn iv a S
      Chapter 5. Table 6–1 compares the code of the two types of entity beans.


      Table 6–1 Coding Differences between Persistent Types

       Difference                      Container-Managed                   Bean-Managed

       Class definition                Abstract                            Not abstract

       Database access calls           Generated by tools                  Coded by developers

                                       Represented by virtual              Coded as instance
       Persistent state
                                       persistent fields                   variables
                                       THE PLAYEREJB CODE                             123


Table 6–1 Coding Differences between Persistent Types (Continued)

 Difference                 Container-Managed               Bean-Managed

 Access methods for per-
 sistent and relationship   Required                        None
 fields

 yeKyramirPyBdnif
                            Handled by container            Coded by developers
 method

                            Handled by container, but the
 Customized finder meth-
                            developer must define the EJB   Coded by developers
 ods
                            QL queries

 Select methods             Handled by container            None

 Return value of
                            Should be null                  Must be the primary key
 etaerCbje



Note that for both types of persistence, the rules for implementing business and
home methods are the same. See the sections The Business Methods, page (91)
and The Home Methods, page (92) in Chapter 5 .

Access Methods
An entity bean with container-managed persistence has persistent and relation-
ship fields. These fields are virtual, so you do not code them in the class as
instance variables. Instead, you specify them in the bean’s deployment descrip-
tor. To permit access to the fields, you define abstract    and
                                                              teg   methods in
                                                                          te s
the entity bean class.

Access Methods for Persistent Fields
The EJB container automatically performs the database storage and retrieval of
the bean’s persistent fields. The deployment descriptor of           specifies
                                                                    B JE re y al P
the following persistent fields:
    •
    d Ir e ya lp     (primary key)
           em an •
    n oi t is op •
       y r al as •
124                                        CONTAINER-MANAGED PERSISTENCE EXAMPLES



      The  n ae B re ya l P   class defines the access methods for the persistent fields as fol-
      lows:

                    ; )( d Ir ey a lP te g g ni rt S t ca rt s ba c il b up
          ; )d i g ni rt S (d Ir e ya lP te s d io v t ca rt s ba c il b up

                        ;) (e m aN te g g ni rt S t ca rt s ba c il b up
          ; ) em an g n ir tS ( em aN te s d io v t ca rt s ba c il b up

                             ; )( n oi ti s oP te g g ni rt S t ca rt s ba c il b up
          ;) no i ti so p g ni rt S (n oi t is oP te s d io v t ca rt s ba c il b up

                          ; ) (y ra l aS te g e lb uo d t ca rt s ba c il b up
          ; )y ra l as e lb u od (y r al aS te s d io v t ca rt s ba c il b up

      The name of an access method begins with           or    , followed by the capital-
                                                             te g     te s
      ized name of the persistent or relationship field. For example, the accessor meth-
      ods for the  yr al a sfield are          and
                                          y ra la St e g       . This naming convention
                                                             y ra la S te s
      is similar to that of JavaBeans™ components.

      Access Methods for Relationship Fields
      In the
      p pA re ts o R        application, since a player can belong to multiple teams, a
                   instance may be related to many
               BJ Er ey a lP                                    instances. To specify this
                                                           B JE m ae T
      relationship, the deployment descriptor of               defines a relationship field
                                                            B JE re y al P
      named          . In the
              s m ae t                      class, the access methods for the
                                  n a eB re y al P                                    rela-
                                                                                       s ma et
      tionship field are as follows:

                        ;) (s m ae Tt e g no it c el lo C t ca rt s ba c il b up
          ;) s ma et no it ce l lo C( s ma eT te s d io v t ca rt s ba c il b up

      Select Methods
      A select method is similar to a finder method in the following ways:
          • A select method queries a database and returns objects.
          • The deployment descriptor specifies an EJB QL query for a select method.
          • The entity bean class does not implement the select method.
                                             THE PLAYEREJB CODE                                        125


However, a select method differs significantly from a finder method:
      • A select method can return persistent fields or the home interfaces of
        related entity beans. A finder method can return only the home interface
        (or a collection thereof) that defines it.
      • Since it is not exposed in any of the local or remote interfaces, a select
        method cannot be invoked by a client. It can be invoked only by the meth-
        ods implemented within the entity bean class. A select method is usually
        invoked by a business method.
      • A select method is defined in the entity bean class. For bean-managed per-
        sistence, a finder method is defined in the entity bean class, but for con-
        tainer-managed persistence it is not.
The   na e Br ey al P   class defines these select methods:

      r ey a lP la co L (s eu g ae Lt ce l eS bj e n oi tc e ll oC t c ar ts b a ci lb u p
                                                                                ) re ya l p
                                                  ;n oi tp e cx Er ed n iF s w or ht

      ) re ya l p re y al Pl ac o L( st r op St ce l eS bj e n oi tc e ll oC t c ar ts b a ci lb u p
                                                            ;n oi tp e cx Er ed n iF s w or ht

The signature for a select method must follow these rules:
      •   The prefix of the method name must be             tc e le Sb je   .
      •   The access control modifier must be           c il bu p     .
      •   The method must be declared as           tc ar t sb a   .
      •   The         clause must include the
               sw o rh t                               no i tp ec xE r ed ni F .b je .x a va j   .

Business Methods
Since clients cannot invoke select methods, the             na eB re y al P     class wraps them in
the              and
   s eu ga e Lt eg               business methods:
                           st r op St eg

      { n o it pe cx E re dn i F sw or h t )( s eu ga eL t eg n oi t ce ll o C ci lb u p

                                                             = re y al p re y al Pl a co L
             ; )( t ce jb Ol a co LB J Et eg .t x et no c )r ey al P la co L. m ae t(
                                          ;) re y al p( s eu ga eL t ce le Sb j e nr u te r
      }

      { n oi tp ec x Er ed n iF s wo r ht ) ( st ro pS t eg n oi t ce ll o C ci lb u p
126                                      CONTAINER-MANAGED PERSISTENCE EXAMPLES


                                                                 = r e ya lp re ya lP l ac oL
                  ;) ( tc ej bO l ac oL B JE te g. t xe tn o c) re ya l Pl ac o L. ma et (
                                                ;) r ey al p (s tr op S tc el e Sb je n r ut er
           }

      Entity Bean Methods
      Because the container handles persistence, the life-cycle methods in the                    r e ya lP
          class are nearly empty.
      n a eB
      The  et ae r Cb jemethod initializes the bean instance by assigning the input argu-
      ments to the persistent fields. After the              method completes, the con-
                                                          e ta er Cb j e
      tainer inserts a row into the database. Here is the source code for the                 et ae r Cb je
      method:

                             ,e m an g n ir tS , d i gn i rt S( e t ae rC b je g ni r tS c il b up
           { n oi tp e cx Ee ta e rC s w or ht ) y ra la s e lb uo d , no i ti so p g ni rt S

                         ; )d i (d Ir ey a lP te s
                            ; ) em an (e m aN te s
                ;) no i ti so p (n oi ti s oP te s
                      ; )y ra l as (y ra l aS te s
                                ;l lu n n ru te r
           }

      Except for a debug statement, the   e vo me Rb j e       method in the                 class is
                                                                                   n ae Br ey a lP
      empty. The container invokes                         right before it deletes the database row.
                                               ev om e Rb je
      The                     method must have the same input parameters and return
            e t ae rC ts o Pb je
      type as the
           et ae rC b je       method. If you want to set a relationship field to initialize
      the bean instance, you should do so in the                    method. You may not
                                                            et a er Ct so P bj e
      set a relationship field in the          method.
                                         e ta er C bj e
      The container automatically synchronizes the state of the entity bean with the
      database. After the container loads the bean’s state from the database, it invokes
      the          method. In like manner, before storing the state in the database, the
          da oL b je
      container invokes the            method.
                                e ro tS b je


      Local Home Interface
      The local home interface defines the           et a er c   , finder, and home methods that may
      be invoked by local clients.
                                                                                                   }
                                                                                         . ..
                                                     ; no i tp ec xE r ed ni F s wo rh t
                  )e u ga el e u ga eL l ac oL (e u ga eL y Bd ni f n oi tc el l oC c i lb up
                                                                                     . . .
                                                     ; no i tp ec xE r ed ni F s wo rh t
                   ) n oi ti so p g ni r tS (n oi t is oP y Bd ni f n oi tc el l oC c i lb up
                                                   ; no i tp ec xE r ed ni F s wo rh t
                       )d i gn i rt S( ye Ky ra m ir Py B dn if r e ya lP la c oL c i lb up
                                                   ; no i tp ec xE e ta er C s wo rh t
                                        )y ra la s e lb u od , no i ti so p g ni rt S
                  ,e m an g ni r tS , d i gn ir t S( e t ae rc r e ya lP la c oL c i lb up
                { e m oH la co L BJ E s dn et xe em oH r ey al Pl a co L ec a fr et n i ci lb u p
                                                                          ; *. bj e .x av a j tr op m i
                                                                          ; *. li t u. av a j tr op m i
                                                                                     ;m ae t e ga kc a p
                                      interface follows.     e mo Hr ey a lP la c oL    An excerpt of the
      • The                      method must be defined.           y eK yr am i rP yB d ni f
      • The        no it pe c xE re d ni F. bj e .x av aj
                     clause contains the                                  .           sw o rh t
        those types.
      • The return type is the entity bean’s local interface type, or a collection of
      • The name begins with         .                         dn if
                                                            These rules apply for a finder method:
                   no it pe c xE et a er C. bj e .x av aj
                  • The           clause contains the                             .   sw o rh t
                    of the corresponding                e t ae rC bj e
                                                        method.
      clause   sw or ht
                  • The           clause includes the exceptions specified by the     s wo r ht
                  • It returns the local interface type of the entity bean.
                    method in the entity bean class.
      e ta er C bj e
                  • It has the same number and types of arguments as its matching
                  • The name begins with             .      e t ae rc
                                                 method follow:         e ta er c   The syntax rules for a
127                                     THE PLAYEREJB CODE
128                                           CONTAINER-MANAGED PERSISTENCE EXAMPLES



        Local Interface
        This interface defines the business and access methods that a local client may
        invoke. The
               n ae B re ya l P     class implements two business methods:                    se ug a eL te g
        and             . It also defines several
                            s tr op S te g           and      access methods for the per-
                                                             teg        te s
        sistent and relationship fields. The      methods are hidden from the bean’s cli-
                                                      te s
        ents because they are not defined in the                  interface. However, the
                                                               r ey al P la co L
        t eg methods are exposed to the clients by the interface:

               ; ma e t eg ak c ap

               ;* . li tu .a v aj t ro p mi
               ;* . bj e. xa v aj t ro p mi

               { t ce jb O la co L BJ E sd n et xe re ya lP l ac oL ec af re t ni c il b up

                     c il bu p    ; )( d Ir ey al P te g g ni rt S
                     c il bu p           ;) (e ma N te g g ni rt S
                     c il bu p    ; )( n oi ti so P te g g ni rt S
                     c il bu p       ; ) (y ra la S te g e lb uo d
                     c il bu p   ;) (s m ae Tt eg no it c el lo C

                     ; no it p ec xE re d ni F s wo rh t ) (s eu g ae Lt eg no it c el lo C c il bu p
                       ;n oi t pe cx Er e dn iF sw or ht )( st r op St eg no it c el lo C c il bu p
               }


      A Guided Tour of the RosterApp Settings
        This section introduces you to the settings of the deployment descriptors for
        entity beans with container-managed persistence and relationships. As this tour
        guides you through the              screens, it discusses the highlights of the
                                         l oo t yo lp ed
        tabs and dialog boxes that appear.
        To begin our tour, please run
                                 l oo ty o lp ed                     and open the   ra e. p pA re ts o R   file,
        which is in the      s ra e/ se l pm ax e/ l ai ro t ut ee 2j  directory.

        RosterApp
        To view the deployment settings for the application, select the                  p p Ar et so R    node
        in the tree view.
                                    A GUIDED TOUR OF THE ROSTERAPP SETTINGS                   129


General Tab (RosterApp)
The Contents field displays the files contained in the
                                  r ae . pp Ar e ts oR                             file,
including the two EJB JAR files (                ,                            ) and the
                                        r aj .b j e re ts o r r aj .b j e ma e t
J2EE application client JAR file (            ). See Figure 6–2. r aj .c a r et so r




Figure 6–2 General Tab of RosterApp

JNDI Names Tab (RosterApp)
The Application table lists the JNDI names for the enterprise beans in the             so R
      application.
pp Ar e t
The References table has two entries. The EJB Ref entry maps the coded name
(                    ) in the
 re ts o Re lp mi S /b je                    to the JNDI name of the
                            tn e il Cr et s oR                              B JE re t so R
session bean. The Resource entry specifies the JNDI name for the database that
is accessed by the entity beans contained in the         module.
                                                  RA Jm a eT
130                                      CONTAINER-MANAGED PERSISTENCE EXAMPLES



      RosterClient
      To view this client, expand the     pp Ar e ts oR    node by clicking its adjacent key icon
      in the tree view. Next, select     tn e il Cr e ts oR .

      JAR File Tab (RosterClient)
      The Contents field shows the files contained by the                                               file: two
                                                                                       r aj .c a r et s or
      XML files (the deployment descriptors) and a single class file (      i lC r et so R
               ).
      ss al c. t ne

      EJB Refs Tab (RosterClient)
      The                 accesses a single bean, the
           tn e il Cr et s oR                                      session bean. Because
                                                                  B JE re ts o R
      this access is remote, the value in the Interfaces column is Remote and the value
      for the Local/Remote Interface column is the bean’s remote interface (                               s or
                   ).
      r et so R. r et


      RosterJAR
      In the tree view, select   RA J re ts oR   . This JAR file contains the         BJ Er e ts oR      session
      bean.

      General Tab (RosterJAR)
      The Contents field lists three packages of class files. The            package con-
                                                                                   r et s or
      tains the class files required for               —the session bean class, remote
                                                 BJ E re ts oR
      interface, and home interface. The          package includes the local interfaces for
                                                         m ae t
      the entity beans accessed by the                  session bean. The
                                                 B JE re t so R                    package     l it u
      holds the utility classes for this application.

      RosterEJB
      In the tree view, expand the      RA Jr e ts oR   node and select      B JE r et so R    .

      General Tab (RosterEJB)
      This tab shows that              is a stateful session bean with remote access.
                                B JE re t so R
      Because it allows no local access, the Local Interfaces fields are empty.

      EJB Refs Tab (RosterEJB)
      The            session bean accesses three entity beans:
           B JE re ts o R                                                  ,         ,
                                                                                   B JE m ae T B JE re y al P
      and           . Because this access is local, the entries in the Interfaces col-
           B JE e ug ae L
      umns are defined as Local. The Home Interface column lists the local home
                                              A GUIDED TOUR OF THE ROSTERAPP SETTINGS                   131


interfaces of the entity beans. The Local/Remote Interfaces column displays the
local interfaces of the entity beans.
To view the runtime deployment settings, select a row in the table. For example,
when you select the row with the Coded Name of                              , the
                                                                    eu ga e Le lp mi S /b je
            name appears in the Enterprise Bean Name field. If a component ref-
B JE eu ga e L
erences a local entity bean, then you must enter the name of the referenced bean
in the Enterprise Bean Name field.

TeamJAR
In the tree view, select the
                 R A Jm ae T                node. This JAR file contains the three related
entity beans:              ,              , and
                  BJ E ma eT BJ E eu ga e L               .
                                                  B JE r ey al P

General Tab (TeamJAR)
The Contents field shows two packages of class files:        and     . The
                                                                   m ae t     l it u           m ae t
package has the entity bean classes, local interfaces, and local home interfaces
for all three entity beans. The    package contains utility classes.
                                     l i tu

Relationships Tab (TeamJAR)
On this tab (Figure 6–3) you define the relationships between entity beans with
container-managed persistence.
132                                  CONTAINER-MANAGED PERSISTENCE EXAMPLES




      Figure 6–3 Relationships Tab of TeamJAR

      The Container Managed Relationships table summarizes two relationships:
                             and
      B JE re ya l P BJ Em a eT                     . In the
                                        B JE re ya l P BJ Em a eT              rela-
                                                                            B JE m ae T B JE eu ga e L
      tionship,
         B JE m ae T     is designated as EJB A and           as EJB B. (This desig-
                                                              B J Er ey al P
      nation is arbitrary—we could have assigned
                                  BJ Em a eT                 to EJB A and
                                                               B J Er ey al P
      to EJB B.)

      Edit Relationship Dialog Box (TeamJAR)
      To view the Edit Relationship dialog box (Figure 6–4), on the Relationships tab
      select a row and click Edit. For example, to view the                     rela-
                                                                  BJ E re ya lP BJ Em a eT
      tionship, select the row in which the EJB A value is    and then click Edit.     ma eT
                                            A GUIDED TOUR OF THE ROSTERAPP SETTINGS        133




Figure 6–4 Edit Relationship Dialog Box of        RA Jm a eT

TeamEJB-PlayerEJB Relationship
The Multiplicity combo box offers four choices. For this relationship, the Many
To Many choice should be selected because a team has many players and a
player can belong to more than one team.
The information in the Enterprise Bean A box defines           side of the rela-
                                                                  B JE m ae T
tionship. The Field Referencing Bean B combo box displays the relationship
field (        ) in
         B JE ma e T       . This field corresponds to the relationship access
                           s r ey al p
methods in the
      av aj . na eB ma e T     source code:

                      ; )( sr ey a lP te g n oi tc e ll oC t c ar ts b a ci lb u p
    ; )s re ya l p no i tc el lo C (s re y al Pt es di ov t c ar ts b a ci lb u p

The selection of the Field Type combo box is                            , which
                                                     no i tc el lo C .l it u .a va j
matches the           type in the access methods. The
                     sr ey al p                                 type is a multi-
                                                                s re ya l p
valued object (            ) because on the
              no it c el lo C                       side of the relationship the
                                                                              BJ E ma eT
multiplicity is many.
The B JE re ya l P BJ E ma eTrelationship is bidirectional—each bean has a relation-
ship field that identifies the related bean. If this relationship were unidirectional,
then one of the beans would not have a relationship field identifying the other
bean. For the bean without the relationship field, the value of the Field Referenc-
ing combo box would be              .
                                > en on <
134                                        CONTAINER-MANAGED PERSISTENCE EXAMPLES



      LeagueEJB-TeamEJB Relationship
      In the Edit Relationship dialog box, the Multiplicity choice should be One to
      Many. This choice indicates that a single league has multiple teams.
      ForB JE eu ga e L  , the relationship field is         and for
                                                            sm ae t            it is          .
                                                                                        BJ E ma eT   e ug a el
      Because
      B JE m ae T           is on the multiple side of the relationship, the         field is a
                                                                                  s ma e t
                     . In contrast, since
             n oi tc el l oC                           is on the single side of the relation-
                                                B JE e ug ae L
      ship, the
      e u ga el              field is a single-valued object, a                . The
                                                                          eu ga eL l ac oL             m ae T
                    code defines the league relationship field with these access methods:
               av aj .n a eB

                             ;) (e ug a eL te g e ug ae L la co L t ca rt s ba c il b up
           ;) sr ey a lp e u ga eL la c oL (e u ga eL te s d io v t ca rt s ba c il b up

      For  BJ E ma eT(Enterprise Bean B), the Delete When Bean A Is Deleted checkbox
      is selected. Because of this selection, when a               instance is deleted the
                                                                 BJ E eu ga e L
      related  BJ E ma eTinstances are automatically deleted. This type of deletion, in
      which one deletion triggers another, is called a cascade delete. For               ,     B JE e ug ae L
      the corresponding checkbox is disabled: If you delete a team, you don’t want to
      automatically delete the league, because there may be other teams in that league.
      In general, if a bean is on the multiple side of a relationship, the other bean can-
      not be automatically deleted.

      PlayerEJB
      In the tree view, expand the        R AJ ma e T   node and select the   BJ Er e ya lP    entity bean.

      General Tab (PlayerEJB)
      This tab shows the enterprise bean class and interfaces. Since the                        BJ Er e ya lP
      entity bean uses container-managed persistence, it has local interfaces. It does
      not have remote interfaces because it does not allow remote access.

      Entity Tab (PlayerEJB)
      The radio buttons at the top of the tabbed page define the bean’s persistence type
      (Figure 6–5). For              , this type is container-managed persistence, ver-
                               B JE re ya l P
      sion 2.0. (Because version 1.0 did not support relationships, it is not recom-
      mended. These version numbers identify a particular release of the Enterprise
      JavaBeans™ Specification, not the J2EE SDK software.)
                                            A GUIDED TOUR OF THE ROSTERAPP SETTINGS     135




Figure 6–5 Entity Tab of   B J Er ey a lP

The Fields To Be Persisted box lists the persistent and relationship fields defined
by the access methods in the                        code. The checkboxes for the
                                      a v aj .n a eB re ya l P
persistent fields must be selected, but those for the relationship fields must not
be selected. The             entity bean has one relationship field:
                  B J Er ey al P                                            . sm ae t
The abstract schema name is            , a name that represents the relationships
                                    re ya l P
and persistent fields of the             entity bean. This abstract name is refer-
                                   BJ E re ya lP
enced in the              Enterprise JavaBeans™ Query Language (EJB™ QL)
              B JE re y al P
queries. For more information on EJB QL, see Chapter 8.

Finder/Select Methods Dialog Box (PlayerEJB)
To open this dialog box, click Finder/Select Methods on the Entity tab. This dia-
log box(Figure 6–6) enables you to view and edit the EJB QL queries for a
bean’s finder and select methods. For example, to list the finder methods defined
in the                    interface, select the Local Finders radio button. When
      e mo Hr e ya lP la c oL
you select the finder method, its EJB QL query appears in an editable text field.
136                                CONTAINER-MANAGED PERSISTENCE EXAMPLES




      Figure 6–6 Finder/Select Methods Dialog Box of PlayerEJB

      Entity Deployment Settings Dialog Box (PlayerEJB)
      To view this dialog box, click Deployment Settings in the Entity tab. In this dia-
      log box, you define the runtime settings of an entity bean with container-man-
      aged persistence. These runtime settings are specific to the J2EE™ SDK; other
      implementations of the J2EE platform may take a different approach.
      In the J2EE SDK, the bean’s persistent fields are stored in a relational database
      table. In the checkboxes of the Database Table box, you specify whether or not
      the server automatically creates or drops the table. If you want to save the data in
      your table between deployments, then make sure that the Delete Table checkbox
      is not selected. Otherwise, every time you undeploy the bean, the table will be
      deleted.
      The J2EE server accesses the database by issuing SQL calls. In an entity bean
      with container-managed persistence, you do not code these calls. The       y ol p ed
      l o ot utility creates the SQL calls automatically when you click the Generate
      Default SQL button. To view the SQL statement for a finder method, for exam-
      ple, select the Local Finder radio button and then select an entry in the Method
      list. You may modify a SQL statement by editing the text in the SQL Query field.
      For the finder and select methods, the corresponding EJB QL query is also dis-
      played. When you click Generate Default SQL,                translates the EJB
                                                         lo o ty ol p ed
      QL queries into SQL calls. If you change an EJB QL query, you should click the
      Generate Default SQL button again.
                                                METHOD INVOCATIONS IN ROSTERAPP                              137


  To view the SQL                    statement, for example, click the Container
                            EL B AT E T AE RC
  Methods radio button and then select the createTable entry in the Method list.
  The                   statement defines column names for the bean’s persistent
        EL BA T E TA ER C
  fields and specifies a primary key constraint for         , the bean’s primary
                                                                    d Ir e ya lp
  key field.
  When the EJB container creates a new                     instance, it issues a SQL
                                                          B J Er ey al P
  TR ES N I statement. To examine this statement, select createRow from the Method
  list. In the         statement, the parameters in the
                TR ES N I                                        clause correspond to
                                                                      s eu la v
  the arguments of the             method that is defined in the
                               et ae r c                                           e mo Hr e ya lP l ac oL
  interface:

                      , em an gn ir t S ,d i g ni rt S ( et ae r c re ya l Pl ac o L ci lb u p
        ;n o it pe c xE et ae r C sw o rh t )y r al as el bu od ,n oi ti s op g n ir tS

  Database Deployment Settings Dialog Box (PlayerEJB)
  To access this dialog box, click Deployment Settings on the Entity tab. In the
  Deployment Settings dialog box that appears, click Database Settings. The
  Deployment Settings dialog box with the Database Settings label should appear.
  It is important that you set the JNDI name of the database. (If it is not set, the
  bean cannot connect to the database.) For this example, the Database JNDI
  Name field should be                      . The User Name and Password fields
                                ep ac sd u ol C/ cb d j
  are blank because they are not required for Cloudscape.


Method Invocations in RosterApp
  To show how the various components interact, this section describes the
  sequence of method invocations that occur for particular functions. The source
  code for the components is in the             so rp m c/ bj e /c rs /s e lp ma x e/ la ir o tu te e 2j
  ret directory.

  Creating a Player

  1. RosterClient
  The
  t ne i lC re t so R   invokes the                   business method of the
                                             re ya l Pe ta e rc                                so R
           session bean. In the following line of code, the type of the
                  BJ Er e t                                                                  r et so R ym
  object is
      r et so R    , the remote interface of             . The argument of the
                                                          BJ Er et s oR                        er c
              method is a
             r ey al Pe t a                  object, which encapsulates information
                                 sl ia te D re ya l P
  about a particular player.
                                 instances, respectively.                                      BJ Em a eT
and    BJ E re ya l P   sion bean. The    and                            1T        1P
                                                    parameters are the primary keys of the
ses-   BJ E re ts oR    The                          r ey al P dd a
                                             calls the                            tn e il Cr et s oR
                                                                   business method of the
                                                                                  1. RosterClient
                                                     Adding a Player to a Team
                                                                                                   }
                                                                               ;d i n ru te r
                                                                  ; )y ra l as (y ra l aS te s
                                                            ;) no i ti so p (n oi ti s oP te s
                                                                        ; ) em an (e m aN te s
                                                                     ; )d i (d Ir ey a lP te s
    { no it p ec xE et a er C s wo rh t ) yr al a s el bu o d, no i ti so p g ni rt S
                    ,e m an g n ir tS , d i gn i rt S( e t ae rC b je g ni r tS c il b up
statement. The code for the                            et ae rC b je
                                          method follows.
TR ES N I
the container saves the persistent fields in the database by issuing a SQL
            e ta e rC bj e
fields by calling the    access methods. After invoking the                t es
                                                                          method,
The                method assigns the input arguments to the bean’s persistent       et ae r Cb je
                                                                                      3. PlayerEJB
                                                                                           }
                                                                                      }
                      ;) ) (e ga s se Mt eg . xe (n o it pe cx E BJ E w en w or h t
                                                      { )x e n oi tp e cx E( h c ta c }
                                               ; )) ( yr al aS t eg .s l ia te d
                ,) (n oi t is oP t eg .s li a te d , )( em aN t eg .s l ia te d
,) ( dI te g. s li at ed ( et ae r c. em oH r ey al p = r ey a lp r ey a lP la co L
                                                                                      { y rt
                        { ) s li at e d sl ia t eD re y al P( re y al Pe t ae rc d i ov c il b up
for the               method:                                                re ya l Pe ta er c
The type of the                   e mo H re ya lP l ac oL
                            object is                                 e mo Hr e ya lp
                                                       . Here is the source code
e mo H re ya lP l ac oL
the          method is defined in the local home interface,                     .           e ta er c
           BJ E re ya l P
instance of the            entity bean. Because the access             B JE r ey al P
                                                                        is local,
The                  method of the        B JE re t so R
                                                 session bean creates a new      r ey al P et ae rc
                                                                                      2. RosterEJB
                                                    ; )) 00 . 00 1 , "r ep ee k la og "
    , " se no J l ih P" ," 1P " (s li at e Dr ey a lP w en ( re ya l Pe ta er c .r et so R ym
                        CONTAINER-MANAGED PERSISTENCE EXAMPLES                                              138
                                                                                                    }
                                                                                                }
                             ; )) ( eg as s eM te g. x e( no i tp ec xE B JE w en wo rh t
                                                             { ) xe n o it pe cx E ( hc t ac }
                                                             ; )r ey al p (d da .s r ey al p
                                       ;) ( sr ey al P te g = s re ya l p no it c el lo C
                                                                                           { y rt
                                     { ) r ey al p r ey al P la co L( r ey al Pd d a di o v ci lb u p
      code for the         method:                                              re y al Pd d a
      method invokes the    method of the   n oi t ce ll o C                    dd a
                                                      interface. Here is the source
      r ey al P dd a
      fetch the            of related           r ey a lP la c oL
                                                    objects. Next, the           no it c el lo C
      The            method of s re ya lP t eg
                                        invokes the             B JE ma e T
                                                                 access method to         r e ya lP d da
                        ; )s re ya l p no i tc el lo C (s re y al Pt es di ov t c ar ts b a ci lb u p
                                          ; )( sr ey a lP te g n oi tc e ll oC t c ar ts b a ci lb u p
                relationship field are as follows:                                                 s re ya l p
      that represents the players that belong to the team. The access methods for the
      n oi tc e ll oC
      The                  s r ey al p
                     entity bean has a relationship field named       ,a                     BJ Em a eT
                                                                                           3. TeamEJB
                                                                                                        }
                                                                                              }
                           ; )) ( eg as s eM te g. x e( no i tp ec xE B JE w en wo rh t
                                                           { ) xe n o it pe cx E ( hc t ac }
                                                      ; )r e ya lp (r e ya lP dd a .m ae t
                        ; )d Ir e ya lp ( ye Ky ra m ir Py B dn if .e m oH re ya l p
                                                           = r ey al p r ey al P la co L
          ;) d Im ae t (y eK yr a mi rP y Bd ni f. e mo Hm a et = m a et m ae T la co L
                                                                                         { y rt
                { ) d Im ae t g ni rt S , dI re y al p g ni rt S( r ey al Pd d a di o v ci lb u p
                 method of the           session bean:        BJ Er et s oR                     r ey al Pd d a
      business method of the                                      B J Em ae T
                                      entity bean. Here is the source code for the
      r ey al P dd a
      locate the           and                                  BJ Em a eT
                                       instances. Second, it invokes the           BJ Er e ya lP
      They eK y ra mi rP y Bd ni f
                     method performs two steps. First, it calls                 to        r ey a lP dd a
                                                                                          2. RosterEJB
                                                      ;) "1 T " ," 1P " (r ey al P dd a. r et so Ry m
139                         METHOD INVOCATIONS IN ROSTERAPP
140                                           CONTAINER-MANAGED PERSISTENCE EXAMPLES



      Removing a Player
      1. RosterClient
      To remove player , the client would invoke the
                                4P                                           r ey a lP ev om e r   method of the
                session bean:
      BJ Er et s oR

            ;) "4 P" ( re ya l Pe vo me r .r et so R ym

      2. RosterEJB
      The
      re ya l Pe vo me r   method locates the            instance by calling
                                                    BJ E re ya l P                                     P yB d ni f
                  and then invokes the
                ye Ky ra m ir                  method on the instance. This invocation
                                                                 e vo m er
      signals the container to delete the row in the database that corresponds to the
                  instance. The container also removes the item for this instance from
        BJ Er ey a lP
      the
      s r ey al p   relationship field in the        entity bean. By this removal, the
                                                                    B JE ma eT
      container automatically updates the                         relationship. Here is
                                                     B JE re y al P BJ E ma eT
      the                  method of the
          r e ya lP e vo me r                      session bean:      B JE re t so R

                       { ) dI re ya l p gn i rt S( re y al Pe v om er d i ov c il b up
                                                                             { yr t
                                               = re ya l p re y al Pl ac o L
            ;) dI r ey al p (y eK yr a mi rP y Bd ni f. e mo Hr e ya lp
                                                     ;) ( ev om e r. re ya l p
                                               { )x e n oi tp e cx E( h c ta c }
               ;) ) (e ga s se Mt eg . xe (n o it pe cx E BJ E w en w or h t
                                                                                  }
                                                                                     }

      Dropping a Player from a Team

      1. RosterClient
      To drop player    from team
                           2P                 1T   , the client would call the       r ey a lP po rd   method of
      the            session bean:
          B JE r et so R

            ; )" 1 T" , "2 P "( re y al Pp or d .r et so R ym

      2. RosterEJB
      The               method retrieves the
                           r ey a lP po r d              and        instances by call-
                                                                                B JE ma e T      B JE r ey al P
      ing their                     methods. Next, it invokes the
            y eK yr am i rP yB d ni f                                        business
                                                                     r ey al Pp o rd
      method of the
                  B JE ma eT  entity bean. The               method of the
                                                          BJ Er e ts oR                     re ya lP p or d
      session bean follows:
      y eK yr a mi rP y Bd ni f
      object of the target team by invoking the                                                 m ae Tl ac o L
                  method of the          BJ Er et s oR
                                           session bean locates the            ma e Tf Os re y al Pt e g   The
                                                                                          2. RosterEJB
                                  ; )" 2T " (m ae Tf O sr ey a lP te g. r et so Ry m = t s iL re ya l p
      fields. The                     ma eT fO s re ya lP t eg
                                  calls the                               t ne il Cr e ts oR
                                                              method as follows:
           ,       B JE r ey al P
                       , and          —which are copies of the       y ra la s        n oi t is op em a n
                                                                             persistent
      dI re y al p
              objects. A                                      s li at e Ds re y al P
                                            object contains four variables—           ,             s li a t
       eD re y al P t si L ya rr A
      of the             session bean. This method returns an            of          B JE r et so R
                m ae Tf O sr ey a lP te g
      The client can fetch a team’s players by calling the                     method
                                                                                      1. RosterClient
                                                    Getting the Players of a Team
                                                                                                       }
                                                                                             }
                           ; )) ( eg as s eM te g. x e( no i tp ec xE B JE w en wo rh t
                                                           { ) xe n o it pe cx E ( hc t ac }
                                                      ; )r e ya lp (e v om er .s r ey al p
                                     ;) ( sr ey al P te g = s re ya l p no it c el lo C
                                                                                           { y rt
                                   { )r e ya lp r e ya lP l ac oL (r e ya lP po r d di o v ci lb u p
      the         entity bean:                                                                BJ E ma eT
                   r ey al Pp o rd
             method of the               interface. Here is the no i tc el lo C
                                                                              method of              ev om e r
      the               re ya l p
                   relationship field. Next, it drops the target          by calling the      s r ey al p
      the method retrieves the        r ey al Pl a co L
                                            of               n oi tc e ll oC
                                                              objects that correspond to
      The                     BJ Er e ya lP B J Em ae T
                         method updates the                                             r e ya lP p or d
                                                                     relationship. First,
                                                                                           3. TeamEJB
                                                                                                       }
                                                                                              }
                           ; )) ( eg as s eM te g. x e( no i tp ec xE B JE w en wo rh t
                                                           { ) xe n o it pe cx E ( hc t ac }
                                                     ;) re y al p( re y al Pp or d .m ae t
          ;) d Im ae t (y eK yr a mi rP y Bd ni f. e mo Hm a et = m a et m ae T la co L
                        ; )d Ir e ya lp ( ye Ky ra m ir Py B dn if .e m oH re ya l p
                                                           = r ey al p r ey al P la co L
                                                                                         { y rt
               { )d I ma et g n ir tS ,d Ir ey a lp g n ir tS (r e ya lP po r d di o v ci lb u p
141                       METHOD INVOCATIONS IN ROSTERAPP
                                 ;) (s re y al Pt e g no it c el lo C t ca rt s ba c il b up
                                                             relationship field:          sr ey a lp
entity bean is an access method of the          BJ Em a eT                     s re y al Pt e g
                                                                      method of the                The
                                                                                  3. TeamEJB
                                                                                               }
                                                          ;t s iL sl i at ed n r ut er
                                                                                      }
                                            ; )s li a te d( dd a .t si L sl ia te d
                                       ; )) ( yr al a St eg .r e ya lp
         , )( n oi ti so P te g. r ey al p , )( em a Nt eg .r e ya lp
                ,) (d Ir e ya lP t eg .r ey a lp (s l ia te Dr e ya lP we n
                                               = s l ia te d s li at e Dr ey al P
              ; )( tx en . i )r e ya lP la c oL ( = r ey al p r ey a lP la co L
                                                         { )) ( tx eN s ah .i ( e li hw
                                     ; )( r ot ar e ti .s re y al p = i r ot a re tI
                         ;) (t s iL ya rr A w en = ts iL s li at e d ts iL y ar rA
   { ) sr ey a lp n oi t ce ll o C( sl ia t eD oT s re ya lP y po c t si Ly ar r A et av i rp
                   method:    s li at eD o Ts re y al Py po c
                                         objects that is generated by the
sl ia t eD re y al P  of  t si Ly ar r A The                        ma eT fO s re ya l Pt eg
                                                                    method returns the
                                                                                               }
                                ; )s re ya l p( sl i at eD oT s re ya l Py po c n ru te r
                                                                                       }
                      ;) ) (e ga s se Mt eg . xe (n o it pe cx E BJ E w en w or h t
                                                      { )x e n oi tp e cx E( h c ta c }
                                         ;) ( sr ey a lP te g. m ae t = s re ya l p
    ; ) dI ma e t( ye Ky r am ir P yB dn if . em oH m ae t = m ae t m ae Tl ac o L
                                                                                  { yr t
                                                 ; l lu n = s re ya l p no it c el lo C
                  { )d I ma et gn ir tS ( ma eT f Os re ya l Pt eg ts iL ya r rA c il b up
                         method:
ma eT f Os re y al Pt eg the         entity bean. Here is the source code for the   B JE ma eT
method of     s re ya l Pt eg
                         method. Next, the         m ae Tf Os r ey al P te g
                                                              method calls the
                   CONTAINER-MANAGED PERSISTENCE EXAMPLES                                                142
                                           METHOD INVOCATIONS IN ROSTERAPP                               143


This method is exposed to local clients because it is defined in the local inter-
face,          :
     ma e Tl ac o L

    ; )( s re ya lP t eg n oi t ce ll o C ci lb u p

When invoked by a local client, a          access method returns a reference to the
                                           te g
relationship field. If the local client alters the object returned by a         access te g
method, it also alters the value of the relationship field inside the entity bean. For
example, a local client of the              entity bean could drop a player from a
                                      B JE ma e T
team as follows:

    ;) dI ma e t( ye K yr am ir P yB dn i f. em oH m ae t = m ae t m ae Tl ac o L
                       ;) (s re y al Pt e g. ma et = sr ey a lp n o it ce ll o C
                                                ;) r ey al p( e vo me r .s re ya l p

If you want to prevent a local client from modifying a relationship field in this
manner, you should take the approach described in the next section.

Getting a Copy of a Team’s Players
In contrast to the methods discussed in the preceding section, the methods in this
section demonstrate the following techniques:
    • Filtering the information passed back to the remote client
    • Preventing the local client from directly modifying a relationship field

1. RosterClient
If you wanted to hide the salary of a player from a remote client, you would
require the client to call the
              B JE re t so R                         method of the
                                                 y po C ma eT f Os re ya l Pt eg
session bean. Like the                     method, the
              y po Cm a eT fO s re ya lP t eg                  m ae Tf Os r ey al P te g
method returns an              of                objects. However, the objects
                                                      s l ia te Dr e ya lP     ts iL ya r rA
returned by                         are different—their
                                  y ra la s                     variables have
                                                                       y po Cm ae T fO sr e ya lP te g
been set to zero. The                calls the
                         y po Cm a eT fO s re ya lP t eg               method
                                                                      tn ei l Cr et so R
as follows:

    ;) "5 T "( yp o Cm ae Tf O sr ey a lP te g. r et so Ry m = t s iL re ya l p

2. RosterEJB
Unlike the                      method, the
                         yp oC m ae Tf O sr ey al P te g              methodma e Tf Os r ey al Pt e g
does not invoke the
              m ae Tl a co L   access method that is exposed in the         sr e ya lP te g
interface. Instead, the                       method retrieves a copy of the
                                                        y po Cm a eT fO s re ya lP t eg
player information by invoking the                     business method that is
                                             s re y al Pf O yp oC te g
                                                                                              }
                                                               ; ts iL r ey al p n ru te r
                                                                                      }
                                              ; )s l ia te d( d da .t s iL re ya l p
      ; )0 0. 0 , )( no i ti so P te g. re y al p , )( em aN t eg .r e ya lp
                , )( dI r ey al P te g. re y al p( s li at eD r ey al P w en
                                                = s li at ed sl ia t eD re ya l P
               ;) (t xe n .i ) r ey al Pl a co L( = re ya l p re y al Pl ac o L
                                                         { ) ) (t xe N sa h. i( el ih w
                                        ;) ( ro ta r et i. sr e ya lp = i ro t ar et I
                                     ;) (s r ey al P te g = s re ya l p no it c el lo C
                             ;) ( ts iL ya r rA w e n = ts i Lr ey a lp t si L ya rr A
                                      { ) ( sr ey a lP fO yp o Ct eg ts iL ya r rA c il b up
                    BJ Em ae T
method. The source code for the    sr ey a lP fO yp o Ct eg
                                                        of         follows.
yp o Cm ae Tf O sr ey al P te g
player’s salary is hidden from a client that invokes the
sistent fields—except for the                        yr a la s
                                       field, which it sets to zero. As a result, a
     BJ Er ey a lP
of the                  objects. The method copies the values of        s li at e Dr ey al P
                                                                              per-
           of related                                      re ya l Pl ac oL
                                   objects and copies information to the variables        no it c el
 l oC   objects. To create this                 ts iL y ar rA
                                           , the method iterates through the                 sl i at
 e Dr e ya lP     t si Ly a rr A
                          method of          B JE ma eT
                                               returns an             sr e ya lP f Oy po Ct e g
                                                                     of                           The
                                                                                    3. TeamEJB
                                                                                              }
                                                              ; t si Ls r ey al p n ru te r
                                                                                       }
                      ;) ) (e ga s se Mt eg . xe (n o it pe cx E BJ E w en w or h t
                                                      { )x e n oi tp e cx E( h c ta c }
                         ; )( sr e ya lP fO y po Ct e g. ma et = ts i Ls re ya l p
    ; ) dI ma e t( ye Ky r am ir P yB dn if . em oH m ae t = m ae t m ae Tl ac o L
                                                                                  { yr t
                                            ;l lu n = t si L sr ey a lp t si L ya rr A
            { )d Im ae t g ni r tS (y po C ma eT f Os re ya l Pt eg ts iL ya r rA c il b up
:                B JE re t so R              y po Cm a eT fO s re ya lP t eg
                            source code for the                        method of
 . Here is the  B J Em ae T method cannot modify the   s r ey al p
                                                               relationship field of
yp oC m ae Tf O sr ey al P te g
                            defined in the                         ma e Tl ac o L
                                                     interface. As a result, the
                     CONTAINER-MANAGED PERSISTENCE EXAMPLES                                             144
                        will execute the SQL           statement.       T C EL ES
      method, it    n oi ti s oP yB dn i f
                        ment. At runtime, when the container invokes the
              TC E LE S
          state-        The                                                            lo o ty ol pe d
                                          utility translates the EJB QL query into a SQL
                                                                    1 ? = no i ti so p .p E RE H W
                                           p re ya l P MO R F )p (T C EJ BO T C NI TS I D TC EL E S
      method has this EJB QL query:
      n oi ti s oP yB d ni f
      defined in the bean’s deployment descriptor. For example, the
      ify the queries associated with the finder methods, EJB QL queries must be
      entity bean class (                                              n ae Br ey a lP
                                     ) does not implement its finder methods. To spec-
      Because the                                                             B JE r ey al P
                                entity bean uses container-managed persistence, the
                                                           ;n oi tp e cx Er ed n iF s w or ht
                        ) no it s is op gn ir tS ( no it i so Py Bd n if n oi t ce ll o C ci lb u p
                  method:      no it i so Py Bd n if   interface defines the    em o Hr ey a lP la co L     The
                                                                                         3. PlayerEJB
                                                                                                        }
                                       ; ) sr ey al p (s li a te Do Ts r ey al Py p oc n r ut er
                                                                                            }
                           ; )) ( eg as s eM te g. x e( no i tp ec xE B JE w en wo rh t
                                                           { ) xe n o it pe cx E ( hc t ac }
                  ;) n oi ti so p (n oi t is oP yB d ni f. e mo Hr ey a lp = s r ey al p
                                                                                       { y rt
                                                           ; l lu n = s re ya lp no it c el lo C
               { )n o it is op gn ir t S( no it i so Py B sr ey al P te g ts i Ly ar r A ci lb u p
                                      method of the    BJ Er e ya lP
                                                               entity bean:            n oi ti s oP yB dn i f
      list by invoking the       s re y al p      method retrieves the  no i ti so Py B sr ey al P te g     The
                                                                                          2. RosterEJB
                 ; )" r ed ne fe d "( no i ti so Py B sr ey a lP te g. r et so Ry m = t s iL re ya l p
                                                  of the              session bean:    B JE re t so R
      method    n oi ti s oP yB sr e ya lP t eg   The client starts the procedure by invoking the
                                                                                     1. RosterClient
                                                  Finding the Players by Position
145                       METHOD INVOCATIONS IN ROSTERAPP
     re y al Pl ac o L
         , the             the parameter of the    s tr o pS tc el e Sb je
                                                                  method is of type
method. Since     s tr op S tc el eS b je
                           The            method is a wrapper for the              s tr op St e g
                                                                                   3. PlayerEJB
                                                                                                }
                                                                ; ts iL s tr op s n ru te r
                                                                                          }
                                                   ; ) tr op s( d da .t s iL st ro p s
                                  ; )( tx en . i )g n ir tS ( = t ro p s gn ir t S
                                                           { ) ) (t xe N sa h. i( el ih w
                                           ; ) (r ot a re ti .s t ro ps = i ro t ar et I
                                                                                      }
                     ;) ) (e ga s se Mt eg . xe (n o it pe cx E BJ E w en w or h t
                                                     { )x e n oi tp e cx E( h c ta c }
                                        ;) ( st ro p St eg .r e ya lp = st ro p s
                  ;) dI r ey al p (y eK yr a mi rP y Bd ni f. e mo Hr e ya lp
                                                     = re ya l p re y al Pl ac o L
                                                                                 { yr t
                                                     ; ll un = st ro p s no it c el lo C
                                     ; )( ts i Ly ar r A we n = t si L st ro ps ts iL ya r rA
             { ) dI re y al p g ni rt S( r ey al P fO st ro p St eg ts iL ya r rA c il b up
            session bean:                                                                BJ Er et s oR
                  re ya lP f Os tr o pS te g
        bean. Here is the source code for the                    method of the               y ti t ne
BJ Er e ya lP returned by the                     st ro p St eg
                                            business method of the                     n oi tc el l oC
         ts iL y ar rA
represent the sports of the specified player. It constructs the         from a
The            gn ir tS       ts iL y ar rA
                           method returns an                of         re ya lP f Os tr op S te g
                                                                   objects that
                                                                                   2. RosterEJB
                           ; )" 82 P "( re ya l Pf Os t ro pS te g .r et s oR ym = ts iL tr o ps
                                                                            bean:
session   B JE re ts o R   method of the       re ya l Pf Os tr o pS te g   The client invokes the
                                                                                1. RosterClient
                                               Getting the Sports of a Player
Dialog Box (PlayerEJB), page (135).
edit an EJB QL query in                              lo ot y ol pe d
                                      , see the section Finder/Select Methods
For details about EJB QL, please refer to Chapter 8. To learn how to view and
                   CONTAINER-MANAGED PERSISTENCE EXAMPLES                                                146
                                                                                           l o ot yo lp e d
                                                                utility.   l oo ty ol p ed   3. Run the
                                                                                    es ob r ev       ee 2 j
                                    2. In another terminal window, start the J2EE server.
                                                                              t ra t s     e p ac sd uo l c
                        1. In a terminal window, start the Cloudscape database server.
                                                                                             Setting Up
                                   Running the RosterApp Example
                                         T CE LE S
      container will execute its corresponding SQL      statement.
      managed persistence, when the         s tr op S tc el eS b je
                                                       method is invoked the EJB
                           BJ Er e ya lP
      statements for the bean’s EJB QL queries. Because            uses container-
      T CE LE S
      Before deploying                  lo o ty ol pe d
                                     , you run                        B JE r ey al P
                                                         to generate SQL
                                                                                  1 ? = p E RE H W
                                                     t SA )s ma et . p( N I , p re y al P MO R F
                                                       tr o ps .e ug a el .t T C NI TS I D TC EL E S
                       method:                                                           s t ro pS t ce le Sb j e
      The bean’s deployment descriptor specifies the following EJB QL query for the
                                                            ;n oi tp e cx Er ed n iF s w or ht
      ) re ya l p re y al Pl ac o L( st r op St ce l eS bj e n oi tc e ll oC t c ar ts b a ci lb u p
                              method:    s tr op S tc el e Sb je   class defines the       na e Br ey al P    The
                                                                                                          }
                                                ; )r e ya lp ( st ro pS t ce le Sb j e nr u te r
                  ; )( t ce jb Ol a co LB J Et eg .t x et no c )r ey al P la co L. m ae t(
                                                                  = re y al p re y al Pl a co L
                   { n oi tp ec x Er ed n iF s wo r ht ) ( st ro pS t eg n oi t ce ll o C ci lb u p
      class implements the                         st r op St eg
                                     method as follows:                                          n a eB re ya l P
      method passes along a reference to the entity bean instance. The                             s tr op St e g
147                          RUNNING THE ROSTERAPP EXAMPLE
148                                       CONTAINER-MANAGED PERSISTENCE EXAMPLES



        Deploying the Application
            1. In            , open the
                  l oo ty o lp ed                      file.
                                               ra e .p pA re t so R
               a. Choose File→Open from the main menu.
               b. In the Open Object dialog box, navigate to the                m ax e /l ai r ot ut ee 2 j
                             directory.
                   sr a e/ se l p
               c. Select the                file.
                                ra e .p pA r et so R
               d. Click Open Object.
            2. Deploy the application.
               a. In deploytool, select             from the tree view.
                                             pp A re ts o R
               b. Choose Tools→Deploy from the main menu.
               c. In the Introduction dialog box, select the Return Client JAR checkbox.
               d. In the Client JAR File Name field, make sure that the file is called                  soR
                                          and     that its path
                                   ra j .t ne il C pp Ar e t            refers to      the
                                                    directory.
                   s ra e/ s el pm ax e /l ai ro t ut ee 2 j
               e. Click Next until the Review dialog box appears.
               f. Click Finish.

        Running the Client
            1. In a terminal window, go to the         s ra e/ s el pm ax e /l ai r ot ut ee 2 j   directory.
            2. Set the           environment variable to
                        H T AP CP P A                                 r aj . tn ei lC p pA re ts o R .
            3. Type the following command:

            tn ei lc n ur   ra e .p pA re t so R t ne il c      tn ei l Cr et s oR e ma n    ht u at xe t

            4. At the login prompts, enter        t se u g   for the user name and     3 2 1t se u g   for the
               password.


      deploytool Tips for Entity Beans With
      Container-Managed Persistence
        Chapter 2 covered the basic steps for building and packaging enterprise beans.
        This section highlights the tasks in            that are needed for entity beans
                                                   lo ot y ol pe d
        with container-managed persistence. The examples referenced in this section are
        from A Guided Tour of the RosterApp Settings, page (128).
                                     DEPLOYTOOL   TIPS FOR ENTITY BEANS WITH CONTAINER-MANAGED PERSIS-



Specifying the Bean’s Type
In the New Enterprise Bean wizard, specify the bean’s type and persistent man-
agement.
    1. In the Edit Contents dialog box, add all of the classes required by the entity
       bean and by its related beans.
    2. In the General dialog box, select the Entity radio button.
    3. In the General dialog box, specify the local interfaces of the entity bean.
       (If the bean also has remote interfaces, specify them as well.)
    4. In the Entity Settings dialog box, select the radio button for Container-
       Managed Persistence (2.0). You may skip the other settings in this dialog
       box and enter them later in the Entity tab.

Selecting the Persistent Fields and Abstract Schema
Name
In the Entity tab, enter the field information and the abstract schema name.
    1. In the Fields To Be Persisted list, select the fields that will be saved in the
       database. The names of the persistent fields are determined by the access
       methods defined in the entity bean code.
    2. Enter values in the Primary Key Class and Primary Key Field Name fields.
       The primary key uniquely identifies the entity bean.
    3. In the Abstract Schema Name field, enter a name that represents the entity
       bean. This name will be referenced in the EJB QL queries.
An example is shown in the section Entity Tab (PlayerEJB), page (134).

Defining EJB QL Queries for Finder and Select
Methods
You specify these settings in the Finder/Select Methods dialog box.
    1. To open the Finder/Select Methods dialog box, go to the Entity tab and
       click Finder/Select Methods.
    2. To display a set of finder or select methods, click one of the radio buttons
       under the Show label.
    3. To specify an EJB QL query, choose the name of the finder or select
       method from the Method list and then enter the query in the field labeled
       EJB QL Query.
150                                     CONTAINER-MANAGED PERSISTENCE EXAMPLES



      An example is shown in the section Finder/Select Methods Dialog Box
      (PlayerEJB), page (135).

      Generating SQL and Specifying Table Creation
      In             , the various Deployment Settings dialog boxes enable you to
         lo o ty ol p ed
      enter information needed by the server at runtime. These settings are specific to
      the J2EE SDK implementation.
          1. To open the Deployment Settings dialog box, go to the Entity tab and click
             Deployment Settings.
          2. With container-managed persistence, the container can automatically cre-
             ate or delete the database table used by the entity bean. If you’ve loaded
             test data into the table, you may want to deselect the checkboxes in the
             Database Table box.
          3. To translate the EJB QL queries into SQL            statements, click Gen-
                                                              TC E LE S
             erate Default SQL. If this button is disabled, you must first specify the
             database settings.
      An example is shown in the section Entity Deployment Settings Dialog Box
      (PlayerEJB), page (136).

      Specifying the Database JNDI Name, User Name,
      and Password
      You specify these settings in the Database Settings dialog box.
          1. To open the Database Settings dialog box, go to the Entity tab and click
             Deployment Settings. In the Deployment Settings dialog box, click Data-
             base Settings.
          2. Enter a value in the Database JNDI Name field. The examples in this book
             use the                     JNDI name.
                       ep a cs du o lC /c bd j
          3. The Cloudscape database shipped with the J2EE SDK does not require a
             user name or password. So, if your bean connects to the Cloudscape data-
             base, you may leave the User Name and Password fields blank. To connect
             to other types of databases, you may need to enter values into these fields.
      An example is shown in the section Database Deployment Settings Dialog Box
      (PlayerEJB), page (137).
                                               PRIMARY KEYS FOR CONTAINER-MANAGED PERSISTENCE          151


  Defining Relationships
  The Relationships tab enables you to define relationships between entity beans
  that reside in the same EJB JAR file.
       1. Before you create a relationship between two entity beans, you must first
          create both beans with the New Enterprise Bean wizard.
       2. To display the Relationships tab, select the EJB JAR in the tree view and
          then select the Relationships tab.
       3. To add or edit a relationship, go the Relationships tab and click the appro-
          priate button.
       4. The Add (or Edit) Relationship dialog box appears. (The Add Relation-
          ship and Edit Relationship dialog boxes are identical.)
  An example is shown in the section Edit Relationship Dialog Box
  (TeamJAR), page (132).


Primary Keys for Container-Managed
Persistence
  If the primary key class does not belong to the J2SE or J2EE standard libraries,
  then you must implement the class and package it along with the entity bean. For
  example, if your entity bean requires a composite primary key (which is made up
  of multiple fields), then you need to provide a customized primary key class.

  The Primary Key Class
  In the following example, the
  y eK r ed rO e sa hc ru P                            class implements a composite
  key for the                        entity bean. The key is composed of two fields,
                          BJ E re dr Oe s ah cr u P
                   and             , whose names must match two of the persistent
                            dI r od ne v       l ed o Mt cu do r p
  fields in the entity bean class.

       { el b az il ai r eS .o i .a va j st ne me l pm i y e Kr ed rO e sa hc r uP ss a lc ci lb u p

             ; le d oM tc ud o rp g ni r tS c i lb up
                    ;d Ir od n ev g ni r tS c i lb up

             ; } { ) ( ye Kr ed r Oe sa hc r uP c i lb up

             { )( l ed oM t cu do rP t eg g ni r tS c i lb up

                   ; le do Mt c ud or p n ru te r
                                              l ed o Mt cu d or p
                ) that make up the primary key:                     and d Ir o dn evsistent fields (
class, the following access methods define the per-                 na eB re d rO es a hc ru P
                                                                                    In the
                              Primary Keys in the Entity Bean Class
                         • The class is serializable.
                           ods.
meth-   ) re ht o t ce jb O( s la uq e      ) ( ed oC hs a h
                           The class implements the                and                           •
                           The class has a public default constructor.                           •
                           The fields are a subset of the bean’s persistent fields.              •
                                                  c i lb up
                           All fields are declared as        .                                   •
                             c i lb up
                           The access control modifier of the class is          .                •
requirements:
For container-managed persistence, a primary key class must meet the following
                                                                                                 }
                                                                                         }
         ; )( e do Ch sa h .) dI r od ne v( t ac no c .l ed oM t cu do r p nr ut e r
                                                      { ) (e d oC hs a h tn i c il bu p
                                                                                         }
                                                                ;e sl a f nr ut e r
                                                                                  }
               ;) )d Ir o dn ev . )r eh to ) ye Kr e dr Oe sa h cr uP ( (
                                                (s l au qe .d I ro dn e v
        && ) l ed oM tc u do rp . )r eh to ) ye Kr e dr Oe sa h cr uP ( (
                                   ( sl au q e. le d oM tc ud o rp ( n ru te r
                     { ) ye Kr e dr Oe sa h cr uP fo ec na t sn i r eh to ( f i
                                { ) re ht o t ce j bO (s la u qe n a el oo b c il bu p
                                                                                         }
                                                           ;d I ro dn e v nr ut e r
                                            { )( d Ir od ne V te g g ni rt S c il bu p
                                                                                         }
                   CONTAINER-MANAGED PERSISTENCE EXAMPLES                                              152
                                            PRIMARY KEYS FOR CONTAINER-MANAGED PERSISTENCE          153


             ;) (d I ro dn e Vt eg g n ir tS t c ar ts b a ci lb u p
    ;) di gn ir tS ( dI ro d ne Vt es di ov t c ar ts b a ci lb u p

                 ; ) (l ed oM t cu do r Pt eg g n ir tS t c ar ts b a ci lb u p
    ; )e ma n g ni r tS (l ed o Mt cu d or Pt es di ov t c ar ts b a ci lb u p

The next code sample shows the                method of the
                                       e t ae rC b je                  n ae Br e dr Oe s ah cr uP
class. The return type of the            method is the primary key, but the return
                                             e t ae rC b je
value is      . Although not required, the
         l lu n                    l l un       return value is recommended for
container-managed persistence. This approach saves overhead because the bean
does not have to instantiate the primary key class for the return value.

    ,d Ir od n ev g n ir tS ( e ta er C bj e ye K re dr Oe s ah cr u P ci lb u p
               )e ma N tc ud or p g ni r tS , le d oM tc ud o rp g n ir tS
                                       { n oi tp e cx Ee ta e rC s w or ht

                       ; ) dI ro dn e v( dI r od ne Vt e s
    ; ) le do M tc ud or p (l ed oM t cu do r Pt es
        ;) em a Nt cu do r p( em aN t cu do r Pt es

          ;l l un n r ut er
    }

Generating Primary Key Values
For some entity beans, the value of a primary key has a meaning for the business
entity. For example, in an entity bean that represents a phone call to a support
center, the primary key might include a time stamp that indicates when the call
was received. But for other beans, the key’s value is arbitrary—provided that it’s
unique. With container-managed persistence, these key values can be generated
automatically by the EJB container. To take advantage of this feature, an entity
bean must meet these requirements:
    • In the deployment descriptor, the primary key class is defined as a
                           . The primary key field is not specified.
        tc ej bO . gn al . av aj
    • In the home interface, the argument of the                         method
                                                              ye Ky ra m ir Py B dn if
      must be a                       .
                     tc ej b O. gn al . av aj
    • In the entity bean class, the return type of the            method must be
                                                               e ta e rC bj e
      a                      .
          tc e jb O. gn a l. av a j
In these entity beans, the primary key values are in an internal field that only the
EJB container can access. You cannot associate the primary key with a persistent
field or any other instance variable. However, you can fetch the bean’s primary
154                                 CONTAINER-MANAGED PERSISTENCE EXAMPLES



      key by invoking the
                 ye K yr am i rP te g         method, and you can locate the bean by
      invoking its                       method.
                        ye Ky ra m ir Py B dn if
                       7
        A Message-Driven
           Bean Example
                                                       Dale Green and Kim Haase



S   INCE message-driven beans are based on the Java™ Message Service (JMS)
technology, to understand the example in this chapter you should already be
familiar with basic JMS concepts such as queues and messages. The best place
to learn about these concepts is the Java Message Service Tutorial:

    l mt h. xe d ni /l a ir ot ut / sm j/ s tc ud or p /m oc .n u s. av a j/ /: pt t h

This chapter describes the source code of a simple message-driven bean exam-
ple. Before proceeding, you should read the basic conceptual information in the
section What Is a Message-Driven Bean?, page (56).

In This Chapter
           Example Application Overview 156
           The J2EE™ Application Client 157
           The Message-Driven Bean Class 158
               The onMessage Method 158
               The ejbCreate and ejbRemove Methods 159
           Running the SimpleMessageEJB Example 159
               Starting the J2EE™ Server 159
               Creating the Queue 159
               Deploying the Application 160
               Running the Client 160
                                                                                         155
156                                          A MESSAGE-DRIVEN BEAN EXAMPLE


                    Deploytool Tips for Message-Driven Beans 161
                       Specifying the Bean’s Type and Transaction Management 161
                       Setting the Message-Driven Bean’s Characteristics 161
                    Deploytool Tips for JMS Clients 163
                       Setting the Resource References 164
                       Setting the Resource Environment References 164
                       Specifying the JNDI Names 164


      Example Application Overview
        This application has the following components:
             •                        : A J2EE™ application client that sends several
                 t n ei lC eg a ss eM e lp mi S
               messages to a queue.
             •                    : A message-driven bean that asynchronously receives
                 B JE eg a ss eM e lp mi S
               and processes the messages that are sent to the queue.
        Figure 16 illustrates the structure of this application. The application client sends
        messages to the queue, which was created administratively using the                ni md a ee 2j
        command. The JMS provider (in this, case the J2EE server) delivers the mes-
        sages to the instances of the message-driven bean, which then processes the mes-
        sages.




        Figure 7–1 The     p p Ae ga ss e Me lp m iS   Application

        The source code for this application is in the                       m ax e /l ai r ot ut ee 2 j
                                  directory. To compile the code, go to the
        eg as s em el p mi s/ bj e /c rs /s e lp
                                                                                           }
                                                 ; )e g as se m( d ne s. re d ne Se u eu q
                                                      ; )) (t xe T te g. eg a ss em
                              + " : e ga ss em gn id n eS "( nl t ni rp .t u o. me t sy S
                       ;) )1 + i( + " eg as s em s i s ih T" ( tx eT te s .e ga s se m
                                          { ) + +i ; S GS M_ MU N < i ; 0 = i tn i( r o f
                                   ; )( e ga ss eM t xe Te t ae rc .n o is se Se u eu q = e ga ss e m
                                      Finally, the client sends several messages to the queue:
                             ;) e ue uq ( re dn eS e ta er c .n oi ss e Se ue uq = re d ne Se ue u q
                                                        ;) E GD EL WO N KC A_ OT U A. no i ss eS
                                , es la f (n oi ss e Se ue u Qe ta er c .n oi tc e nn oC e ue uq
                                                                                 = n oi s se Se ue u q
                       ;) (n oi t ce nn o Ce ue uQ e ta er c .y ro tc a Fn oi tc e nn oC e ue uq
                                                                            = n o it ce n no Ce ue u q
                        Next, the client creates the queue connection, session, and sender:
               ; )" e ma Ne ue u Q/ sm j /v ne /p m oc :a v aj "( pu k oo l. tx e tn oC i dn j
                                                                              ) e ue uQ ( = e ue u q
                      ;) "y ro t ca Fn o it ce nn o Ce ue u Qy M/ sm j /v ne /p m oc :a v aj "(
                                                                   p u ko ol .t x et no C id nj
                         )y ro t ca Fn o it ce nn o Ce ue u Q( = y r ot ca Fn o it ce n no Ce ue u q
                                                                                                  queue:
      listens to. The client starts out by locating the connection factory and                 na eB eg a s
       se Me l pm iS      sends messages to the queue that the         t n ei lC e ga ss eM e lp mi S    The
                                         The J2EE™ Application Client
        directory.s ra e/ se l pm ax e /l ai ro t ut ee 2
                                                file is in the j            ra e. pp A eg as s eM el pm i S
      . A sample   eg as s em el pm i s t n a     directory and type      s el pm ax e /l ai r ot ut ee 2 j
157                          THE J2EE™ APPLICATION CLIENT
158                                         A MESSAGE-DRIVEN BEAN EXAMPLE



      The Message-Driven Bean Class
        The code for the    BJ Ee g as se Me l pm iS    class illustrates the requirements of a mes-
        sage-driven bean class:
            •   It implements the                        and
                                      n ae Bn ev i rD eg a ss eM           r en et s iL eg a ss eM   interfaces.
            •   The class is defined as        .
                                             ci lb u p
            •   The class cannot be defined as             or     .
                                                         t ca r ts ba       l a ni f
            •   It implements one              method.
                                       e ga s se Mn o
            •   It implements one              method and one
                                       e ta e rC bj e                          ev om e Rb je   method.
            •   It contains a public constructor with no arguments.
            •   It must not define the           method.
                                            ez il a ni f
        Unlike session and entity beans, message-driven beans do not have the remote or
        local interfaces that define client access. Client components do not locate mes-
        sage-driven beans and invoke methods on them. Although message-driven beans
        do not have business methods, they may contain helper methods that are invoked
        internally by the             method.
                           e ga ss e Mn o


        The onMessage Method
        When the queue receives a message, the EJB™ container invokes the                            eg as s eM no
        method of the message-driven bean. In the                         class, the
                                                                        n ae Be ga s se Me l pm iS
                  method casts the incoming message to a
        eg as se M no                                                   and displays
                                                                           e ga ss e Mt xe T
        the text:

            { )e ga ss e Mn i e ga ss eM ( eg as s eM no d i ov c il b up
                                 ; ll un = gs m e ga ss e Mt xe T

                                                                                    { yr t
                       { )e ga s se Mt xe T f oe c na ts ni eg as s eM ni ( f i
                               ; e ga ss eM n i )e g as se Mt x eT ( = g sm
                                                  n l tn ir p. t uo .m e ts yS
                  " : de v ie ce r e ga ss e M :N A EB E GA S SE M" (
                                              ;) )( t xe Tt eg . gs m +
                                                                         { es le }
                                                  n l tn ir p. t uo .m e ts yS
                               " :e py t g no rw fo e ga s se M" (
                   ;) )( e ma Nt e g. )( ss a lC te g .e ga ss e Mn i +
                                                                                    }
                                                  { )e n oi t pe cx E SM J( h c ta c }
                                                      ;) (e ca r Tk ca t St ni rp . e
                                                  ; ) (y ln Ok c ab ll o Rt es .c d m
                                               RUNNING THE SIMPLEMESSAGEEJB EXAMPLE                         159


                 { ) et e l ba wo rh T ( hc t ac }
               ; ) (e ca rT k ca tS tn i rp .e t
                                                 }
      }

  The ejbCreate and ejbRemove Methods
  The signatures of these methods have the following requirements:
      •    The access control modifier must be         .    c il bu p
      •    The return type must be       . di ov
      •    The modifier cannot be          or
                                           ci ta ts .    la ni f
      •    The          clause must not define any application exceptions.
                  sw o rh t
      •    The method has no arguments.
  In the   n a eB eg as s eM el pm i S   class, the   e t ae rC bj e   and   e vo me R bj e   methods are
  empty.


Running the SimpleMessageEJB Example
  Starting the J2EE Server
  To view the output of the message-driven bean, you must start the server in ver-
  bose mode:

      ee 2 j     es ob r ev

  Creating the Queue
      1. Create the queue with the           n i md ae e2 j   command:

      n im da ee 2 j     e u eu q e ue uQ yM / sm j n oi ta ni t se Ds mJ d da

      2. Verify that the queue was created:

      n im da ee 2 j     n o it an it s eD sm Jt s il

  Deploying the Application
      1. In,l oo t yo lp ed       open the     se Me l pm iS / sr ae /s e lp ma x e/ la ir o tu te e 2j
                              file (File→Open).
              r a e. pp A eg as
160                                           A MESSAGE-DRIVEN BEAN EXAMPLE



             2. Deploy the                   application (Tools→Deploy). In the Intro-
                                 pp A eg as s eM el pm i S
                duction dialog box, make sure that you select the Return Client JAR
                checkbox. For detailed instructions, see Deploying the J2EE™
                Application, page (37).

        Running the Client
             1. In a terminal window, go to the               s ra e/ s el pm ax e /l ai r ot ut ee 2 j    direc-
                tory.
             2. Set the             environment variable to
                               H TA P CP PA                                      i lC p pA eg a ss eM el p mi S
                        .
                 r a j. tn e
             3. Type the following command on a single line:

                  ra e. p pA eg a ss eM el p mi S tn e il c tn ei lc n ur          e ma n
                                h tu at xe t tn ei l Ce ga s se Me lp m iS

             4. At the login prompts, enter          ee 2 j   for the user name and         e e2 j   for the pass-
                word.
             5. The client displays these lines:

             1 e ga s se m si si hT :e ga ss e m gn id n eS
             2 e ga s se m si si hT :e ga ss e m gn id n eS
             3 e ga s se m si si hT :e ga ss e m gn id n eS

             6. In the terminal window in which you’ve started the J2EE server (in ver-
                bose mode), the following lines should be displayed:

             1 e g as se m s i si h T :d e vi ec er eg as s eM : NA E B EG AS S EM
             2 e g as se m s i si h T :d e vi ec er eg as s eM : NA E B EG AS S EM
             3 e g as se m s i si h T :d e vi ec er eg as s eM : NA E B EG AS S EM


      deploytool Tips for Message-Driven Beans
        Chapter 2 covered the basic steps for building and packaging enterprise beans.
        This section describes the tasks in
                               l oo ty o lp ed          that are necessary for message-
        driven beans. To view an example in
        l oo ty ol p ed                                                  , open the
        j                                                         file and select
                   r ae . pp Ae g as se Me l pm iS / sr ae /s e lp ma x e/ la ir o tu te e 2                m iS
                        from the tree view.                              B JE e ga ss eM e lp
                                          DEPLOYTOOL   TIPS FOR MESSAGE-DRIVEN BEANS                  161


Specifying the Bean’s Type and Transaction
Management
You specify the type when you create the bean with the New Enterprise Bean
wizard.
    1. To start the wizard, select File→New→Enterprise Bean.
    2. In the General dialog box of the wizard, select the Message-Driven radio
       button.
    3. In the Transaction Management dialog box, you may select either the
       Bean-Managed or Container-Managed radio button. If you select the
       Bean-Managed button, then in step 4 of the next section, you may select
       the acknowledgment type.

Setting the Message-Driven Bean’s Characteristics
You may specify these settings in two places:
    • The Message-Driven Bean Settings dialog box of the New Enterprise
      Bean wizard
    • The Message tab of the bean (see Figure 7–2)
These settings are as follows:
    1. For the Destination Type, select either the Queue or Topic radio button. A
       queue uses the point-to-point messaging domain and may have at most
       one consumer. A topic uses the publish-subscribe messaging domain; it
       may have zero, one, or many consumers.
    2. In the Destination combo box, select the JNDI name of the destination that
       you have created administratively. For an example, see the section Creat-
       ing the Queue, page (159). The destination is either a          or a eu eu Q         c ip oT
       object; it represents the source of incoming messages and the target of out-
       going messages.
    3. In the Connection Factory combo box, select the appropriate object, either
       a                                 or a
          y r ot ca F no it ce n no Ce u eu Q                             . These
                                                       y ro t ca Fn oi t ce nn o Cc ip oT
       objects produce the connections through which J2EE components access
       the messaging service.
    4. If you’ve specified bean-managed transactions, then you may select the
       acknowledgment type—either Auto-Acknowledge or Duplicates-OK—
       from the Acknowledgement combo box. The Auto-Acknowledge type
       instructs the session to automatically acknowledge that the bean has con-
       sumed the message. The Duplicates-OK type instructs the session to lazily
162                                           A MESSAGE-DRIVEN BEAN EXAMPLE



                  acknowledge the delivery of messages; this type may result in duplicate
                  messages, but it reduces session overhead.
               5. In the JMS Message Selector field, you may enter a statement that filters
                  the messages received by the bean.




        Figure 7–2 Message Tab of           B JE eg a ss eM el p mi S


      deploytool Tips for JMS Clients
        For more information on JMS clients, please see the Java Message Service Tuto-
        rial:
        h   l mt h .x ed ni / la ir o tu t/ sm j /s tc u do rp /m o c. nu s .a va j/ / :p tt
                                          DEPLOYTOOL   TIPS FOR JMS CLIENTS                            163


Setting the Resource References
  1.   In the tree view, select the client’s node.
  2.   Select the Resource Refs tab.
  3.   Click Add.
  4.   In the Coded Name field, enter the name that matches the parameter of the
                method in the client’s code. For example, if the        parameter
                                                                   p u ko ol   pu ko o l
       is                                                       , the Coded Name
       yr ot ca F no it c en no Ce u eu Qy M /s mj /v n e/ pm oc : av aj
       should be                                   .
                      yr ot ca F no it c en no Ce u eu Q/ s mj
  5.   In the Type field, select the connection factory class that matches the des-
       tination type.
  6.   In the Authentication field, in most cases you will select Container. You
       would select Application if your code explicitly logs on to the messaging
       service.
  7.   In the Sharable field, make sure the checkbox is selected. This choice
       allows the container to optimize connections.
  8.   Enter strings in the User Name and Password fields. The authentication
       service of the J2EE SDK will prompt you for these fields when you run
       the client.

Setting the Resource Environment References
  1. Select the Resource Env. Refs tab.
  2. Click Add.
  3. In the Coded Name field, enter a name that matches the parameter of the
              call that locates the queue or topic. For example, if the
                                                         p u ko ol                         p uk oo l
     parameter is
       e ma N eu eu Q/ s mj /v n e/ pm oc : av aj     , the Coded Name should
     be                   .                em aN e ue uQ /s m j
  4. In the Type field, select the class that matches the destination type.

Specifying the JNDI Names
  1. In the tree view, select the application’s node.
164                                   A MESSAGE-DRIVEN BEAN EXAMPLE



         2. Select the JNDI Names tab and enter the appropriate names. For example,
            the                    discussed in this chapter uses the JNDI names
                p pA e ga ss e Me lp mi S
            shown in Table 7–1.


      Table 7–1 JNDI Names for the          p p Ae ga s se Me lp m iS   Application

       Component or Reference Name                           JNDI Name

       BJEegasseMelpmiS                                      eueuQyM/smj

       yrotcaFnoitcennoCeueuQyM/smj                          yrotcaFnoitcennoCeueuQ/smj

       emaNeueuQ/smj                                         eueuQyM/smj
                              8
                     Enterprise
                 JavaBeans™
              Query Language
                                                                    Dale Green



T   HE Enterprise JavaBeans™ Query Language (EJB™ QL) defines the queries
for the finder and select methods of an entity bean with container-managed per-
sistence. A subset of SQL92, EJB QL has extensions that allow navigation over
the relationships defined in an entity bean’s abstract schema. The scope of an
EJB QL query spans the abstract schemas of related entity beans that are pack-
aged in the same EJB JAR file.
You define EJB QL queries in the deployment descriptor of the entity bean. Typ-
ically, a tool will translate these queries into the target language of the underly-
ing data store. Because of this translation, entity beans with container-managed
persistence are portable—their code is not tied to a specific type of data store.
This chapter relies on the material presented in earlier chapters. For conceptual
information, see the section Container-Managed Persistence, page (53). For code
examples, see Chapter 6.

In This Chapter
          Terminology 166
          Simplified Syntax 167
                                                                                       165
166                                  ENTERPRISE JAVABEANS™ QUERY LANGUAGE


                  Example Queries 167
                       Simple Finder Queries 167
                       Finder Queries That Navigate to Related Beans 169
                       Finder Queries with Other Conditional Expressions 170
                       Select Queries 172
                  Full Syntax 173
                       BNF Grammar of EJB QL 173
                       BNF Symbols 176
                       FROM Clause 176
                       Path Expressions 179
                       WHERE Clause 182
                       SELECT Clause 190
                  EJB QL Restrictions 191



      Terminology
        The following list defines some of the terms referred to in this chapter.
            • Abstract schema: The part of an entity bean’s deployment descriptor that
              defines the bean’s persistent fields and relationships.
            • Abstract schema name: A logical name that is referenced in EJB QL que-
              ries. You specify an abstract schema name for each entity bean with con-
              tainer-managed persistence.
            • Abstract schema type: All EJB QL expressions evaluate to a type. If the
              expression is an abstract schema name, by default its type is the local inter-
              face of the entity bean for which the abstract schema name is defined.
            • Backus-Naur Form (BNF): A notation that describes the syntax of high-
              level languages. The syntax diagrams in this chapter are in BNF notation.
            • navigation: The traversal of relationships in an EJB QL expression. The
              navigation operator is a period.
            • path expression: An expression that navigates to a related entity bean.
            • persistent field: A virtual field of an entity bean with container-managed
              persistence; it is stored in a database.
            • relationship field: A virtual field of an entity bean with container-managed
              persistence; it identifies a related entity bean.
                                            SIMPLIFIED SYNTAX                                                167


Simplified Syntax
  This section briefly describes the syntax of EJB QL so that you can quickly
  move on to the section Example Queries, page (167). When you are ready to
  learn about the syntax in more detail, see the section Full Syntax, page (173).
  An EJB QL query has three clauses:                   ,
                                          MO R F T C EL ES    , and       . The
                                                                       E RE HW            and
                                                                                        T C EL ES
      clauses are required, but the
  MO R F                                           clause is optional. Here is the high-level
                                                       ER E HW
  BNF syntax of an EJB QL query:

       ] es ua lc _ er eh w [ es ua l c_ mo r f es ua l c_ tc el e s = : : LQ B J E

  The          clause defines the types of the objects or values returned by the
           T C EL ES
  query. A return type is either a local interface, a remote interface, or a persistent
  field.
  The  M OR Fclause defines the scope of the query by declaring one or more identifi-
  cation variables, which may be referenced in the            and
                                                               T CE LE Sclauses. An
                                                                             E R EH W
  identification variable represents one of the following elements:
       • The abstract schema name of an entity bean
       • A member of a collection that is the multiple side of a one-to-many rela-
         tionship
  The  E RE HWclause is a conditional expression that restricts the objects or values
  retrieved by the query. Although optional, most queries have a          clause.E RE H W


Example Queries
  The following queries are from the            entity bean of the
                                               BJ E re ya lP                                p pA re t so R
  J2EE™ application, which is documented in the Chapter 6. To see the relation-
  ships between the beans of the        , see Figure 6–1 (page 121).
                                       p p Ar et so R


  Simple Finder Queries
  If you are unfamiliar with EJB QL, these simple queries are a good place to start.

  Example 1

       )p ( TC EJ B O TC EL E S
            p re y al P MO R F
168                                      ENTERPRISE JAVABEANS™ QUERY LANGUAGE



      Data retrieved: All players.
      Finder method:    ) (l la d ni f
      Description: The       clause declares an identification variable named , omit-
                          M O RF                                                              p
      ting the optional keyword . If the
                                      SA     keyword were included, the clause would
                                                  SA
      be written as follows:

          p SA r e ya lP M O RF

      The re y al Pelement is the abstract schema name of the          B J Er ey al P     entity bean.
      Because the bean defines the             method in the
                                           l la dn i f          em oH r ey al Pl a co L          inter-
      face, the objects returned by the query have the                           type.
                                                                               r ey a lP la co L
      See also: Identification Variables, page (177)

      Example 2

          ) p( T CE JB O T CN IT S ID T CE L ES
                            p r e ya lP M O RF
                 1? = no it is o p. p ER E HW

      Data retrieved: The players with the position specified by the finder method’s
      parameter.
      Finder method:     ) no it i so p g ni rt S( n oi ti s oP yB dn i f
      Description: In a           clause, the
                           TC EL ES                            keyword must precede a stand-
                                                           T C EJ BO
      alone identification variable such as . The T CN IT S ID      keyword eliminates dupli-
                                                                     p
      cate values.
      The E RE HW  clause restricts the players retrieved by checking their          ,a  n oi t is op
      persistent field of the
                          B JE re y al P   entity bean. The    element denotes the input
                                                                    1?
      parameter of the                      method.
                         n oi t is oP yB d ni f
      See also: Input Parameters, page (183),                     DISTINCT          and     OBJECT
      Keywords, page (191)

      Example 3

                          ) p( T CE JB O T CN IT S ID T CE L ES
                                            p r e ya lP M O RF
          2 ? = e ma n .p D NA 1? = no it is o p. p ER E HW

      Data retrieved: The players with the specified position and name.
                                                  EXAMPLE QUERIES                                        169


Finder method:         ) em an gn ir tS ,n oi t is op g n ir tS (e m aN dn A no it is o Py Bd n if
Description: The           and       elements are persistent fields of the
                                             e ma n
                                               no i ti so p                                   ya lP
      entity bean. The
B JE r e                     clause compares the values of these fields with the
                                            E R EH W
parameters of the                           method. EJB QL denotes an input
                         em aN dn A no it i so Py Bd n if
parameter with a question mark followed by an integer. The first input parameter
is , the second is , and so forth.
    1?                     2?


Finder Queries That Navigate to Related Beans
In EJB QL, an expression can traverse—or navigate—to related beans. These
expressions are the primary difference between EJB QL and SQL. EJB QL navi-
gates to related beans, whereas SQL joins tables.

Example 4

             )p (T C EJ BO T C NI TS I D TC EL E S
     t SA )s ma et . p( N I , p re y al P MO R F
                         1 ? = y ti c .t E RE H W

Data retrieved: The players whose teams belong to the specified city.
Finder method:         ) yt i c gn i rt S( yt i Cy Bd n if
Description: The        clause declares two identification variables: and . The
                         M OR F                                                        p     t
p variable represents the            entity bean, and the variable represents the
                                   B JE re ya l P                        t
related          beans. The declaration for references the previously declared
       B JE m ae T                                                t
p variable. The
     NI            keyword signifies that          is a collection of related beans.
                                                              sm ae t
The           expression navigates from a
           s m ae t. p                                  bean to its related
                                                        B JE re y al P                     B JE ma e T
beans. The period in the          expression is the navigation operator.
                                   sm ae t. p
In the         clause, the period preceding the persistent variable
           ER E HW                                                         is a delim-
                                                                                 y ti c
iter, not a navigation operator. Strictly speaking, expressions can navigate to
relationship fields (related beans), but not to persistent fields. To access a persis-
tent field, an expression uses the period as a delimiter.
Expressions may not navigate beyond (or further qualify) relationship fields that
are collections. In the syntax of an expression, a collection-valued field is a ter-
minal symbol. Because the           field is a collection, the
                                       s ma e t                     clause cannot
                                                                             E RE HW
specify                  —an illegal expression.
             y t ic .s m ae t. p
See also: Path Expressions, page (179)
170                                     ENTERPRISE JAVABEANS™ QUERY LANGUAGE



      Example 5

                    ) p( T CE JB O T CN IT S ID T CE L ES
           t S A ) sm ae t .p ( N I ,p r e ya lP M O RF
                              1? = eu ga e l. t ER E HW

      Data retrieved: The players that belong to the specified league.
      Finder method:     )e ug a el e ug a eL la c oL (e ug a eL yB d ni f
      Description: The expressions in this query navigate over two relationships. The
                expression navigates the
        sm ae t .p                                   -          relationship, and the
                                                 BJ Em a eT B JE re ya l P
                 expression navigates the
      e ug ae l .t                                            relationship.
                                                  BJ E eu ga e L BJ Em a eT
      In the other examples, the input parameters are          objects, but in this exam-
                                                                     g ni rt S
      ple the parameter is an object whose type is a                interface. This type
                                                              e ug a eL la co L
      matches the          relationship field in the comparison expression of the
                     eu ga el                                                                  ER EH W
      clause.

      Example 6

                    ) p( T CE JB O T CN IT S ID T CE L ES
           t S A ) sm ae t .p ( N I ,p r e ya lP M O RF
                    1 ? = t ro p s. eu ga e l. t ER E HW

      Data retrieved: The players who participate in the specified sport.
      Finder method:     )t ro p s gn i rt S( tr o pS yB d ni f
      Description: The         persistent field belongs to the
                          tr o ps                                          bean. To reach
                                                                       BJ Ee u ga eL
      the
      t ro ps   field, the query must first navigate from the                  bean to the
                                                                   B J Er ey al P
               bean (
        BJ Em a eT            ) and then from the
                        s ma et .p                           bean to the
                                                          BJ Ee u ga eL               bean
                                                                                     B JE ma e T
      (         ). Because the
      eu g ae l. t                       relationship field is not a collection, it may be
                                     e u ga el
      followed by the        persistent field.
                         t ro ps


      Finder Queries with Other Conditional Expressions
      Every         clause must specify a conditional expression, of which there are
              ER EH W
      several kinds. In the previous examples, the conditional expressions are compar-
      ison expressions that test for equality. The following examples demonstrate
      some of the other kinds of conditional expressions. For descriptions of all condi-
      tional expressions, see the section WHERE Clause, page (182).
                                            EXAMPLE QUERIES                                    171


Example 7

             )p ( TC EJ B O TC EL E S
                  p re y al P MO R F
    Y T PM E SI sm ae t .p E RE H W

Data retrieved: All players who do not belong to a team.
Finder method:    ) (m ae Tn O to Nd n if
Description: The         relationship field of the
                    sm ae t                            BJ E re ya lP   bean is a collection.
If a player does not belong to a team, then the                collection is empty and the
                                                                s m ae t
conditional expression is      .
                              E UR T
See also: Empty Collection Comparison Expressions, page (186)

Example 8

             )p (T C EJ BO T C NI TS I D TC EL E S
                               p re y al P MO R F
    2? D N A 1? N E EW TE B y ra la s .p E RE H W

Data retrieved: The players whose salaries fall within the range of the specified
salaries.
Finder method:    ) hg i h el b uo d ,w o l el bu o d( eg n aR yr al a Sy Bd n if
Description: This
            NE E WT EB      expression has three arithmetic expressions: a persis-
tent field (        ) and the two input parameters ( and ). The following
                    y ra la s .p                                1?         2?
expression is equivalent to the         expression:
                                       N EE W TE B

    2 ? =< yr al as . p DN A 1 ? => yr al as . p

See also: BETWEEN Expressions, page (184)

Example 9

                          ) 1p ( T C EJ BO T C NI TS I D TC EL E S
                            2p r e ya lP , 1 p re y al P MO R F
    1? = em an .2 p D NA yr al as . 2p > y r al as . 1p E RE H W

Data retrieved: All players whose salaries are higher than the salary of the player
with the specified name.
Finder method:    )e ma n g ni rt S (y ra l aS re hg i Hy Bd n if
172                                       ENTERPRISE JAVABEANS™ QUERY LANGUAGE



      Description: The     clause declares two identification variables ( and ) of
                             M OR F                                                        1p       2p
      the same type (       ). Two identification variables are needed because the
                            re ya lP
            clause compares the salary of one player ( ) with that of the other play-
       ER E HW                                                      2p
      ers ( ).
      1p
      See also: Identification Variables, page (177)

      Select Queries
      The queries in this section are for select methods. Unlike finder methods, a select
      method may return persistent fields or other entity beans.

      Example 10

                     eu g ae l. t T CN IT S ID T CE L ES
          t S A ) sm ae t .p ( N I ,p r e ya lP M O RF
                                       1? = p ER E HW

      Data retrieved: The leagues to which the specified player belongs.
      Select Method:       ) re ya lp re ya l Pl ac oL ( se ug ae L tc el e Sb je
      Description: The return type of this query is the abstract schema type of the
      BJ Ee ug a eLentity bean. This abstract schema type maps to the                    e ug a eL la c oL
            interface. Because the expression
             e m oH                                     is not a stand-alone identifica-
                                                        e ug ae l .t
      tion variable, the        keyword is omitted.
                             T CE JB O
      See also: SELECT Clause, page (190)

      Example 11

            t r op s. eu g ae l. t T CN IT S ID T CE L ES
          t S A ) sm ae t .p ( N I ,p r e ya lP M O RF
                                        1? = p ER E HW

      Data retrieved: The sports that the specified player participates in.
      Select Method:       )r ey al p r ey a lP la co L (s tr op S tc el e Sb je
      Description: This query returns a            g ni r tS   named   tr op s   , which is a persistent
      field of the          entity bean.
                      B JE e ug ae L
                            m r et _l a no it id n oc R O n oi ss e rp xe _l a no it i dn oc
                              | m re t _l an oi t id no c = :: n o is se rp x e_ la n oi ti dn o c
                              n oi ss e rp xe _l a no it i dn oc E R EH W =: : e su a lc _e re h w
                                            } )e l ba ir a v_ no it a ci fi tn e di ( T C EJ BO
                                            | n o is se r px e_ ht a p_ de ul a v_ el g ni s{
                                              ] T C NI TS I D [ T CE L ES = :: es ua l c_ tc el e s
                                                    d le i f_ rm c_ d eu la v_ n oi tc e ll oc
              * ]. d le if _r m c_ de u la v_ el g ni s[ . el ba ir a v_ no it a ci fi t ne di
                                           =: : n oi ss e rp xe _h t ap _d eu l av _n o it ce ll o c
                                                           dl ei f_ r mc _d eu l av _e l gn is
              * ]. d le if _r m c_ de u la v_ el g ni s[ . el ba ir a v_ no it a ci fi t ne di
                                                         = :: n oi t ag iv an _ de ul a v_ el gn i s
                                                       n oi ta gi v an _d eu l av _e l gn is
                                     | d le if _ pm c. } el ba ir a v_ no it a ci fi t ne di
                                                  | n o it ag iv a n_ de ul a v_ el g ni s{
                                               = :: n o is se rp x e_ ht ap _ de ul a v_ el gn i s
                                     r ei fi tn e di ] S A [ e ma n _a me hc s _t ca r ts ba
                                                    =: : n oi ta r al ce d_ e lb ai r av _e gn a r
          r e if it n ed i ] S A [ )n o is se rp x e_ ht a p_ de ul a v_ no it c el lo c ( NI
                                                 = :: n o it ar al c ed _r eb m em _n o it ce ll o c
                                                    no i ta ra lc e d_ el ba i ra v_ e gn ar
                                            | n oi ta r al ce d_ r eb me m_ n oi tc e ll oc
                                       =: : no i ta ra l ce d_ el b ai ra v_ n oi ta c if it ne d i
                                *] no i ta ra lc e d_ el b ai ra v_ n oi ta ci f it ne d i ,[
             no it a ra lc ed _ el ba i ra v_ no i ta ci f it ne di MO RF = : : es u al c_ mo r f
                    ]e su al c _e re h w[ e su a lc _m o rf e su a lc _t ce l es = : : LQ B J E
                                                 Here is the entire BNF diagram for EJB QL:
                                                           BNF Grammar of EJB QL
      quotes the Enterprise JavaBeans Specification.
      Beans Specification. Much of the following material paraphrases or directly
      This section discusses the EJB QL syntax, as defined in the Enterprise Java-
                                                                                     Full Syntax
173                                            FULL SYNTAX
  | no i ss er px e _n ae b _y ti tn e } > < | = { eu la v _n ae b_ y ti tn e
| no is s er px e_ e mi te t ad } < | > | > < | = { e u la v_ em i te ta d
                 | }n oi s se rp xe _ na el o ob } >< | = { e ul av _n a el oo b
                      | n o is se rp x e_ gn i rt s }> < |= { eu la v_ g ni rt s
                                                   = :: no is s er px e_ n os ir ap m oc
     no i ss er px e _h ta p _d eu la v _n oi t ce ll oc ] F O [ RE BM EM ] T ON [
                                                           } re t em ar ap _ tu pn i
   | el b ai ra v_ n oi ta c if it ne d i | n oi ta gi v an _d e ul av _e l gn is {
                                         = :: no is se r px e_ r eb me m_ n oi tc el l oc
          YT PM E ] TO N [ SI n oi s se rp x e_ ht ap _ de ul a v_ no it c el lo c
                         = : : no is s er px e _n os ir a pm oc _ no it ce l lo c_ yt p me
                  L L UN ] T ON [ SI no is s er px e_ h ta p_ d eu la v_ e lg ni s
                                         = : : no is s er px e _n os ir a pm oc _l l un
       ] r et ca ra h c ep a cs e EP A CS E [ eu la v_ n re tt a p EK IL ] T ON [
                                       no is s er px e_ h ta p_ d eu la v_ e lg ni s
                                                             =: : n oi ss e rp xe _e k il
             ) *] l ar et i l_ gn ir t s ,[ la re ti l _g ni r ts ( NI ] T ON [
                                       no is s er px e_ h ta p_ d eu la v_ e lg ni s
                                                                = :: n oi s se rp xe _ ni
            n oi ss e rp xe _ ci te mh t ir a D NA n oi s se rp x e_ ci te m ht ir a
                               N EE WT E B ] T O N [ n oi s se rp x e_ ci te m ht ir a
                                                          = :: n o is se rp x e_ ne ew t eb
                                        n oi s se rp xe _ re bm e m_ no it c el lo c
                      | n o is se rp x e_ no s ir ap mo c _n oi t ce ll oc _ yt pm e
                                        | n o is se rp x e_ no s ir ap mo c _l lu n
                                                             | n oi ss er p xe _n i
                                                          | no i ss er px e _e ki l
                                                     | n oi ss e rp xe _n e ew te b
                                                | n oi s se rp x e_ no si r ap mo c
                                                  =: : n oi ss e rp xe _d n oc _e lp m is
         ) no is se r px e_ l an oi ti d no c( | no is s er px e _d no c_ e lp mi s
                                                     = : : yr a mi rp _l a no it id n oc
                           y ra mi rp _ la no i ti dn oc = :: ts et _l a no it id n oc
                  t s et _l a no it id n oc ] TO N [ = :: r o tc af _l a no it id n oc
                        ro t ca f_ la n oi ti d no c DN A m re t _l an oi t id no c
                           | r ot ca f _l an o it id no c = :: mr et _l a no it id n oc
                ENTERPRISE JAVABEANS™ QUERY LANGUAGE                                          174
                                                     = :: sg ni rt s _g ni nr u te r_ s no it cn u f
      r et em a ra p_ t up ni | eu la v _n ae b_ y ti tn e = :: n o is se rp x e_ na e b_ yt it n e
                  el b ai ra v_ n oi ta c if it ne d i | n oi ta gi v an _d eu l av _e l gn is
                                                                    = :: e ul a v_ na e b_ yt it n e
                                                          r et em ar a p_ tu pn i | l a re ti l
                  | n oi ss er p xe _h t ap _d eu l av _e l gn is = : : no is s er px e _n ae lo o b
                            no i ss er p xe _h ta p _d eu l av _e lg n is = :: eu la v _n ae lo o b
               re te m ar ap _t u pn i | e ul av _ em it e ta d =: : n oi ss e rp xe _ em it et a d
                           n oi s se rp x e_ ht ap _ de ul a v_ el gn i s =: : e ul av _ em it et a d
                  s g ni rt s_ g ni nr u te r_ sn o it cn u f | )n o is se rp x e_ gn i rt s(
        | l a re ti l | n oi s se rp x e_ ht ap _ de ul a v_ el gn i s =: : y ra mi r p_ gn ir t s
                n oi s se rp xe _ tu pn i | y ra m ir p_ g ni rt s = :: n oi s se rp x e_ gn ir t s
                                                     s gn i rt s_ gn i nr ut er _ sn oi t cn uf
                           | n o is se r px e_ ht a p_ de u la v_ el g ni s =: : e ul a v_ gn ir t s
                       s ci re m un _g n in ru te r _s no i tc nu f | r et em a ra p_ t up ni
                                         | )n oi s se rp x e_ ci te m ht ir a( | la r et il
                  | n oi ss er p xe _h t ap _d eu l av _e l gn is = : : yr am i rp _c i te mh ti r a
                         yr am i rp _c i te mh ti r a }    | + { = :: r ot c af _c i te mh ti r a
                            ro t ca f_ c it em ht i ra } / | * { m re t_ c it em h ti ra
                                         | ro tc a f_ ci t em ht ir a = :: m r et _c i te mh ti r a
                      mr et _c i te mh t ir a }     | + { no is s er px e_ c it em h ti ra
                                  | m r et _c it e mh ti r a =: : n oi ss er p xe _c i te mh ti r a
                                  n oi s se rp xe _ ci te m ht ir a = :: n oi s se rp x e_ ra la c s
                                                          > < | =< | < | = > | > | =
                                                                =: : r ot ar e po _n o si ra pm o c
                               n oi ss e rp xe _r a la cs =: : ro t an gi se d _e ul a v_ el gn i s
                                                    sc ir e mu n_ gn i nr ut er _ sn oi t cn uf
                     | n oi ss e rp xe _ ht ap _d e ul av _ el gn is =: : eu l av _c i te mh ti r a
                                                            ro ta ng i se d_ eu l av _e l gn is
                                       r ot ar ep o _n os i ra pm oc eu la v_ c it em h ti ra
175                                             FULL SYNTAX
176                                        ENTERPRISE JAVABEANS™ QUERY LANGUAGE


                           | )n o is se r px e_ gn i rt s , no is se r px e_ g ni rt s( T AC NO C
                   ,n o is se rp x e_ ci t em ht ir a , no i ss er px e _g ni r ts (G NI R TS BU S
                                                                )n oi s se rp x e_ ci te m ht ir a

                                         =: : sc ir em u n_ gn i nr ut er _ sn oi tc n uf
                                         | ) no is se r px e_ g ni rt s( H TG NE L
                                            , no is se r px e_ g ni rt s( E TA CO L
             | ) ] no is s er px e_ c it em h ti ra , [ no is s er px e_ g ni rt s
                                       | ) n oi ss er p xe _c i te mh ti r a( SB A
                                         )n o is se rp x e_ ci t em ht ir a (T RQ S

      BNF Symbols
      Table 8–1 describes the BNF symbols used in this chapter.


      Table 8–1 BNF Symbol Summary

       Symbol              Description

                           The element to the left of the symbol is defined by the con-
       ::=
                           structs on the right

       *                   The preceding construct may occur zero or more times

       {...}               The constructs within the curly braces are grouped together

       [...]               The constructs within the square brackets are optional

       |                   An exclusive OR

       BOLD-               A keyword (although capitalized in the BNF diagram, key-
       FACE                words are not case sensitive)

                           A whitespace character can be a space, horizontal tab, or
       Whitespace
                           form feed




      FROM Clause
      The       clause defines the domain of the query by declaring identification vari-
               MO RF
      ables. Here is the syntax of the    clause:
                                               MO R F
      n oi t ar al ce d _e lb a ir av _n o it ac i fi tn ed i M OR F = :: e s ua lc _m o rf
                         * ]n o it ar al c ed _e l ba ir av _ no it a ci fi tn e di , [

      = :: n o it ar a lc ed _e l ba ir a v_ no it a ci fi tn e di
                                            FULL SYNTAX                                                 177


      | n oi ta r al ce d_ r eb me m_ n oi tc e ll oc
             no i ta ra lc e d_ el ba i ra v_ e gn ar

                                       = :: n o it ar al c ed _r eb m em _n o it ce ll o c
r e if it n ed i ] S A [ )n o is se rp x e_ ht a p_ de ul a v_ no it c el lo c ( NI

               =: : n oi ta r al ce d_ e lb ai r av _e gn a r
r ei fi tn e di ] S A [ e ma n _a me hc s _t ca r ts ba

Identifiers
An identifier is a sequence of one or more characters. The first character must be
a valid first character (letter, , ) in an identifier of the Java™ programming
                                      _ $
language (hereafter in this chapter called simply “Java”). Each subsequent char-
acter in the sequence must be a valid non-first character (letter, digit, , ) in a           _ $
Java identifier. (For details, see the J2SE™ API documentation of the                    va Js i
                       and
tr a tS re i fi tn ed I a                             methods of the
                                t ra P re if i tn ed Ia v aJ si                        r et ca r ah C
class.) The question mark ( ) is a reserved character in EJB QL and cannot be
                                                           ?
used in an identifier. Unlike a Java variable, an EJB QL identifier is not case sen-
sitive.
An identifier cannot be the same as an EJB QL keyword:
     REBMEM      DNA
        TON       SA
       LLUN NEEWTEB
     TCEJBO TCNITSID
         FO    YTPME
         RO    ESLAF
     TCELES     MORF
       EURT       NI
    NWONKNU       SI
      EREHW     EKIL
EJB QL keywords are also reserved words in SQL. In the future, the list of EJB
QL keywords may expand to include other reserved SQL words. The Enterprise
JavaBeans™ Specification recommends that you not use other reserved SQL
words for EJB QL identifiers.

Identification Variables
An identification variable is an identifier declared in the    clause. Although
                                                                        M OR F
the         and
    T CE L ES          clauses may reference identification variables, they can-
                    E RE H W
not declare them. All identification variables must be declared in the                        M OR F
clause.
Since an identification variable is an identifier, it has the same naming conven-
tions and restrictions as an identifier. For example, an identification variable is
178                                   ENTERPRISE JAVABEANS™ QUERY LANGUAGE



      not case sensitive and it cannot be the same as an EJB QL keyword. (See the pre-
      vious section for more naming rules.) Also, within a given EJB JAR file, an
      identifier name must not match the name of any entity bean or abstract schema.
      The  MO R Fclause may contain multiple declarations, separated by commas. A
      declaration may reference another identification variable that has been previ-
      ously declared (to the left). In the following    clause, the variable refer-
                                                           M OR F                         t
      ences the previously declared variable :    p

          t S A ) sm ae t .p ( N I ,p r e ya lP M O RF

      Even if an identification variable is not used in the       clause, its declaration
                                                                    E RE HW
      can affect the results of the query. For an example, compare the next two queries.
      The following query returns all players, whether or not they belong to a team:

          )p (T CE J BO T CE L ES
              p r e ya lP M O RF

      In contrast, because the next query declares the              t   identification variable, it
      fetches all players that belong to a team:

                                 )p (T CE J BO T CE L ES
          t S A ) sm ae t .p ( N I ,p r e ya lP M O RF

      The following query returns the same results as the preceding query, but the
            clause makes it easier to read:
      ER E HW

                       )p (T CE J BO T CE L ES
                           p r e ya lP M O RF
          YT PM E T ON SI s ma e t. p ER E HW

      An identification variable always designates a reference to a single value, whose
      type is that of the expression used in the declaration. There are two kinds of dec-
      larations: range variable and collection member.

      Range Variable Declarations
      To declare an identification variable as an abstract schema type, you specify a
      range variable declaration. In other words, an identification variable can range
      over the abstract schema type of an entity bean. In the following example, an
      identification variable named represents the abstract schema named
                                        p                                          :   re y al P

          p r e ya lP M O RF
                                           FULL SYNTAX                                       179


A range variable declaration may include the optional            SA   operator:

     p S A re y al P MO R F

In most cases, to obtain objects a query navigates through the relationships with
path expressions. But for those objects that cannot be obtained by navigation,
you can use a range variable declaration to designate a starting point (or root).
If the query compares multiple values of the same abstract schema type, then the
MO R F clause must declare multiple identification variables for the abstract
schema:

     2p r e ya lP , 1 p re y al P MO R F

For a sample of such a query, see Example 9 (page 171).

Collection Member Declarations
In a one-to-many relationship, the multiple side consists of a collection of entity
beans. An identification variable may represent a member of this collection. To
access a collection member, the path expression in the variable’s declaration
navigates through the relationships in the abstract schema. (For more informa-
tion on path expressions, see the following section.) Because a path expression
may be based on another path expression, the navigation can traverse several
relationships. See Example 6 (page 170).
A collection member declaration must include the            NI   operator, but it may omit
the optional  operator.
               SA
In the following example, the entity bean represented by the abstract schema
named          has a relationship field called
         re ya l P                                . The identification variable
                                                   s ma e t
named represents a single member of the
                 t                              collection.
                                                      sm a et

     t SA )s ma et . p( N I , p re y al P MO R F

Path Expressions
Path expressions are important constructs in the syntax of EJB QL, for several
reasons. First, they define navigation paths through the relationships in the
abstract schema. These path definitions affect both the scope and the results of a
query. Second, they may appear in any of the three main clauses of an EJB QL
query (        ,      ,     ). Finally, although much of EJB QL is a subset of
         M OR F ER E HW TC EL ES
SQL, path expressions are extensions not found in SQL.
180                                       ENTERPRISE JAVABEANS™ QUERY LANGUAGE



      Syntax
      There are two types of path expressions: single-valued and collection-valued.
      Here is the syntax for path expressions:

                      =: : n oi ss er p xe _h t ap _d eu l av _e lg n is
                         | n oi ta gi v an _d e ul av _e l gn is {
            | dl ei f _p mc . }e lb ai r av _n o it ac if i tn ed i
                              no it ag i va n_ d eu la v_ e lg ni s

                                                       =: : no i ta gi v an _d eu l av _e lg n is
            *] . dl ei f_ r mc _d e ul av _e l gn is [ .e lb ai r av _n o it ac if i tn ed i
                                                        d le if _ rm c_ d eu la v_ e lg ni s

                                        = :: no is s er px e_ h ta p_ d eu la v_ n oi tc el l oc
            *] . dl ei f_ r mc _d e ul av _e l gn is [ .e lb ai r av _n o it ac if i tn ed i
                                                  dl e if _r mc _ de ul a v_ no it c el lo c

      In the preceding diagram, the                 element represents a persistent field,
                                             dl ei f_ p mc
      and the
      dl e if _r mc            element designates a relationship field. The term
                       qualifies the relationship field as the single side of a one-to-one
             d eu l av _e lg n is
      or one-to-many relationship; the term                            designates it as the
                                                        d eu l av _n o it ce ll o c
      multiple (collection) side of a relationship.
      The period (.) in a path expression serves two functions. If a period precedes a
      persistent field, it is a delimiter between the field and the identification variable.
      If a period precedes a relationship field, it is a navigation operator.

      Examples
       In the following query, the        clause contains a single-valued expression.
                                           ER E HW
      The is an identification variable, and
            p                                       is a persistent field of
                                                       yr al as                  .           r ey al P

                     ) p( T CE JB O T CN IT S ID T CE L ES
                                       p r e ya lP M O RF
            2 ? D NA 1 ? N EE WT E B yr al a s. p ER E HW

      The   E RE H W  clause of the next example also contains a single-valued expression.
      The       is an identification variable,
                  t                                   is a single-valued relationship field,
                                                eu ga el
      and   t r op s is a persistent field of     .eu g ae l

                     ) p( T CE JB O T CN IT S ID T CE L ES
            t S A ) sm ae t .p ( N I ,p r e ya lP M O RF
                     1 ? = t ro p s. eu ga e l. t ER E HW
                                             FULL SYNTAX                                                181


In the next query, the         clause contains a collection-valued expression. The
                          E R EH W
p is an identification variable, and       designates a collection-valued relation-
                                         s ma e t
ship field.

     )p (T C EJ BO T C NI TS I D TC EL E S
                       p re y al P MO R F
         Y T PM E SI sm ae t .p E RE H W

Expression Types
The type of an expression is the type of the object represented by the ending ele-
ment, which can be one of the following:
     • Persistent field
     • Single-valued relationship field
     • Collection-valued relationship field
For example, the type of the expression      y ra la s. p         is   e lb uo d   because the termi-
nating persistent field (     ) is a
                           y ra l as                    .
                                                      e l bu od
In the expression  s ma et .p, the terminating element is a collection-valued rela-
tionship field (       ). This expression’s type is a collection of the abstract
                         s ma et
schema type named  m ae T   . Because         is the abstract schema name for the
                                              ma eT
         entity bean, this type maps to the bean’s local interface,
B JE ma e T                                                                   . For  ma eT l ac oL
more information on the type mapping of abstract schemas, see the section
Return Types, page (190).

Navigation
A path expression enables the query to navigate to related entity beans. The ter-
minating elements of an expression determine whether navigation is allowed. If
an expression contains a single-valued relationship field, the navigation may
continue to an object that is related to the field. However, an expression cannot
navigate beyond a persistent field or a collection-valued relationship field. For
example, the expression                              is illegal, since
                                    t r op s. eu g ae l. s ma et .p        is a col-
                                                                                   s ma et
lection-valued relationship field. To reach the
                                t ro p s                 field, the    clause could      MO RF
define an identification variable named for the
                             sm ae t           t            field:

     t )s m ae t. p( NI , p S A re y al P MO R F
       re c co s' = tr op s. e ug ae l .t E RE H W  '
182                                          ENTERPRISE JAVABEANS™ QUERY LANGUAGE



      WHERE Clause
      The  ER E HW  clause specifies a conditional expression that limits the values
      returned by the query. The query returns all corresponding values in the data
      store for which the conditional expression is        . Although usually specified,
                                                                     EU R T
      the ER EH W  clause is optional. If the         clause is omitted, then the query
                                                          E R EH W
      returns all values. The high-level syntax for the        clause follows:
                                                                       E R EH W

          no is s er px e_ l an oi t id no c E RE HW =: : es u al c_ er e hW

      Literals
      There are three kinds of literals: string, numeric, and boolean.

      String Literals
      A string literal is enclosed in single quotes:

          ' ek u D'

      If a string literal contains a single quote, you indicate the quote with two single
      quotes:

          's '' ek u D'

      Like a Java     g ni r tS   , a string literal in EJB QL uses the Unicode character encod-
      ing.

      Numeric Literals
      There are two types of numeric literals: exact and approximate.
      An exact numeric literal is a numeric value without a decimal point, such as 65,
      −233, +12. Using the Java integer syntax, exact numeric literals support numbers
      in the range of a Java     .  gn o l
      An approximate numeric literal is a numeric value in scientific notation, such as
      57., −85.7, +2.1. Using the syntax of the Java floating point literal, approximate
      numeric literals support numbers in the range of a Java          .          e lb u od

      Boolean Literals
      A boolean literal is either        EU RT   or   ES L AF   . These keywords are not case sensitive.
                                          FULL SYNTAX                                   183


Input Parameters
An input parameter is designated by a question mark ( ) followed by an integer.
                                                                     ?
For example, the first input parameter is , the second is , and so forth.
                                                   1?                    2?
The following rules apply to input parameters:
    • They can be used only in a          clause.
                                         ER E HW
    • Their use is restricted to a single-valued path expression within a condi-
      tional expression.
    • They must be numbered, starting with the integer 1.
    • The number of input parameters in the           clause must not exceed the
                                                          ER E HW
      number of input parameters in the corresponding finder or select method.
    • The type of an input parameter in the        clause must match the type of
                                                        ER EH W
      the corresponding argument in the finder or select method.

Conditional Expressions
A E R EH Wclause consists of a conditional expression, which is evaluated from left
to right within a precedence level. You may change the order of evaluation with
parentheses.
Here is the syntax of a conditional expression:

      | m re t _l an oi t id no c = :: n o is se rp x e_ la n oi ti dn o c
    m r et _l a no it id n oc R O n oi ss e rp xe _l a no it i dn oc

       | ro tc af _ la no i ti dn oc =: : mr e t_ la n oi ti dn o c
    r ot c af _l an o it id n oc D NA mr et _l a no it i dn oc

    ts e t_ la n oi ti dn o c ] T ON [ = : : ro tc a f_ la n oi ti dn o c

    y r am ir p_ l an oi t id no c = : : ts e t_ la n oi ti dn o c

                                                  =: : y ra mi r p_ la n oi ti dn o c
    ) n oi ss er p xe _l a no it id n oc ( | n oi ss e rp xe _d n oc _e l pm is

                               = :: n o is se rp x e_ dn o c_ el pm i s
                              | no is s er px e_ n os ir a pm oc
                                  | n o is se rp x e_ ne e wt eb
                                       | n oi ss e rp xe _ ek il
                                          | n oi s se rp x e_ ni
                      | no i ss er px e _n os ir a pm oc _ ll un
    | no i ss er px e _n os i ra pm oc _ no it ce l lo c_ y tp me
                      no is s er px e_ r eb me m_ n oi tc e ll oc
184                                      ENTERPRISE JAVABEANS™ QUERY LANGUAGE



      Operators and Their Precedence
      Table 8–2 lists the EJB QL operators in order of decreasing precedence.


      Table 8–2 EJB QL Operator Precedence

       Type           Precedence Order

       Navigation     .   (a period)

       Arithmetic       +  (unary)
                      / *  (multiplication and division)
                      + - (addition and subtraction)

       Comparison      =
                       >
                      =>
                       <
                      =<
                      ><   (not equal)

       Logical        TON
                      DNA
                       RO



      BETWEEN Expressions
      A           expression determines whether an arithmetic expression falls within
        N E EW TE B
      a range of values. The syntax of the        expression follows:
                                                  NE E WT EB

                                                        = :: n o is se rp x e_ ne ew t eb
                             N EE WT E B ] T O N [ n oi s se rp x e_ ci te m ht ir a
          n oi ss e rp xe _ ci te mh t ir a D NA n oi s se rp x e_ ci te m ht ir a

      These two expressions are equivalent:

               9 1 D NA 51 N EE W TE B eg a .p
          9 1 =< eg a. p D NA 5 1 = > eg a .p

      The following two expressions are also equivalent:

          9 1 DN A 5 1 N EE WT EB TO N eg a .p
              91 > eg a .p R O 5 1 < eg a .p
                                           FULL SYNTAX                                                  185


If an arithmetic expression has a          L LU N   value, then the value of the          N EE WT E B
expression is unknown.

IN Expressions
An  NI expression determines whether or not a string belongs to a set of string lit-
erals. Here is the syntax of the expression:
                                      NI

                                                        = :: no is s er px e_ n i
                               n oi ss e rp xe _h t ap _d eu l av _e l gn is
     ) * ]l a re ti l _g ni rt s , [ l ar et il _ gn ir ts ( N I ] TO N [

The single-valued path expression must have a         value. If the single-val-
                                                           gn ir t S
ued path expression has a       value, then the value of the
                                  LL UN                          expression isNI
unknown.
In the following example, if the country is         KU   the expression is   EU RT   . If the coun-
try is      it is
         ur eP       .
                   E S LA F

     )' e cn ar F ' ,' SU ' , 'K U' ( N I y rt nu oc . o

LIKE Expressions
A  E K ILexpression determines whether a wildcard pattern matches a string. Here
is the syntax:

                                                          = :: n o is se r px e_ ek i l
                                    n oi ss e rp xe _h t ap _d eu l av _e l gn is
     ]r e tc ar ah c e pa c se E PA C SE [ e ul av _n r et ta p E KI L ] TO N [

The single-valued path expression must have a                value. If this value is
                                                             g n ir tS
LL U N, then the value of the      expression is unknown. The pattern value is a
                                  E KI L
string literal that may contain wildcard characters. The underscore (_) wildcard
character represents any single character. The percent ( ) wildcard character rep-
                                                                   %
resents zero or more characters. The           clause specifies an escape character
                                             EP A CS E
for the wildcard characters in the pattern value.
186                                      ENTERPRISE JAVABEANS™ QUERY LANGUAGE



      Table 8–3 shows some sample      expressions. The
                                              E KI L           and        columns
                                                                          EU R T         ES L AF
      indicate the value of the expression for a single-valued path expression.
                                    E KI L


      Table 8–3    EK I L   Expression Examples

        Expression                                              TRUE                 FALSE

       '3%21' EKIL enohp.sserdda                                  '321'              '4321'
                                                                '39921'

       'es_l' EKIL drow.ecnetnesa                               'esol'               'esool'

       '\' EPACSE ’%_\' EKIL derocsrednu.drowa                  'oof_'               'rab'

                                                                                       '321'
       '3%21' EKIL TON enohp.sserdda                            4321
                                                                                     '39921'



      NULL Comparison Expressions
      A L L UNcomparison expression tests whether a single-valued path expression has
      a      value. Usually, this expression is used to test whether or not a single-val-
         L LU N
      ued relationship has been set. If a path expression contains a        value during
                                                                                    L L UN
      evaluation, it returns a       value. Here is the syntax of a
                                    L LU N                                   comparison
                                                                                   L LU N
      expression:

                                  = : : no is s er px e _n os ir a pm oc _l l un
           L L UN ] T ON [ SI no is s er px e_ h ta p_ d eu la v_ e lg ni s

      Empty Collection Comparison Expressions
      An empty collection comparison expression tests whether a collection-valued
      path expression has no elements. In other words, it tests whether or not a collec-
      tion-valued relationship has been set. Here is the syntax:
                     = : : no is s er px e _n os ir a pm oc _ no it ce l lo c_ yt p me
      YT PM E ] TO N [ SI n oi s se rp x e_ ht ap _ de ul a v_ no it c el lo c
      If the collection-valued path expression is          LL UN   , then the empty collection com-
      parison expression has a       value.
                                     LL U N

      Collection Member Expressions
      The collection member expression determines whether a value is a member of a
      collection. The value and the collection members must have the same type. The
      expression syntax follows:
                                           FULL SYNTAX                                                187


                                           =: : n oi ss er p xe _r eb m em _n o it ce ll o c
    | e lb a ir av _n o it ac i fi tn ed i | n o it ag iv a n_ de ul a v_ el g ni s{
                                                             }r et em a ra p_ t up ni
      n oi s se rp xe _ ht ap _ de ul av _ no it c el lo c ] FO [ RE B ME M ] TO N [

If the collection-valued path expression is unknown, then the collection member
expression is unknown. If the collection-valued path expression designates an
empty collection, then the collection member expression is        .           ES LA F

Functional Expressions
EJB QL includes several string and arithmetic functions, which are listed in the
following tables. In Table 8–4, the      and
                                        tr a ts       arguments are of type
                                                          ht gn e l            .           tn i
They designate positions in the            argument. In Table 8–5, the
                                        gn ir tS                                          r eb mu n
argument may be either an      ,a
                                tn i   , or a
                                         t ao lf    .     e l bu od


Table 8–4 String Expressions

 Function Syntax                                Return Type

 )gnirtS ,gnirtS(TACNOC                         gnirtS

 )htgnel ,trats ,gnirtS(GNIRTSBUS               gnirtS

 )]trats ,[ gnirtS ,gnirtS(ETACOL               tni

 )gnirtS(HTGNEL                                 tni



Table 8–5 Arithmetic Expressions

 Function Syntax                                Return Type

 )rebmun(SBA                                          ,
                                                taolf tni     , or   elbuod

 )elbuod(TRQS                                   elbuod
188                                        ENTERPRISE JAVABEANS™ QUERY LANGUAGE



      NULL Values
      If the target of a reference is not in the persistent store, then the target is .    L LU N
      For conditional expressions containing        , EJB QL uses the semantics defined
                                                     L LU N
      by SQL92. Briefly, these semantics are as follows:
           • If a comparison or arithmetic operation has an unknown value, it yields a
                   value.
              L LU N
           • If a path expression contains a       value during evaluation, it returns a
                                                     L LU N
                   value.
              L LU N
           • The             test converts a
                       L LU N SI                 persistent field or a single-valued rela-
                                                       LL U N
             tionship field to      . The
                                   EU RT                test converts them to
                                                LL U N TO N S I                      .ES L AF
           • Boolean operators and conditional tests use the three-valued logic defined
             by the following tables. (In these tables, T stands for        , F for
                                                                             E UR T      ,E SL A F
             and U for unknown.)


      Table 8–6   DNA     Operator Logic

       AND        T       F    U

       T          T       F    U

       F          F       F    F

       U          U       F    U



      Table 8–7   RO    Operator Logic

       OR         T       F    U

       T          T       T    T

       F          T       F    U

       U          T       U    U
                                           FULL SYNTAX                                 189


Table 8–8     TO N   Operator Logic

 NOT

 T            F

 F            T

 U            U



Table 8–9 Conditional Test

 Conditional Test               T      F    U

 Expression   EURT SI           T      F    F

 Expression   ESLAF SI          F      T    F

 Expression is unknown          F      F    T



Equality Semantics
In EJB QL, only values of the same type can be compared. However, this rule
has one exception: Exact and approximate numeric values can be compared. In
such a comparison, the required type conversion adheres to the rules of Java
numeric promotion.
EJB QL treats compared values as if they were Java types, not as if they repre-
sented types in the underlying data store. For example, if a persistent field could
be either an integer or a       , then it must be designated as an
                              LL U N                                         object,
                                                                    r eg et nI
not as ant ni  primitive. This designation is required because a Java object can be
LL U Nbut a primitive cannot.
Two strings are equal only if they contain the same sequence of characters. Trail-
ing blanks are significant; for example, the strings        and
                                                         ' cb a '         are not
                                                                    ' cb a '
equal.
Two entity beans of the same abstract schema type are equal only if their primary
keys have the same value.
190                                     ENTERPRISE JAVABEANS™ QUERY LANGUAGE



      SELECT Clause
      The            clause defines the types of the objects or values returned by the
                  T CE LE S
      query. The
           TC EL ES        clause has the following syntax:

           ] T CN IT S ID [ TC E LE S = :: e su a lc _t ce l es
          | n oi ss e rp xe _h t ap _d e ul av _e l gn is {
          }) e lb ai r av _n oi t ac if i tn ed i( T CE JB O

      Return Types
      The return type defined by the          clause must match that of the finder or
                                            TC EL ES
      select method for which the query is defined.
      For finder method queries, the return type of the             clause is the abstract
                                                                  TC E LE S
      schema type of the entity bean that defines the finder method. This abstract
      schema type maps to either a remote or local interface. If the bean’s remote
      home interface defines the finder method, then the return type is the remote
      interface (or a collection of remote interfaces). Likewise, if the local home inter-
      face defines the finder method, the return type is the local interface (or a collec-
      tion). For example, the                     interface of the
                                 e m oH re ya l Pl ac o L                       entity bean
                                                                            B JE r ey al P
      defines the           method:
                   ll ad n if

          ; no it p ec xE r ed ni F s wo rh t ) (l lA d ni f n oi tc el l oC c il b up

      The EJB QL query of the        ll a dn if   method returns a collection of         re ya l Pl ac o L
      interface types:

          )p (T CE J BO T CE L ES
              p r e ya lP M O RF

      For select method queries, the return type of the        TC E LE S   clause may be one of the
      following:
          • The abstract schema of the entity bean that contains the select method.
          • The abstract schema of a related entity bean
            (By default, each of these abstract schema types maps to the local inter-
            face of the entity bean. Although uncommon, in the deployment descrip-
            tor you may override the default mapping by specifying a remote
            interface.)
          • A persistent field
                                                   EJB QL RESTRICTIONS                                  191


  The                entity bean, for example, implements the
         BJ Er ey a lP                                                   s tr op S tc el e Sb je
  method, which returns a collection of            objects for
                                                       g ni r tS   . The      t ro p s          is a
                                                                                              t ro ps
  persistent field of the            entity bean. See Example 11 (page 172).
                               BJ Ee u ga eL
  A
  T CE LE S   clause cannot specify a collection-valued expression. For example, the
            clause
     TC EL E S                is invalid because
                       s m ae t. p                      is a collection. However, the
                                                              s ma et
            clause in the following query is valid because the is a single element of
     TC EL E S                                                           t
  the
  s ma et      collection:

                                        t TC EL E S
        t SA )s ma et . p( N I , p re y al P MO R F

  DISTINCT and OBJECT Keywords
  The            keyword eliminates duplicate return values. If the method of the
        TC NI T SI D
  query returns a                         —which allows duplicates—then you
                                 n oi tc e ll oC .l i tu .a v aj
  must specify the           keyword to eliminate duplicates. However, if the
                                                  TC NI TS I D
  method returns a                , the
                         T CN IT SI D            keyword is redundant because a
                                            t eS .l it u .a va j
                  may not contain duplicates.
  te S. l it u. av a j
  The           keyword must precede a stand-alone identification variable, but it
        TC EJ B O
  must not precede a single-valued path expression. If an identification variable is
  part of a single-valued path expression, it is not stand-alone.


EJB QL Restrictions
  EJB QL has a few restrictions:
        • Comments are not allowed.
        • Date and time values are in milliseconds and use a Java          . A date or
                                                                                 gn ol
          time literal should be an integer literal. To generate a millisecond value,
          you may use the                           class.
                                     r ad ne l aC .l i tu .a va j
        • Currently, container-managed persistence does not support inheritance.
          For this reason, two entity beans of different types cannot be compared.
192   ENTERPRISE JAVABEANS™ QUERY LANGUAGE
                              9
                Web Clients and
                  Components
                                                          Stephanie Bodoff



WHEN a Web client such as a browser communicates with a J2EE applica-
tion, it does so through server-side objects called Web components. There are
two types of Web components: Java™ Servlets and JavaServer Pages™ (JSP™)
pages. Servlets are Java programming language classes that dynamically process
requests and construct responses. JSP pages are text-based documents that exe-
cute as servlets but allow a more natural approach to creating static content.
Although servlets and JSP pages can be used interchangeably, each has its own
strengths. Servlets are best suited to managing the control functions of an appli-
cation, such as dispatching requests, and handling nontextual data. JSP pages are
more appropriate for generating text-based markup such as HTML, SVG, WML,
and XML.
This chapter describes the packaging, configuration, and deployment procedures
for Web clients. Chapters 10 and 11, cover how to develop the Web components.
Many features of JSP technology are determined by Java Servlet technology, so
you should familiarize yourself with that material even if you do not intend to
write servlets.
Most J2EE Web clients use the HTTP protocol and support for HTTP is a major
aspect of Web components. For a brief summary of HTTP protocol features, see
Appendix A.


                                                                                     193
194                                  WEB CLIENTS AND COMPONENTS



        In This Chapter
                  Web Client Life Cycle 194
                  Web Application Archives 196
                       Creating a WAR File 197
                       Adding a WAR File to an EAR File 198
                       Adding a Web Component to a WAR File 198
                  Configuring Web Clients 200
                       Application-Level Configuration 200
                       WAR-Level Configuration 200
                       Component-Level Configuration 202
                  Deploying Web Clients 203
                  Running Web Clients 204
                  Updating Web Clients 204
                  Internationalizing Web Clients 206


      Web Client Life Cycle
        The server-side portion of a Web client consists of Web components, static
        resource files such as images, and helper classes and libraries. The J2EE plat-
        form provides many supporting services that enhance the capabilities of Web
        components and make them easier to develop. However, because it must take
        these services into account, the process for creating and running a Web client is
        different from that of traditional stand-alone Java classes.
        Web components run within an environment called a Web container. The Web
        container provides services such as request dispatching, security, concurrency,
        and life-cycle management. It also gives Web components access to the J2EE
        platform APIs such as naming, transactions, and e-mail.
        Before it can be executed, a Web client must be packaged into a Web application
        archive (WAR), which is a JAR similar to the package used for Java class librar-
        ies, and installed (or deployed) into a Web container.
        Certain aspects of Web client behavior can be configured when it is deployed.
        The configuration information is maintained in a text file in XML format called
        a Web application deployment descriptor. When you create Web clients and
        components using the J2EE SDK                  utility, it automatically generates
                                           l oo ty o lp ed
        or updates the deployment descriptor based on data that you enter in lo ot y ol pe d
        wizards and inspectors. You can also manually create a deployment descriptor
        according to the schema described in the Java Servlet specification.
                                  WEB CLIENT LIFE CYCLE                           195


The process for creating, deploying, and executing a Web client can be summa-
rized as follows:
    1. Develop the Web component code (including possibly a deployment
       descriptor).
    2. Package the Web client components along with any static resources (for
       example, images) and helper classes referenced by the component.
    3. Deploy the application.
    4. Access a URL that references the Web client.
Developing Web component code is covered in chapters 10 and 11. Steps 2
through 4 are expanded on in the following sections, illustrated with a Hello,
World-style application. This application allows a user to enter a name into an
HTML form (Figure 9–1)




Figure 9–1 Greeting Form
196                                       WEB CLIENTS AND COMPONENTS



        and then displays a greeting after the name is submitted (Figure 9–2)




        Figure 9–2 Response

        The Hello application contains two Web components that generate the greeting
        and the response. This tutorial has two versions of this application: a servlet ver-
        sion called             in which the components are implemented by two servlet
                                                                  p pA 1 ol le H
        classes,                           and
               av aj .t e lv re Se s no ps e R                            , and a JSP ver-
                                                    a v aj .t e lv re Sg n it ee r G
        sion called              in which the components are implemented by two JSP
                                                                 pp A2 o ll eH
        pages,                 and                . The two versions are used to illustrate
                                          ps j. es n op se r       p sj .g ni t ee rg
        the tasks involved in packaging, deploying, and running a J2EE application that
        contains Web components.


      Web Application Archives
        Web clients are packaged in Web application archives. In addition to Web com-
        ponents, a Web application archive usually contains other files, including the fol-
        lowing:
            • Server-side utility classes (database beans, shopping carts, and so on).
              Often these classes conform to the JavaBeans component architecture.
            • Static Web content (HTML, image, and sound files, and so on).
            • Client-side classes (applets and utility classes).
        Web components and static Web content files are called Web resources.
                                        WEB APPLICATION ARCHIVES                             197


A WAR has a specific directory structure. The top-level directory of a WAR is
the document root of the application. The document root is where JSP pages, cli-
ent-side classes and archives, and static Web resources are stored.
The document root contains a subdirectory called           F NI B E W , which contains the
following files and directories:
    •           : The Web application deployment descriptor
       lm x .b ew
    • Tag library descriptor files (see Tag Library Descriptors (page 290))
    •           : A directory that contains server-side classes: servlets, utility
       se s sa lc
      classes, and JavaBeans components
    •     : A directory that contains JAR archives of libraries (tag libraries and
       b il
      any utility libraries called by server-side classes).
You can also create application-specific subdirectories (that is, package directo-
ries) in either the document root or the                   directory
                                            s e ss al c/ F NI B E W


  Note: When you add classes and archives to a WAR,            lootyolped  automatically
  packages them in the     FNI BEWsubdirectory. This is correct for Web components and
  server-side utility classes, but incorrect for client-side classes such as applets and
  any archives accessed by applets. To put client-side classes and archives in the cor-
  rect location, you must drag them to the document root after you have added them
  to the archive.



Creating a WAR File
When you add the first Web component to a J2EE application,          auto-
                                                                        lo o ty ol p ed
matically creates a new WAR file to contain the component. A later section
describes how to add a Web component.
You can also manually create a WAR in three ways:
    • With the                tool distributed with the J2EE SDK. This tool is
                    r eg ak c ap
      described in the section Packager Tool, page (440).
    • With the        task of the
                    r aw               portable build tool.
                                     tn a                       is used to build the
                                                                 t nA
      J2EE Tutorial examples. The example application described in the section
      The Example JSP Pages, page (249) uses            to create the WAR.
                                                        tn a
    • With the JAR tool distributed with the J2SE. If you arrange your applica-
      tion development directory in the structure required by the WAR format,
      it is straightforward to create a Web application archive file in the required
      format. You simply execute the following command in the top-level direc-
      tory of the application:
198                                     WEB CLIENTS AND COMPONENTS


         . r a w. em a Ne vi hc r a fv c r aj

      Note that to use any of these methods, you must also manually create a deploy-
      ment descriptor in the correct format.

      Adding a WAR File to an EAR File
      If you manually create a WAR file or obtain a WAR file from another party, you
      can add it to an existing EAR file as follows:
          1. Select a J2EE application.
          2. Select File→Add→Web WAR.
          3. Navigate to the directory containing the WAR file, select the WAR file,
             and click Add Web WAR.
      See The Example JSP Pages, page (249) for an example.
      You can also add a WAR file to a J2EE application using the          tool. The
                                                                            r eg ak c ap
      Duke’s Bank application described in Building, Packaging, Deploying, and Run-
      ning the Application, page (417) uses          .
                                                   r eg ak c ap


      Adding a Web Component to a WAR File
      The following procedure describes how to create and add the Web component in
      the              application to a WAR. Although the Web component wizard
          p pA 1 ol le H
      solicits WAR and component-level configuration information when you add the
      component, this chapter describes how to add the component and provide con-
      figuration information at a later time using application, WAR, and Web compo-
      nent inspectors:
         1. Go to
             se lp m ax e/ la i ro tu t ee 2j   and build the example by running                tn a
                    . For detailed instructions, see About the Examples, page (xxi)).
                                             1 ol le h
         2. Create a J2EE application called               .
                                                         pp A 1o ll eH
            a. Select File→New→Application.
            b. Click Browse.
            c. In the file chooser, navigate to                          m ax e /l ai r ot ut ee 2 j
                                         .
                 1 ol le h /b ew /c r s/ se l p
            d. In the File Name field, enter             .
                                                     pp A1 o ll eH
            e. Click New Application.
            f. Click OK.
                                         WEB APPLICATION ARCHIVES                                     199


 3. Create the WAR file and add the                        Web component and
                                                  te l vr eS gn i te er G
    all of the            application content.
                p p A1 ol l eH
    a. Invoke the Web component wizard by selecting File→New→Web
        Component.
    b. In the combo box labelled Create New WAR File in Application select
        Hello1App. Enter              in the field labeled WAR Display Name.
                                 R A W1 ol l eH
    c. Click Edit to add the content files.
    d. In the Edit Contents dialog box, navigate to  ma xe / la ir o tu te e2 j
                                  .     Select
        1 ol l eh /b e w/ dl iu b /s el p                                  ,
                                                     ss al c .t el vr e Sg ni te e rG
                                  , and
        s sa l c. te l vr eS es n op se R                   , and click Add.fi g. g ni va w. e ku d
        Click OK.
    e. Click Next.
    f. Select the Servlet radio button.
    g. Click Next.
    h. Select                     from the Servlet Class combo box.
                t e lv re S gn it ee r G
    i. Click Finish.
 4. Add the                      Web component.
              t e lv re S es no ps e R
    a. Invoke the Web component wizard by selecting File→New→Web
       Component.
    b. In the combo box labeled Add To Existing WAR File, select
                  .
        R AW 1 ol le H
    c. Click Next.
    d. Select the Servlet radio button.
    e. Click Next.
    f. Select                     from the Servlet Class combo box.
                t e lv re S es no ps e R
    g. Click Finish.

Note: You can add JSP pages to a WAR file without creating a new Web component
for each page. You simply select the WAR file, click Edit to edit the contents of the
WAR, and add the pages. The JSP version of the Hello, World application,
described in Updating Web Clients, page (204), shows how to do this. If you choose
this method, you will not be able to specify alias paths (described in Specifying an
Alias Path, page (203)) for the pages.
200                                         WEB CLIENTS AND COMPONENTS



      Configuring Web Clients
        The following sections describe the Web client configuration parameters that
        you will usually want to specify. Configuration parameters are specified at three
        levels: application, WAR, and component. A number of security parameters can
        be applied at the WAR and component levels. For information on these security
        parameters, see Web-Tier Security, page (337).

        Application-Level Configuration

        Context Root
        A context root is a name that gets mapped to the document root of a Web client.
        If your client’s context root is      , then the request URL
                                              g o la ta c

            l mt h .x ed n i/ go la t ac /0 0 08 : > ts o h < // :p t th

        will retrieve the file   l mt h .x ed ni   from the document root.
        To specify the context root for        p pA 1 ol le H   in   lo o ty ol p ed   ,
            1. Select           .
                         pp A 1o ll e H
            2. Select the Web Context tab
            3. Enter        in the Context Root field.
                        1 o ll eh


        WAR-Level Configuration
        The following sections give generic procedures for specifying WAR-level con-
        figuration information. For some specific examples, see The Example
        Servlets, page (211).

        Context Parameters
        The Web components in a WAR share an object that represents their Web context
        (see Accessing the Web Context (page 238)). To specify initialization parameters
        that are passed to the context,
            1. Select the WAR.
            2. Select the Context tab.
            3. Click Add.
                                     CONFIGURING WEB CLIENTS                           201


References to Environment Entries, Enterprise Beans,
Resource Environment Entries, or Resources
If your Web components reference environment entries, enterprise beans,
resource environment entries, or resources such as databases, you must declare
the references as follows:
    1. Select the WAR.
    2. Select the Environment, Enterprise Bean Refs, Resource Env. Refs or
       Resource Refs tab.
    3. Click Add in the pane to add a new reference.

Event Listeners
To add an event listener class (described in Handling Servlet Life-Cycle
Events, page (216)),
    1.   Select the WAR.
    2.   Select the Event Listeners tab.
    3.   Click Add.
    4.   Select the listener class from the new field in the Event Listener Classes
         pane.

Error Mapping
You can specify a mapping between the status code returned in an HTTP
response or a Java programming language exception returned by any Web com-
ponent and a Web resource (see Handling Errors, page (218)). To set up the map-
ping,
    1. Select the WAR.
    2. Select the File Refs tab.
    3. Click Add in the Error Mapping pane.
    4. Enter the HTTP status code (see HTTP Responses, page (432)) or fully-
       qualified class name of an exception in the Error/Exception field.
    5. Enter the name of a resource to be invoked when the status code or excep-
       tion is returned. The name should have a leading forward slash .     /


  Note: You can also define error pages for a JSP page contained in a WAR. If error
  pages are defined for both the WAR and a JSP page, the JSP page’s error page takes
  precedence.
202                                 WEB CLIENTS AND COMPONENTS



      Filter Mapping
      A Web container uses filter mapping declarations to decide which filters to apply
      to a request, and in what order (see Filtering Requests and
      Responses, page (228)). The container matches the request Uniform Resource
      Identifier (URI) to a servlet as described in Specifying an Alias Path, page (203).
      To determine which filters to apply, it matches filter mapping declarations by
      servlet name or URL pattern. The order in which filters are invoked is the order
      in which filter mapping declarations that match a request URI for a servlet
      appear in the filter mapping list.
      You specify a filter mapping in   lo ot y ol pe d   as follows:
          1. Select the WAR.
          2. Select the Filter Mapping tab.
          3. Add a filter.
             a. Click Edit Filter List.
             b. Click Add.
             c. Select the filter class.
             d. Enter a filter name.
             e. Add any filter initialization parameters.
             f. Click OK.
          4. Map the filter.
             a. Click Add.
             b. Select the filter name.
             c. Select the target type. A filter can be mapped to a specific servlet or to
                all servlets that match a given URL pattern.
             d. Specify the target. If the target is a servlet, select the servlet from the
                drop-down list. If the target is a URL pattern, enter the pattern.

      Component-Level Configuration

      Initialization Parameters
      To specify parameters that are passed to the Web component when it is initial-
      ized,
          1. Select the Web component.
          2. Select the Init. Parameters tab.
          3. Click Add to add a new parameter and value.
                                             DEPLOYING WEB CLIENTS                                203


  Specifying an Alias Path
  When a request is received by a Web container, it must determine which Web
  component should handle the request. It does so by mapping the URL path con-
  tained in the request to a Web component. A URL path contains the context root
  (described in the section Context Root, page (200)) and an alias path:

      ht a p sa il a /t oo r t xe tn o c/ 00 08 : >t so h </ /: pt t h

  Before a servlet can be accessed, the Web container must have at least one alias
  path for the component. The alias path must start with a and end with a string
                                                                         /
  or a wildcard expression with an extension (            , for example). Since Web
                                                          p s j. *
  containers automatically map an alias path that ends with         , you do not have
                                                                         ps j. *
  to specify an alias path for a JSP page unless you wish to refer to the page by a
  name other than its file name. In the example discussed in the section Updating
  Web Clients, page (204), the page                     has an alias,
                                             ps j. gn i te er g                  , but
                                                                             g ni t ee rg /
  the page                  is referenced by its file name within
            p sj .e sn o ps er                                                   .
                                                                             ps j. gn i te er g
  You set up the mappings for the servlet version of the Hello application using the
  Web component inspector as follows:
      1.   Select the                     Web component.
                      t e lv re S gn it ee r G
      2.   Select the Aliases tab.
      3.   Click Add to add a new mapping.
      4.   Type              in the aliases list.
                g ni t ee rg /
      5.   Select the                     Web component.
                      t e lv re S es no ps e R
      6.   Click Add.
      7.   Type              in the aliases list.
                e sn o ps er /


Deploying Web Clients
  The next step after you have created, packaged, and configured a Web client is to
  deploy the EAR file that contains the client. To deploy the             applica-
                                                                             p pA 1o ll e H
  tion,
      1.   Select             .
                  p pA 1 ol le H
      2.   Select Tools→Deploy.
      3.   Select a target server.
      4.   Click Finish.
204                                         WEB CLIENTS AND COMPONENTS



      Running Web Clients
        A Web client is executed when a Web browser references a URL that is mapped
        to a component contained in the client. Once you have deployed the                 pp A 1o ll eH
        application, you can run the Web client by pointing a browser at

            g ni te e rg /1 ol l eh /0 0 08 : > ts o h < // :p t th

        Replace           with the name of the host running the J2EE server. If your
                  > ts o h<
        browser is running on the same host as the J2EE server, you may replace                 >t s oh <
        with            .
             ts oh l ac ol


      Updating Web Clients
        During development, you will often need to make changes to Web clients. To
        update a servlet you modify the source file, recompile the servlet class, update
        the component in the WAR, and redeploy the application. Except for the compi-
        lation step, you update a JSP page in the same way.
        To try this feature, first build, package, and deploy the JSP version of the Hello
        application:
            1. Go to                            and build the example by running
                cr s /s el pm a xe /l a ir ot ut e e2 j
                            .                   2o ll e h tn a
            2. Create a J2EE application called       .      pp A 2o ll eH
               a. Select File→New→Application.
               b. In the file chooser, navigate to                           m ax e /l ai r ot ut ee 2 j
                                          .
                    2 ol le h /b ew /c r s/ se l p
               c. In the File Name field, enter     .     pp A2 o ll eH
               d. Click New Application.
               e. Click OK.
            3. Create the WAR and add the                  Web component and all of the
                                                        gn it e er g
                           application content.
                p pA 2 ol le H
               a. Invoke the Web component wizard by selecting File→New→Web
                  Component.
               b. In the combo box labeled Create New WAR File in Application select
                             . Enter
                    pp A 2o ll e H               in the field labeled WAR Display Name.
                                            R AW 2 ol le H
               c. Click Edit to add the content files.
                                              UPDATING WEB CLIENTS                                        205


          d. In       the     Edit     Contents dialog box, navigate
                                                           ma xe                         to
                                               . Select
               2 ol l eh /b e w/ dl iu b /s el p                  ,                               , and
                                                               p s j. es n op se r ps j. gn i te er g
                                       , and click Add. Click OK.
                         fi g .g ni va w .e ku d
          e.   Click Next.
          f.   Select the JSP radio button.
          g.   Click Next.
          h.   Select                from the JSP Filename combo box.
                        p sj . gn it ee r g
          i.   Click Finish.
     4.   Add the alias            for the
                             gn it e er g/            g ni t ee rg   Web component.
     5.   Specify the context root        .
                                          2 ol l eh
     6.   Deploy             .
                      p p A2 ol l eH
     7.   Execute the application by                       pointing a Web browser at
          g ni te e rg /2 o ll eh /0 0 08 :> ts o h < // : pt th. Replace with the name
                                                                            > t so h<
          of the host running the J2EE server.
Now modify one of the JSP files. For example, you could replace the contents of
             with the following:
p sj . es no ps e r

     >2 h/ <! > %e ma nr e su =% < , iH >2 h <

To update the file in the WAR and redeploy the application:
     1. Edit                .
                 p sj .e s no ps e r
     2. Execute               to copy the modified file to the build directory.
                      2 ol le h t na
     3. Select            .
                    p pA 2 ol le H
     4. In            , select Tools→Update Files.
               l o ot yo l pe d
     5. A dialog box appears reporting the changed file.Verify that                 p sj .e s no ps e r
        has been changed and dismiss the dialog box.
     6. Select Tools→Deploy. Make sure the checkbox labeled Save Object
        Before Deploying is checked.
You can also perform steps 4 through 6 by selecting Tools→Update And Rede-
ploy. The              utility replaces the old JSP file in
               l oo t yo lp e d                                       with r ae . pp A2 ol l eH
the new one and then redeploys the application.
206                                         WEB CLIENTS AND COMPONENTS



        When you execute the application, the response should be changed (Figure 9–3)




        Figure 9–3 New Response


      Internationalizing Web Clients
        Internationalization is the process of preparing an application to support various
        languages. Localization is the process of adapting an internationalized applica-
        tion to support a specific language or locale. Although all client user interfaces
        should be internationalized and localized, it is particularly important for Web cli-
        ents because of the far-reaching nature of the Web. For a good overview of inter-
        nationalization and localization, see

             lm t h. xe dn i /n 81 i /l ai ro t ut /s k oo b/ sc o d/ mo c .n us .a v aj // :p t th

        In the simplest internationalized program, strings are read from a resource bun-
        dle that contains translations for the language in use. The resource bundle maps
        keys used by a program to the strings displayed to the user. Thus, instead of cre-
        ating strings directly in your code, you create a resource bundle that contains
        translations and read the translations from that bundle using the corresponding
        key. A resource bundle can be backed by a text file (properties resource bundle)
        or a class (list resource bundle) containing the mappings.
        In the following chapters on Web technology, the Duke’s Bookstore example is
        internationalized and localized into English and Spanish. The key and value
        pairs    are    contained    in    list  resource    bundles    named                         s em
                                       . To give you an idea of what the key and string
        s sa l c. *_ e ga ss eM k oo B. se g as
                                                           st n ir pe ul b /m oc .n u s. av a j/ /: pt t h
      more information on this subject, see the J2EE Blueprints:
      This has been a very brief introduction to internationalizing Web clients. For
      internationalized; see the section Internationalization, page (415) in Chapter 18.
      client distributed with this tutorial’s case study application, Duke’s Bank, are
      In addition to Duke’s Bookstore, both the Web client and the J2EE application
                                                    ;) ” re ih s aC el ti T “( gn ir t St eg . se ga ss e m
               as follows:    r e ih sa Ce l ti T   and looks up the string associated with the key
                      ;) "s e ga ss e m" (e tu b ir tt A te g. no i ss es )e l dn uB e cr uo se R (
                                                                = se g as se m e ld nu B ec ru os e R
                         A Web component retrieves the resource bundle from the session:
                                                                                                  }
                         ; )s e ga ss em ," se g as se m" ( et ub ir t tA te s .n oi ss e s
                                                                          ;) el ac o l
              , "s eg a ss eM b eW "( el d nu Bt e g. el dn u Be cr uo s eR = se ga ss e m
                                       ; ) (e la c oL te g. t se uq er = el ac o l el ac o L
                                                                { ) ll un = = s eg a ss em ( f i
                                                            ;) "s e ga ss em " (e tu b ir tt At e g
                          . no is s es )e l dn uB ec r uo se R ( = se g as se m e ld nu B ec ru os e R
      ing Attributes with a Session, page (239)):
      dle for that locale, and then saves the bundle as a session attribute (see Associat-
      (set by a browser language preference) from the request, opens the resource bun-
      To get the correct strings for a given user, a Web component retrieves the locale
                                                          , }" gn ip p oh S tr a tS " , "t ra tS " {
                                            ,} "! r ep ol e ve d be W g ni tc e ps er fl es y n a
       ro f d ae r t su m a s i si h T .b eW eh t r of s no i ta ci lp p a po l ev ed u o y
       ya w eh t m ro fs n ar t na c s tn en op m oc b eW wo h tu ob a s kl at " ," kl aT " {
                                                     , }" g ni da eR er "e W t ah W" ," ta hW " {
                                         ,} " re b mu n r ot is iv er a uo Y " ," r ot is iV " {
                               , }" no i tp ir cs e D ko o B" , "n o it pi rc s eD ko o Be lt iT " {
                                                          , }" re ih s aC " ," r ei hs a Ce lt iT " {
                                         .                                  av a j. se ga s se Mk o oB .s eg a s
       se m   pairs in a resource bundle look like, here are a few lines from the file
207                          INTERNATIONALIZING WEB CLIENTS
208   WEB CLIENTS AND COMPONENTS
                                           10
                                 Java Servlet
                                  Technology
                                                          Stephanie Bodoff



A   S soon as the Web began to be used for delivering services, service providers
recognized the need for dynamic content. Applets, one of the earliest attempts
towards this goal, focused on using the client platform to deliver dynamic user
experiences. At the same time, developers also investigated using the server plat-
form for this purpose. Initially, Common Gateway Interface (CGI) scripts were
the main technology used to generate dynamic content. Though widely used,
CGI scripting technology has a number of shortcomings, including platform
dependence and lack of scalability. To address these limitations, Java Servlet
technology was created as a portable way to provide dynamic, user-oriented con-
tent.

In This Chapter
          What Is a Servlet? 210
          The Example Servlets 211
              Troubleshooting 215
          Servlet Life Cycle 216
              Handling Servlet Life-Cycle Events 216
              Handling Errors 218
          Sharing Information 218
              Using Scope Objects 219
              Controlling Concurrent Access to Shared Resources 220
              Accessing Databases 221
                                                                                     209
210                                         JAVA SERVLET TECHNOLOGY


                      Initializing a Servlet 222
                      Writing Service Methods 223
                           Getting Information from Requests 223
                           Constructing Responses 225
                      Filtering Requests and Responses 228
                           Programming Filters 229
                           Programming Customized Requests and Responses 231
                           Specifying Filter Mappings 233
                      Invoking Other Web Resources 235
                           Including Other Resources in the Response 235
                           Transferring Control to Another Web Component 237
                      Accessing the Web Context 238
                      Maintaining Client State 239
                           Accessing a Session 239
                           Associating Attributes with a Session 239
                           Session Management 240
                           Session Tracking 241
                      Finalizing a Servlet 242
                           Tracking Service Requests 243
                           Notifying Methods to Shut Down 243
                           Creating Polite Long-Running Methods 244


      What Is a Servlet?
        A servlet is a Java programming language class used to extend the capabilities of
        servers that host applications accessed via a request-response programming
        model. Although servlets can respond to any type of request, they are commonly
        used to extend the applications hosted by Web servers. For such applications,
        Java Servlet technology defines HTTP-specific servlet classes.
        The                   and
               te l vr es .x a va j                       packages provide interfaces and
                                         pt th . te lv re s .x av aj
        classes for writing servlets. All servlets must implement the           interface,
                                                                                   te lv re S
        which defines life-cycle methods.
        When implementing a generic service, you can use or extend the                     v re S ci re n eG
        t elclass provided with the Java Servlet API. The                class provides
                                                                       te lv r eS pt t H
        methods, such as       and
                               t eG od     , for handling HTTP-specific services.
                                            t s oP od
        This chapter focuses on writing servlets that generate responses to HTTP
        requests. Some knowledge of the HTTP protocol is assumed; if you are unfamil-
        iar with this protocol, you can get a brief introduction to HTTP in Appendix A.
                                                THE EXAMPLE SERVLETS                                        211


The Example Servlets
  This chapter uses the Duke’s Bookstore application to illustrate the tasks
  involved in programming servlets. Table 10–1 lists the servlets that handle each
  bookstore function. Each programming task is illustrated by one or more serv-
  lets. For example,                        illustrates how to handle HTTP
                               t el vr e Ss li at e Dk oo B                                          T EG
  requests,                      and
              t e lv re S go la ta C                      show how to construct
                                           t e lv re S sl ia te D ko oB
  responses, and                 illustrates how to track session information.
                                           te lv r eS go la t aC


  Table 10–1 Duke’s Bookstore Example Servlets

   Function                                                   Servlet

   Enter the bookstore                                        telvreSerotSkooB

   Create the bookstore banner                                telvreSrennaB

   Browse the bookstore catalog                               telvreSgolataC

                                                                  telvreSgolataC  ,
   Put a book in a shopping cart
                                                              telvreSsliateDkooB

   Get detailed information on a specific book                telvreSsliateDkooB

   Display the shopping cart                                  telvreStraCwohS

   Remove one or more books from the shopping cart            telvreStraCwohS

   Buy the books in the shopping cart                         telvreSreihsaC

   Receive an acknowledgement for the purchase                telvreStpieceR



  The data for the bookstore application is maintained in a database and accessed
  through the helper class                   . The
                                  BD ko oB . es ab a ta d    package also contains
                                                               e sa ba t ad
  the class               , which represents a book. The shopping cart and shop-
              s li a te Dk oo B
  ping cart items are represented by the classes                              and
                                                                       t r aC gn ip p oh S. t ra c
                             , respectively.
  m et It ra C gn ip p oh S. tr a c
  The     source     code      for    the    bookstore      application is located in the
  1 er ot sk o ob /b e w/ cr s/ s el pm ax e /l ai r ot ut ee 2 jdirectory created when you
212                                       JAVA SERVLET TECHNOLOGY



      unzip the tutorial bundle (see Downloading the Examples, page (xxii)). To build,
      deploy, and run the example, follow these steps.
          1. Go to
               se lp m ax e/ la i ro tu t ee 2j   and build the example by running                              tn a
                               (see How to Build and Run the Examples, page (xxii)).
                                         1e ro t sk oo b
          2.   Start the  ee 2j  server.
          3.   Start  . lo ot yo l pe d
          4.   Start the Cloudscape database server by running                  ep ac s du ol c          tr at s   .
          5.   Load the bookstore data into the database by running                          b ew et ae r c t n a
               .b d
          6. Create a J2EE application called              p p A1 er o ts ko oB     .
             a. Select File→New→Application.
             b. In the file chooser, navigate                             to             m ax e /l ai r ot ut ee 2 j
                                              .
                  1e r ot sk oo b /b ew /c r s/ se l p
             c. In the File Name field, enter            p p A1 er ot s ko oB   .
             d. Click New Application.
             e. Click OK.
          7. Create the WAR and add the                       Web component and all of
                                                             te lv r eS re nn a B
             the Duke’s Bookstore content to the                     application.
                                                    p pA 1e r ot sk oo B
             a. Select File→New→Web Component.
             b. Click the Create New WAR File In Application radio button and select
                                 from the combo box. Enter
                  pp A1 er o ts ko o B                                             in the
                                                                                        R AW 1 er ot s ko oB
                field labeled WAR Display Name.
             c. Click Edit to add the content files.
             d. In the Edit Archive Contents dialog box, navigate to
                   n aB                                                . Select
                                         1e ro t sk oo b /b ew /d l iu b/ s el pm ax e /l ai ro t ut ee 2 j
                                     ,                             ,
                   v re S sl ia t eD ko oB s sa lc . te lv re S er ot S ko oB ss a lc .t el v re Sr e n
                            ,
                  s sa l c. te lv r eS tr a Cw oh S       ,
                                                         ss a lc .t el v re Sg o la ta C,    ss a lc .t e l
                                            , and
                                   s s al c. t el vr eS t pi ec e R        . Click Add.
                                                                            ss al c. t el vr eS r ei hs a C
                Add
                  e sa b at ad tr ac     and                  . Add the
                                                   fi g. s ko ob .e k ud      ,         ,
                                                                               lm th . eg ap r or re
                            ,   l it u ,             ,           , and          packages.
                                                s eg a ss em s r en et s il s re t li f no i tp ec x e
                Click OK.
             e. Click Next.
             f. Select the Servlet radio button.
             g. Click Next.
             h. Select                    from the Servlet Class combo box.
                           t el v re Sr en n aB
                                           THE EXAMPLE SERVLETS                                      213


      i. Click Next twice.
      j. In the Component Aliases pane, click Add and then type                   r en na b /   in
         the Alias field.
      k. Click Finish.
   8. Add each of the Web components listed in Table 10–2. For each servlet,
      click the Add to Existing WAR File radio button and select
                        from the combo box. Since the WAR contains all of the
      R AW 1 er ot s ko oB
      servlet classes, you do not have to add any more content.


Table 10–2 Duke’s Bookstore Web Components

 Web Component Name             Servlet Class                         Component Alias

 telvreSerotSkooB               telvreSerotSkooB                      retne/

 telvreSgolataC                 telvreSgolataC                        golatac/

 telvreSsliateDkooB             telvreSsliateDkooB                    sliatedkoob/

 telvreStraCwohS                telvreStraCwohS                       tracwohs/

 telvreSreihsaC                 telvreSreihsaC                        reihsac/

 telvreStpieceR                 telvreStpieceR                        tpiecer/



   9. Add a resource reference for the Cloudscape database.
      a. Select                 .
                  RA W1 e ro ts ko o B
      b. Select the Resource Refs tab.
      c. Click Add.
      d. Select                           from the Type column
                  ec ru oS a ta D. l qs .x av a j
      e. Enter               in the Coded Name field.
                 BD ko oB / cb dj
      f. Enter                    in the JNDI Name field.
                 e pa c sd uo lC / cb dj
   10.Add the listener class                               (described in Han-
                                    r en e ts iL tx e tn oC .s r en et s il
      dling Servlet Life-Cycle Events, page (216).
      a. Select the Event Listeners tab.
      b. Click Add.
      c. Select the                                class from the drop-down
                        r e ne ts i Lt xe tn o C. sr en e ts il
         field in the Event Listener Classes pane.
214                                JAVA SERVLET TECHNOLOGY



      11.Add an error page (described in Handling Errors, page (218)).
         a. Select the File Refs tab.
         b. In the Error Mapping panel, click Add.
         c. Enter                                         in the Error/Exception
                    no it pe c xE dn u oF to Nk o oB .n oi t pe cx e
            field.
         d. Enter                     in the Resource To Be Called field.
                   lm t h. eg ap r or re /
         e. Repeat for
            n oi tp e cx Ed n uo Ft oN s ko oB . no it pe c xe  and                v re s .x av a j
                                           .
                                       n oi t pe cx Ee l ba li av a nU .t e l
      12.Add the filters                                  and
                           r et li F re tn u oC ti H. s re tl i f      re tl i Fr ed r O. sr et l if
         (described in Filtering Requests and Responses, page (228)).
         a. Select the Filter Mapping tab.
         b. Click Edit Filter List.
         c. Click Add.
         d. Select
            re t li Fr et n uo Ct i H. sr et l if   from the Filter Class column. The
                          utility will automatically enter
                                          l oo t yo lp e d                       in the
                                                                    r et li F re tn u oC ti H
            Display Name column.
         e. Click Add.
         f. Select
            re tl i Fr ed rO . sr et li f      from the Filter Class column. The
                          utility will automatically enter
                                   l oo t yo lp e d                        in the Dis-
                                                                     r et li F re dr O
            play Name column.
         g. Click OK.
         h. Click Add.
         i. Select                        from the Filter Name column.
                    re tl iF r et nu oC t iH
         j. Select Servlet from the Target Type column.
         k. Select                        from the Target column.
                    te lv re S er ot Sk o oB
         l. Repeat for
            r et l iF re dr O           . The target type is Servlet and the target is
                               .
                      t el vr eS t pi ec e R
      13.Enter the context root.
         a. Select               .
                    p pA 1 er ot sk o oB
         b. Select the Web Context tab.
         c. Enter              .
                   1e ro t sk oo b
      14.Deploy the application.
         a. Select Tools→Deploy.
         b. Click Finish.
                                               THE EXAMPLE SERVLETS                                         215


      15.Open the bookstore URL                                                                    .
                                             re tn e/ 1 er ot s ko ob /0 0 08 :> t so h < // : pt th


Troubleshooting
The section Common Problems and Their Solutions, page (41) (in particular,
Web Client Runtime Errors, page (45)) lists some reasons why a Web client can
fail. In addition, Duke’s Bookstore returns the following exceptions:
      •                             : Returned if a book can’t be located in the
          no it p ec xE dn u oF to N ko oB
        bookstore database. This will occur if you haven’t loaded the bookstore
        database with data by running                            or if the Cloudscape
                                                   b d b ew e t ae rc t na
        server hasn’t been started or it has crashed.
      •                              : Returned if the bookstore data can’t be
          n oi tp e cx Ed nu o Ft oN s ko oB
        retrieved. This will occur if you haven’t loaded the bookstore database
        with data by running                            or if the Cloudscape server
                                       bd be w e ta er c t na
        hasn’t been started or has crashed.
      •                           : Returned if a servlet can’t retrieve the Web con-
          n oi t pe cx Ee l ba li a va nU
        text attribute representing the bookstore. This will occur if you haven’t
        added the listener class to the application.
Since we have specified an error page, you will see the message                       ac il p pa e hT
                                              . If you don’t specify an error page,
re ta l y rt es a el P . el ba l ia va n u s i no i t
the Web container generates a default page containing the message                           t el vr e S A
                            and a stack trace that can help diagnose the cause of
                      de r ru cc O s a H n oi tp ec x E
the exception. If you use
l mt h .e ga p ro rr e                      , you will have to look in the Web
container’s log to determine the cause of the exception. Web log files reside in
the directory

      b ew /> ts o h < /> sg o l< /E M OH _E E2 J $

and are named       go l .> et ad < .a ni l at ac     .
The        element is the directory specified by the
            > sg ol <                                          entry in the
                                                               y ro t ce ri d. g ol
                     file. The default value is
se it r ep or p .t lu af e d                         . The  element is the
                                                                  > t so h <       s go l
name of the computer. See the Configuration Guide provided with the J2EE
SDK for more information about J2EE SDK log files.
216                                          JAVA SERVLET TECHNOLOGY



      Servlet Life Cycle
        The life cycle of a servlet is controlled by the container in which the servlet has
        been deployed. When a request is mapped to a servlet, the container performs the
        following steps.
            1. If an instance of the servlet does not exist, the Web container
               a. Loads the servlet class.
               b. Creates an instance of the servlet class.
               c. Initializes the servlet instance by calling the         method. Initializa-
                                                                       ti ni
                   tion is covered in Initializing a Servlet, page (222).
            2. Invokes the          method, passing a request and response object. Ser-
                                ec i vr es
               vice methods are discussed in the section Writing Service
               Methods, page (223).
        If the container needs to remove the servlet, it finalizes the servlet by calling the
        servlet’s  yo rt se d method. Finalization is discussed in Finalizing a
        Servlet, page (242).

        Handling Servlet Life-Cycle Events
        You can monitor and react to events in a servlet’s life cycle by defining listener
        objects whose methods get invoked when life cycle events occur. To use these
        listener objects, you must define the listener class and specify the listener class.

        Defining The Listener Class
        You define a listener class as an implementation of a listener interface. Table 10–
        3 lists the events that can be monitored and the corresponding interface that must
        be implemented. When a listener method is invoked, it is passed an event that
        contains information appropriate to the event. For example, the methods in the
                                              ; )) (e g as se M te g. xe +
                                " : es ab a ta d et a er c t 'n dl uo C "
                                                      ( nl tn i rp .t u o. me ts y S
                                                     { ) x e no it p ec xE ( h ct ac }
                     ;) BD ko o b ," BD k oo b" ( et ub ir t tA te s .t xe tn o c
                                     ; )( B Dk oo B w en = BD ko o b BD ko o B
                                                                                   { yrt
                                 ; )( t xe tn o Ct el vr e St eg .t n ev e = t xe tn o c
      { )t n ev e t ne v Et xe tn o Ct el v re S( de z il ai t in It xe t no c d i ov ci lb u p
                                     ; ll un = tx e tn oc t x et no Ct e lv re S e ta vi r p
                                          { r en et s iL tx et n oC te lv r eS s t ne me lp m i
                                                 r e ne ts i Lt xe tn o C ss al c l an i f ci lb u p
                                                                         ;r et nu o C. li t u tr op m i
                                                                    ;* . te lv re s .x av a j tr op m i
                                                                    ;B D ko oB .e s ab at a d tr op m i
      (and remove) the objects as servlet context attributes.
                          t n ev Et xe t no Ct e lv re S
      ods retrieve the Web context object from                         and then store
      helper and counter objects used in the Duke’s Bookstore application. The meth-
      The                                                      re ne ts i Lt xe t no C. sr e ne ts i l
                                            class creates and removes the database
                            tnevEgnidniBnoisseSpttH            replaced
                 and   renetsiLetubirttAnoisseSpttH            removed, or
                                .ptth.telvres.xavaj            Attribute added,       State, page (239))
                                                                                      taining Client
                                        tnevEnoisseSpttH           and timeout        Session (See Main-
                               and   renetsiLnoisseSpttH           invalidation,
                                     .ptth.telvres.xavaj           Creation,
                    tnevEetubirttAtxetnoCtelvreS               replaced
           and   renetsiLetubirttAtxetnoCtelvreS               removed, or
                                  .telvres.xavaj               Attribute added,      Context, page (238))
                                                                                     Accessing the Web
                                  tnevEtxetnoCtelvreS                                Web context (See
                                                                 and destruction
                         and   renetsiLtxetnoCtelvreS
                                                                 Initialization
                                       .telvres.xavaj
                 Listener Interface and Event Class                      Event                    Object
                                                               Table 10–3 Servlet Life-Cycle Events
                                                                                .n oi s se Sp tt H tains an
      , which con-      t ne vE n oi ss eS p tt H   interface are passed an    r en et s iL no i ss eS pt t H
217                                         SERVLET LIFE CYCLE
218                                       JAVA SERVLET TECHNOLOGY


                                                                                             }
                                            ; )( r et nu oC we n = r et nu o c re tn u oC
                          ; )r e tn uo c , "r et n uo Ct ih " (e tu bi r tt At e s. tx et n oc
                                            " re t nu oC ti h d et ae r C" (g o l. tx et n oc
                                                  ;) ) (r et nu o Ct eg . re tn uo c +
                                                         ;) ( re tn uo C w en = re tn u oc
                       ; )r et n uo c ," r et nu o Cr ed ro " (e tu bi r tt At e s. tx et n oc
                                         " re tn u oC re dr o d et ae r C" (g o l. tx et n oc
                                                ; )) ( re tn uo C te g. r et nu oc +
                 }

                 { )t n ev e tn e vE tx e tn oC te l vr eS ( de yo rt s eD tx et n oc d i ov c il b up
                                         ;) ( tx et n oC te lv r eS te g. t ne ve = tx et n oc
                                       ( et u bi rt t At eg .t x et no c = B Dk o ob B Dk o oB
                                                                            ; )" BD ko o b"
                                                                         ; ) (e vo m er .B Dk o ob
                                            ; )" BD k oo b" (e t ub ir tt A ev om e r. tx et n oc
                                      ;) "r e tn uo C ti h" (e t ub ir tt A ev om e r. tx et n oc
                                   ;) "r et n uo Cr e dr o" (e t ub ir tt A ev om e r. tx et n oc
                                                                                                     }
            }

        Specifying Event Listener Classes
        You specify a listener class for a WAR in the                l oo t yo lp ed   Event Listeners
        inspector (see Event Listeners, page (201)).

        Handling Errors
        Any number of exceptions can occur when a servlet is executed. The Web con-
        tainer will generate a default page containing the message               p ec x E t el v re S A
        d er ru cc O sa H n o itwhen an exception occurs, but you can also specify that
        the container should return a specific error page for a given exception. You spec-
        ify error pages for a WAR in the                   File Refs inspector (see Error
                                                   l oo t yo lp ed
        Mapping, page (201)).


      Sharing Information
        Web components, like most objects, usually work with other objects to accom-
        plish their tasks. There are several ways they can do this. They can use private
        helper objects (for example, JavaBeans components), they can share objects that
        are attributes of a public scope, they can use a database, and they can invoke
        other Web resources. The Java Servlet technology mechanisms that allow a Web
                                      SHARING INFORMATION                                     219


component to invoke other Web resources are described in the section Invoking
Other Web Resources, page (235).

Using Scope Objects
Collaborating Web components share information via objects maintained as
attributes of four scope objects. These attributes are accessed with the
                         methods of the class representing the scope. Table 10–4
et ub i rt tA ] te s| te g [
lists the scope objects. Figure 10–1 shows the scoped attributes maintained by the
Duke’s Bookstore application.


Table 10–4 Scope Objects

 Scope
 Object            Class               Accessible From

                   .telvres.xavaj      Web components within a Web context (see Access-
 Web context
                   txetnoCtelvreS      ing the Web Context, page (238))

                                       Web components handling a request that belongs to
                     .telvres.xavaj
 session                               the session (see Maintaining Client
                   noisseSpttH.ptth
                                       State, page (239))

                   subtype of
 request           .telvres.xavaj      Web components handling the request
                   tseuqeRtelvreS

                    .telvres.xavaj     The JSP page that creates the object (see JavaServer
 page
                   txetnoCegaP.psj     Pages™ Technology)
220                                JAVA SERVLET TECHNOLOGY




      Figure 10–1 Duke’s Bookstore Scoped Attributes


      Controlling Concurrent Access to Shared Resources
      In a multithreaded server, it is possible for shared resources to be accessed con-
      currently. Besides scope object attributes, shared resources include in-memory
      data such as instance or class variables and external objects such as files, data-
      base connections, and network connections. Concurrent access can arise in sev-
      eral situations:
          • Multiple Web components accessing objects stored in the Web context
          • Multiple Web components accessing objects stored in a session
          • Multiple threads within a Web component accessing instance variables. A
            Web container will typically create a thread to handle each request. If you
            want to ensure that a servlet instance handles only one request at a time, a
            servlet can implement the                           interface. If a servlet
                                          l ed o Md ae rh T el gn i S
            implements this interface, you are guaranteed that no two threads will exe-
            cute concurrently in the servlet’s service method. A Web container can
            implement this guarantee by synchronizing access to a single instance of
            the servlet, or by maintaining a pool of Web component instances and dis-
            patching each new request to a free instance. This interface does not pre-
            vent synchronization problems that result from Web components
            accessing shared resources such as static class variables or external
            objects.
                                            SHARING INFORMATION                                     221


When resources can be accessed concurrently, they can be used in an inconsis-
tent fashion. To prevent this, you must control the access using the synchroniza-
tion techniques described in the Threads lesson in the Java Tutorial.
In the previous section we showed five scoped attributes shared by more than
one servlet:           ,     ,           ,              , and
                 re t nu oC t ih y cn er r uc t ra c B Dk oo b                . The
                                                                             r et n uo Cr ed r o
        attribute is discussed in the next section. The cart, currency, and counters
BD ko o b
can be set and read by multiple multithreaded servlets. To prevent these objects
from being used inconsistently, access is controlled by synchronized methods.
For example, here is the                   class:
                               re tn u oC .l it u

                                        { re tn uo C s sa l c ci lb u p
                                      ;r et nu o c tn i e ta vi r p
                                         { )( r et nu o C ci lb u p
                                            ; 0 = r et nu o c
                                                                   }
           { ) (r e tn uo C te g tn i d ez in o rh cn y s ci lb u p
                                       ; r et nu o c nr ut e r
                                                                   }
     { ) c t ni (r e tn uo C te s tn i d ez in o rh cn y s ci lb u p
                                            ; c = r et nu o c
                                       ; r et nu o c nr ut e r
                                                                   }
           { ) (r e tn uo C cn i tn i d ez in o rh cn y s ci lb u p
                                   ;) re t nu oc + +( nr ut e r
                                                                   }
                                                                      }

Accessing Databases
Data that is shared between Web components and is persistent between invoca-
tions of a J2EE application is usually maintained by a database. Web compo-
nents use the JDBC 2.0 API to access relational databases. The data for the
bookstore application is maintained in a database and accessed through the
helper class
BD ko oB . es ab a ta d         . For example,                      invokes the
                                                               t el vr e St pi ec e R
                    method to update the book inventory when a user makes a
                 s k oo By u b. BD ko o B
purchase. The
        s k oo By u b     method invokes            for each book contained in
                                                       k oo By ub
the shopping cart. To ensure the order is processed in its entirety, the calls to
          are wrapped in a single JDBC transaction. The use of the shared data-
k oo By u b
base connection is synchronized via the                              methods.
                                                    n o it ce n no C] es a el er |t e g[

     { no it p ec xE r ed rO s w or ht )t ra c t ra Cg n ip po hS ( sk oo By u b di o v ci lb u p
                                        ;) ( sm et I te g. tr a c = sm e ti n o it ce ll o C
                                                ;) ( ro ta re t i. sm et i = i ro ta re t I
                                                                                     { yrt
                                         ; ) "B Dk oo b "( et u bi rt tA t eg
                         . )( t xe tn o Ct el vr e St eg )B D ko oB ( = B Dk o ob
                     { n o it pe cx E te lv r eS s wo r ht ) (t i ni d i ov c il b up
                                                         ; BD ko ob BD ko o B et av i rp
                   { t e lv re S pt tH s d ne tx e t el vr e Sg ol a ta C ss a lc c il b up
context listener:
in their       method that points to the database helper object created by the Web ti n i
             ,         ) te lv re S tr aC w oh S
                                      , and           t el v re Ss l ia te Dk o oB t el vr eS g ol
                                                                initialize a variable
 a ta C te lv r eS er ot S ko oB
All the servlets that access the bookstore database (                        ,
ization process should throw    no it p ec xE el b al ia v an U
                                                         .
       method of the                                              te l vr eS
                               interface. A servlet that cannot complete its initial-      t i ni
initialize resources, and perform any other one-time activities by overriding the
customize this process to allow the servlet to read persistent configuration data,
delivers requests from clients, the Web container initializes the servlet. You can
After the Web container loads and instantiates the servlet class and before it
                                                           Initializing a Servlet
                                                                                           }
                                                                                      }
                                                                                    }
                                           ; )) ( eg as s eM te g. x qs
     + " : d el ia f k ca bl l oR "( no i tp ec xE r ed rO we n wo r ht
                                               ; )( no i tc en n oC es ae l er
                                         { )x qs no it pe c xE LQ S ( hc ta c }
                                                    ;) ) (e ga s se Mt eg . xe
        + " :d el i af n oi t ca sn a rT "( no i tp ec xE r ed rO we n wo r ht
                                                      ; )( no i tc en n oC es ae l er
                                                              ; )( kc a bl lo r. n oc
                                                                              { y rt
                                                      { ) xe n oi t pe cx E ( hc ta c }
                                                      ; )( no i tc en n oC es ae l er
                                                ;) e ur t( ti m mo Co t uA te s. n oc
                                                                 ; )( t im mo c. n oc
                                                                                    }
                                            ; )y ti tn a uq , d i( ko oB y ub
                           ;) (y t it na uQ t eg .i cs = yt i tn au q t ni
                                    ; )( dI k oo Bt eg . db = di g ni r tS
         ; )( m et It eg . ic s) s li at eD k oo B( = db s l ia te Dk o oB
;) (t x en .i ) me tI tr a Cg ni p po hS ( = ic s m e tI tr a Cg ni pp o hS
                                                     { )) (t x eN sa h .i ( el i hw
                                              ; )e s la f( ti m mo Co t uA te s. n oc
                                                            ; ) (n oi t ce nn oC t eg
                                    JAVA SERVLET TECHNOLOGY                                          222
                                             WRITING SERVICE METHODS                             223


                                                   w e n wo rh t ) ll un == B D ko ob ( f i
                  ;) " .e sa b at ad t e g t' nd l uo C" ( no it pe c xE el b al ia va n U
           }
      }


Writing Service Methods
  The service provided by a servlet is implemented in the                method of a
                                                                         e ci vr e s
       d oh t eM od  , the           methods (where
                       t el vr e Sc ir en e G        do h te Mcan take the value     ,    te G
          ,          ,      ,     ,      ) of an
  e ca r T t u P ts oP s no i tp O et el e D                 , or any other protocol-
                                                     t e lv re S pt tH
  specific methods defined by a class that implements the                interface. In
                                                                         t e lv re S
  the rest of this chapter, the term service method will be used for any method in a
  servlet class that provides a service to a client.
  The general pattern for a service method is to extract information from the
  request, access external resources, and then populate the response based on that
  information.
  For HTTP servlets, the correct procedure for populating the response is to first
  fill in the response headers, then retrieve an output stream from the response, and
  finally write any body content to the output stream. Response headers must
  always be set before a                      or
                                r et ir Wt n ir P                         is retrieved
                                                      ma er tS t up tu O te lv re S
  because the HTTP protocol expects to receive all headers before body content.
  The next two sections describe how to get information from requests and gener-
  ate responses.

  Getting Information from Requests
  A request contains data passed between a client and the servlet. All requests
  implement the                     interface. This interface defines methods for
                    t se uq eR t el vr e S
  accessing the following information:
      • Parameters, which are typically used to convey information between cli-
        ents and servlets
      • Object-valued attributes, which are typically used to pass information
        between the servlet container and a servlet or between collaborating serv-
        lets
      • Information about the protocol used to communicate the request and the
        client and server involved in the request
      • Information relevant to localization
224                                       JAVA SERVLET TECHNOLOGY



      For example, in                      the identifier of the book that a customer
                           t el vr e Sg ol at a C
      wishes to purchase is included as a parameter to the request. The following code
      fragment illustrates how to use the                  method to extract the identi-
                                                    re t em ar aP t eg
      fier:

                       ; )" d dA "( re t em ar a Pt eg .t s eu qe r = d Ik o ob g ni r tS
                                                            { )l l un = ! d Ik oo b( fi
          ; )d I ko ob ( sl ia te D ko oB t eg .B Dk o ob = k o ob s l ia te Dk o oB

      You can also retrieve an input stream from the request and manually parse the
      data. To read character data, use the                    object returned by the
                                                       re d ae Rd e re ff uB
      request’s            method. To read binary data, use the
                             r ed ae R te g                                       ma er t St up n It el vr e S
      returned by                 .
                 m a er tS t up nI te g
      HTTP servlets are passed an HTTP request object,                   t se uq e Rt el v re Sp tt H   , which
      contains the request URL, HTTP headers, query string, and so on.
      An HTTP request URL contains the following parts:

          ] gn i rt s y re uq [? ] ht ap ts eu qe r [] tr o p[ :] ts o h[ // :p t th

      The request path is further composed of the following elements:
          • Context path: A concatenation of a forward slash ( with the context      )/
            root of the servlet’s J2EE application.
          • Servlet path: The path section that corresponds to the component alias
            that activated this request. This path starts with a forward slash ( .                 )/
          • Path info: The part of the request path that is not part of the context path
            or the servlet path.
      If the context path is      , and the aliases are as listed in Table 10–5, then
                                g ol at a c/
      Table 10–6 gives some examples of how the URL will be broken down:


      Table 10–5 Aliases

       Pattern                                       Servlet

       */nwal/                                       telvreSnwaL

       psj.*/                                        telvreSPSJ
                                             WRITING SERVICE METHODS                                        225


Table 10–6 Request Path Elements

 Request Path                                   Servlet Path                        Path Info

 lmth.xedni/nwal/golatac/                       nwal/                               lmth.xedni/

 psj.kcabdeef/pleh/golatac/                     psj.kcabdeef/pleh/                  llun



Query strings are composed of a set of parameters and values. Individual param-
eters are retrieved from a request with the              method. There are two
                                                     r et em ar a Pt eg
ways to generate query strings:
    • A query string can explicitly appear in a Web page. For example, an
      HTML page generated by the                  could contain the link
                                               te lv r eS go l at aC

    > a /< tr aC oT d d A> "1 01 = dd A? g ol at ac / 1e ro ts k oo b/ " =f er h a <

       t el vr e Sg ol at a C   extracts the parameter named            dd A   as follows:

    ;) "d d A" (r et e ma ra P te g. ts e uq er = dI ko o b gn ir t S

    • A query string is appended to a URL when a form with a            HTTP                 TE G
      method is submitted. In the Duke’s Bookstore application,                       vr eS r ei hs a C
       t elgenerates a form, then a user name input to the form is appended to
      the URL that maps to                     , and finally
                                                te l vr eS t pi ec eR              t el vr e St pi e ce R
      extracts the user name using the                method.
                                        r e te ma ra P te g


Constructing Responses
A response contains data passed between a server and the client. All responses
implement the                    interface. This interface defines methods that
                   es n op se R te lv re S
allow you to do the following.
    • Retrieve an output stream to use to send data to the client. To send charac-
      ter data, use the                  returned by the response’s
                                 r et ir W tn ir P                                         r et ir W te g
      method. To send binary data in a MIME body response, use the                           vr eS
                         returned by
       m ae rt S tu pt u Ot el                           . To mix binary and text
                                                ma er t St up tu O te g
      data, for example, to create a multipart response, use a                     tu pt u Ot el v re S
               and manage the character sections manually.
       m a er tS
    • Indicate the content type (for example,             ), being returned by the
                                                          l mt h /t xe t
      response. A registry of content type names is kept by the Internet Assigned
      Numbers Authority (IANA) at:
226                                      JAVA SERVLET TECHNOLOGY


           se p yt a id e m/ st n em ng is s a/ an a i/ se to n n i/ u de .i si . pt f/ /: p tf

           • Indicate whether to buffer output. By default, any content written to the
             output stream is immediately sent to the client. Buffering allows content
             to be written before anything is actually sent back to the client, thus pro-
             viding the servlet with more time to set appropriate status codes and head-
             ers or forward to another Web resource.
           • Set localization information.
      HTTP response objects,        e s no ps e Rt el vr e Sp tt H   , have fields representing HTTP
      headers such as
           • Status codes, which are used to indicate the reason a request is not satis-
             fied.
           • Cookies, which are used to store application-specific information at the
             client. Sometimes cookies are used to maintain an identifier for tracking a
             user’s session (see Maintaining Client State, page (239)).
      In Duke’s Bookstore,                            generates an HTML page that dis-
                                 t el vr e Ss li at e Dk oo B
      plays information about a book that the servlet retrieves from a database. The
      servlet first sets response headers: the content type of the response and the buffer
      size. The servlet buffers the page content because the database access can gener-
      ate an exception that would cause forwarding to an error page. By buffering the
      response, the client will not see a concatenation of part of a Duke’s Bookstore
      page with the error page should an error occur. The            method then retrieves
                                                                        te G od
      a re ti r Wt ni rPfrom the response.
      For filling in the response, the servlet first dispatches the request to                    n aB
                   , which generates a common banner for all the servlets in the appli-
      t el vr eS r en
      cation. This process is discussed in the section Including Other Resources in the
      Response, page (235). Then the servlet retrieves the book identifier from a
      request parameter and uses the identifier to retrieve information about the book
      from the bookstore database. Finally, the servlet generates HTML markup that
      describes the book information and commits the response to the client by calling
      the es ol cmethod on the                .
                                     r et i rW tn i rP

           { t el vr e Sp tt H s dn et x e te l vr eS sl i at eD k oo B ss a lc c il b up
              , t se uq e r ts eu q eR te l vr eS pt t H( t eG o d di o v ci lb u p
                             ) es no ps e r es no p se Rt e lv re Sp t tH
              { no i tp ec x EO I ,n o it pe cx E te lv r eS s wo r ht
               r e ti rW e h t gn i ss ec ca er of eb sr ed a eh t es //
                       ; )" l mt h/ t xe t" (e p yT tn et n oC te s .e sn op s er
                                    ; )2 91 8( e zi Sr ef f uB te s .e sn op s er
                    ; )( re t ir Wt e g. es no p se r = t uo r e ti rW tn i rP
                                                                                                  }
                                                                                              }
                                                                        ; )( e so lc .t u o
                                           ;) " >l mt h/ < >y do b/ < "( nl t ni rp .t u o
                                                                                          }
                                                                                   }
                            ; )x e( n oi tp e cx Et el v re S w en w or h t
                                         ;) ( re ff uB t es er . es no ps e r
                           { ) x e no it p ec xE d nu oF to N ko oB ( h ct ac }
                                                                        ...
      + " > 2h /< " + ) (e l ti Tt e g. db + "> 2h < "( nl t ni rp .t u o
                    d en i at bo n o it am r of ni e h t tu o t ni rP / /
                                                                        ...
                       ;) dI k oo b( s li at eD k oo Bt e g. BD ko o b
                                                    = d b sl i at eD ko o B
                                                                            { yrt
                          ko ob eh t tu o ba n o it am ro f ni e h t dn a / /
                                                          { ) ll un =! d I ko ob ( f i
                ;) " dI ko o b" (r et e ma ra P te g. ts e uq er = dI ko o b gn ir t S
                       y al p si d ot ko ob eh t fo re if it n ed i e ht t eG / /
                      ; )e sn o ps er , t se uq e r( ed ul c ni .r e hc ta ps i d
                                                    )l l un = ! r eh ct a ps id ( f i
                                ;) "r en n ab /" ( re hc ta p si Dt s eu qe Rt e g
                                                   .) (t xe t no Ct e lv re St e g
                                         = r eh ct ap s id r eh c ta ps i Dt se uq e R
        r e su e ht ot r e nn ab e h t st e g ti ; r eh ct ap s id e h t te G / /
                                                             ; )" >d a eh /< > el ti t/ < +
                         )" n oi tp ir c se Dk o oB el ti T "( gn ir t St eg . se ga ss e m
                                                                   + > el ti t <> da eh < "
                                                        + "> lm th < "( nl t ni rp .t u o
                                                  e sn op s er e ht et ir w n eh t / /
227                                WRITING SERVICE METHODS
228                                         JAVA SERVLET TECHNOLOGY



        t e lv re Ss l ia te Dk o oB   generates a page that looks like Figure 10–2.




        Figure 10–2 Book Details


      Filtering Requests and Responses
        A filter is an object that can transform the header or content or both of a request
        or response. Filters differ from Web components in that they usually do not
        themselves create a response. Instead, a filter provides functionality that can be
        “attached” to any kind of Web resource. As a consequence, a filter should not
        have any dependencies on a Web resource for which it is acting as a filter, so that
                                           FILTERING REQUESTS AND RESPONSES                         229


it can be composable with more than one type of Web resource. The main tasks
that a filter can perform are as follows:
      • Query the request and act accordingly
      • Block the request-and-response pair from passing any further.
      • Modify the request headers and data. You do this by providing a custom-
        ized version of the request.
      • Modify the response headers and data. You do this by providing a custom-
        ized version of the response.
      • Interact with external resources.
Applications of filters include authentication, logging, image conversion, data
compression, encryption, tokenizing streams, and XML transformations.
You can configure a Web resource to be filtered by a chain of zero, one, or more
filters in a specific order. This chain is specified when the Web application con-
taining the component is deployed and is instantiated when a Web container
loads the component.
In summary, the tasks involved in using filters include
      • Programming the filter
      • Programming customized requests and responses
      • Specifying the filter chain for each Web resource

Programming Filters
The filtering API is defined by the         ,              , and
                                            ni a hC re t li F r et li F       g if no C re tl i F
interfaces in the                 package. You define a filter by implementing
                    t e lv re s. x av aj
the         interface. The most important method in this interface is the
      r et li F                                                                        li Fo d
ret  method, which is passed request, response, and filter chain objects. This
method can perform the following actions:
      • Examine the request headers.
      • Customize the request object if it wishes to modify request headers or
        data.
      • Customize the response object if it wishes to modify response headers or
        data
      • Invoke the next entity in the filter chain. If the current filter is the last filter
        in the chain that ends with the target Web component or static resource,
        the next entity is the resource at the end of the chain; otherwise, it is the
        next filter that was configured in the WAR. It invokes the next entity by
230                                           JAVA SERVLET TECHNOLOGY



             calling the             method on the chain object (passing in the request
                               r et l iF od
             and response it was called with, or the wrapped versions it may have cre-
             ated). Alternatively, it can choose to block the request by not making the
             call to invoke the next entity. In the latter case, the filter is responsible for
             filling out the response.
           • Examine response headers after it has invoked the next filter in the chain.
           • Throw an exception to indicate an error in processing.
      In addition to           , you must implement the
                           re t li Fo d                         and     t in imethods.
                                                                                   yo r ts ed
      The in method is called by the container when the filter is instantiated. If you
              ti
      wish to pass initialization parameters to the filter, you retrieve them from the
                     object passed to
      gi f no Cr et l iF                   .     t in i
      The Duke’s Bookstore application uses the filters                         and
                                                                            re tl iF r et nu o Ct iH
                     to increment and log the value of a counter when the entry and
      r e tl iF re d rO
      receipt servlets are accessed.
      In the             method, both filters retrieve the servlet context from the filter
              re tl i Fo d
      configuration object so that they can access the counters stored as context
      attributes. After the filters have completed application-specific processing, they
      invoke              on the filter chain object passed into the original
               re tl i Fo d                                                                     re t li Fo d
      method. The elided code is discussed in the next section.

           { r et li F s tn em e lp mi r e tl iF r et nu oC t iH s s al c la n if c il b up
                          ; ll un = gi fn o Cr et li f g if no C re tl i F et av i rp

                         )g i fn oC re t li f g if no Cr e tl iF (t i ni d i ov c il b up
                                              { n o it pe cx E te lv r eS s wo r ht
                                  ;g if n oC re tl i f = gi f no Cr e tl if .s i ht
                                                                                        }
                                                        { )( yo rt s ed d i ov c il b up
                                              ; ll u n = gi f no Cr e tl if .s i ht
                                                                                        }
                       , ts e uq er t s eu qe R te lv re S (r et li F od d i ov c il b up
                ) ni a hc n ia h Cr et l iF , es n op se r e sn op s eR te lv r eS
                          { no i tp ec x Et el vr e S ,n oi t pe cx E OI s wo r ht
                                              ) ll u n == g i fn oC r et li f( fi
                                                                    ;n ru t er
                           ; )( r et ir W gn ir tS we n = w s re t ir Wg ni r tS
                     ; )w s( re t ir Wt n ir P we n = r et i rw r e ti rW tn i rP
                       .g if no C re tl i f) re tn u oC ( = r et nu o c re tn u oC
                                               . )( tx e tn oC t el vr eS t eg
                                    ; )" re t nu oC ti h "( et u bi rt tA t eg
                                                           ;) ( nl tn i rp .r et i rw
                                ; )" == = == == == = == == =" ( nl tn i rp .r et i rw
                                              FILTERING REQUESTS AND RESPONSES                              231


                 + " : si s t ih f o r eb mu n e hT "( n lt ni r p. re ti r w
                                        ; ) )( re tn u oC cn i .r et nu o c
                           ; ) "= == = == == == = == == "( n lt ni r p. re ti r w
                                       gn ir ts gn it lu s er e h t go L / /
                                                          ; ) (h su l f. re ti r w
                             . )( tx e tn oC te l vr eS te g .g if n oC re tl i f
                         ; )) (g n ir tS o t. )( re f fu Bt e g. ws (g o l
                                                                             ...
                             ; )r ep p ar w ,t s eu qe r( r et li F od .n ia h c
                                                                             ...
          }
     }

Programming Customized Requests and Responses
There are many ways for a filter to modify a request or response. For example, a
filter could add an attribute to the request or insert data in the response. In the
Duke’s Bookstore example,                          inserts the value of the counter
                                      r e tl iF re t nu oC t iH
into the response.
A filter that modifies a response must usually capture the response before it is
returned to the client. The way to do this is to pass a stand-in stream to the
servlet that generates the response. The stand-in stream prevents the servlet from
closing the original response stream when it completes and allows the filter to
modify the servlet’s response.
To pass this stand-in stream to the servlet, the filter creates a response wrapper
that overrides the             or
                      re t ir Wt eg                    method to return this stand-in
                                          m ae rt S tu pt u Ot eg
stream. The wrapper is passed to the      r e tl iF od  method of the filter chain.
Wrapper methods default to calling through to the wrapped request or response
object. This approach follows the well-known Wrapper or Decorator pattern
described in Design Patterns: Elements of Reusable Object-Oriented Software
(Addison-Wesley, 1995). The following sections describe how the hit counter
filter described earlier and other types of filters use wrappers.
To override request methods, you wrap the request in an object that extends
                          or
r ep pa rW t se uq e Rt el vr e S                          . To override
                                           re p pa rW ts e uq eR t el vr eS p tt H
response methods, you wrap the response in an object that extends
                         or
r e pp ar We s no ps e Rt el vr e S                      .
                                        r ep p ar We s no ps eR t el vr eS p tt H
                       wraps the response in a
re t li Fr e tn uo Ct i H                                                    . The
                                                                         r ep pa r We sn o ps eR ra h C
wrapped response is passed to the next object in the filter chain, which is
                                                                    ko oB
                .                     writes its response into the stream created
                    te lv r eS er ot S ko oB t el v re Se ro t S
by
r e tl iF od . ni ah c      . When                    returns,
                                r ep p ar We sn o ps eR r ah C                  r et li F re tn u oC ti H
retrieves the servlet’s response from
 r e ti rW t ni rP                                   and writes it to a buffer. The
                                                                                          }
                                                                                        }
                                   ;) t up tu o( r et ir Wt n ir P w en n ru t er
                                          {) ( re ti rW t eg r et i rW tn i rP c il b up
                                                                                        }
                                   ;) ( re ti rW y ar rA ra h C we n = t up t uo
                                                           ; ) es no p se r( re p us
  {) es n op se r e sn op s eR te lv r eS pt t H( re pp a rW es no p se Rr a hC c il b up
                                                                                        }
                                            ; )( g ni rt So t .t up t uo n ru t er
                                                  { )( g ni rt So t g ni r tS c il b up
                                          ;t u pt uo r e ti rW ya r rA ra h C et av i rp
                                               { re pp a rW es no p se Rt e lv re Sp t tH
                                sd ne tx e r ep p ar We sn o ps eR r ah C ss a lc c il b up
                                                                            ;) ( es ol c. t uo
                                                      ;) )( g ni rt S ot .w ac ( et ir w. t uo
              ; )) (h t gn el . )( gn ir t So t. w ac (h tg n eL tn e tn oC te s .e sn op s er
                                               ; ) "> lm th / <> yd o b/ <n \" ( et ir w. w ac
                       ; ) "> re tn e c< >t n of /< " + ) (r et n uo Ct e g. re tn u oc
      + "> 'd er ' =r ol o c tn of < " + ) "r ot is i V" (g ni r tS te g .s eg as s em
                                       + "> re t ne c< >r e tn ec < n\ >p <" ( et ir w. w ac
                       ; ) )1 ) "> y do b/ < "( fO xe d ni .) (g n ir tS o t. re pp a rw
                              , 0( gn ir t sb us . )( gn ir t So t. r ep pa rw ( et ir w. w ac
                         ; )( r et ir Wy a rr Ar a hC w en = wa c r et ir W ya rr Ar a hC
                                           ;) re p pa rw , t se uq e r( re tl i Fo d. ni a hc
                                         ;) e sn op se r )e sn op s eR te l vr eS pt t H(
         ( r ep pa rW e sn op s eR ra hC we n = r ep pa r w re p pa rW es n op se Rr a hC
                                 ; )( re t ir Wt e g. es no p se r = t uo r e ti rW tn i rP
response stream.
header of the response, and finally writes the contents of the buffer to the
filter inserts the value of the counter into the buffer, resets the content length
                                    JAVA SERVLET TECHNOLOGY                                      232
                                    FILTERING REQUESTS AND RESPONSES                233


Figure 10–3 shows the entry page for Duke’s Bookstore with the hit counter.




Figure 10–3 Duke’s Bookstore Entry Page


Specifying Filter Mappings
A Web container uses filter mappings to decide how to apply filters to Web
resources. A filter mapping matches a filter to a Web component by name or to
Web resources by URL pattern. The filters are invoked in the order in which fil-
ter mappings appear in the filter mapping list of a WAR. You specify a filter
mapping list for a WAR in the                Filter Mapping inspector (see Filter
                               l o ot yo lp e d
Mapping, page (202)).
234                                 JAVA SERVLET TECHNOLOGY



      Table 10–7 contains the filter mapping list for the Duke’s Bookstore application.
      The filters are matched by servlet name and each filter chain contains only one
      filter.


      Table 10–7 Duke’s Bookstore Filter Mapping List

       Servlet Name                           Filter

       telvreSerotSkooB                       retliFretnuoCtiH

       telvreStpieceR                         retliFredrO



      You can map a filter to one or more Web resources, and you can map more than
      one filter to a Web resource. This is illustrated in Figure 10–4, where filter F1 is
      mapped to servlets S1, S2, and S3, filter F2 is mapped to servlet S2, and filter F3
      is mapped to servlets S1 and S2.




      Figure 10–4 Filter to Servlet Mapping

      Recall that a filter chain is one of the objects passed to the         method of a
                                                                   re tl iF o d
      filter. This chain is formed indirectly via filter mappings. The order of the filters
      in the chain is the same as the order in which filter mappings appear in the Web
      application deployment descriptor.
                                                   INVOKING OTHER WEB RESOURCES                              235


  When a filter is mapped to servlet S1, the Web container invokes the                        r et li F od
  method of F1. The               method of each filter in S1’s filter chain is invoked
                            re tl i Fo d
  by the preceding filter in the chain via the                     method. Since S1’s
                                                                     r e tl iF o d. ni ah c
  filter chain contains filters F1 and F3, F1’s call to                     invokes the
                                                            re t li Fo d .n ia hc
  re tl iF o dmethod of filter F3. When F3’s               method completes, control
                                                                               r e tl iF od
  returns to F1’s             method.
                      re tl i Fo d


Invoking Other Web Resources
  Web components can invoke other Web resources in two ways: indirect and
  direct. A Web component indirectly invokes another Web resource when it
  embeds in content returned to a client a URL that points to another Web compo-
  nent. In the Duke’s Bookstore application, most Web components contain
  embedded URLs that point to other Web components. For example,                              tp ie c eR
           indirectly invokes the
                     t el vr e S                     through the embedded URL
                                              te lv r eS go l at aC
                         .
  g ol at a c/ 1e r ot sk oo b /
  A Web component can also directly invoke another resource while it is execut-
  ing. There are two possibilities: it can include the content of another resource, or
  it can forward a request to another resource.
  To invoke a resource available on the server that is running a Web component,
  you must first obtain a                      object using the
                                   r e hc ta ps i Dt se uq e R                      si Dt s eu qe R te g
                   method.
  ) "L RU " (r eh ct a p
  You can get a                          object from either a request or the Web con-
                      re hc t ap si Dt s eu qe R
  text; however, the two methods have slightly different behavior. The method
  takes the path to the requested resource as an argument. A request can take a rel-
  ative path (that is, one that does not begin with a ), but the Web context requires
                                                                   /
  an absolute path. If the resource is not available, or if the server has not imple-
  mented a                          object for that type of resource,
                r e hc ta p si Dt se u qe R                                         si Dt s eu qe R te g
            will return null. Your servlet should be prepared to deal with this
  r eh ct a p
  condition.

  Including Other Resources in the Response
  It is often useful to include another Web resource, for example, banner content or
  copyright information, in the response returned from a Web component. To
  include another resource, invoke the            method of a
                                                     e d ul cn i                r eh ct a ps iD t se uq eR
  object:

       ;) es no p se r ,t s eu qe r (e du lc n i
                                                                                             }
                                                                                        }
     ;) " > rb < > rh < ;p s bn & > rb <" + "> re tn e c/ <" + "> 1h / <"
+ "> tn of / <e ro t sk oo B> " \k ca l b" \= ro l oc " \3 + "\ =e z is t no f <"
                                                 + " >" \f i g. sk o ob .e ku d /"
                   + ) (h ta P tx et n oC te g. t se uq er + "" \ =c rs g m i<
+ "> tn of / < s' e ku D> "\ 6 60 0C C #" \= ro l oc " \3 + "\ =e z is t no f <"
                 + "> 1h <" + "; p sb n& > r b< > rh < " + " >r et ne c <"
                 + "> "\ ff f ff f# " \= ro lo c gb y do b <" (n l tn ir p. t uo
                      ; )( re t ir Wt e g. es no p se r = t uo r e ti rW tn i rP
                            { no i tp ec x EO I ,n o it pe cx E te lv r eS s wo r ht
                                         ) es no ps e r es no p se Rt e lv re Sp t tH
                    , t se uq e r ts eu q eR te l vr eS pt t H( t so P od d i ov c il b up
                                                                                         }
     ;) " > rb < > rh < ;p s bn & > rb <" + "> re tn e c/ <" + "> 1h / <"
+ "> tn of / <e ro t sk oo B> " \k ca l b" \= ro l oc " \3 + "\ =e z is t no f <"
                                                 + " >" \f i g. sk o ob .e ku d /"
                   + ) (h ta P tx et n oC te g. t se uq er + "" \ =c rs g m i<
+ "> tn of / < s' e ku D> "\ 6 60 0C C #" \= ro l oc " \3 + "\ =e z is t no f <"
                 + "> 1h <" + "; p sb n& > r b< > rh < " + " >r et ne c <"
                 + "> "\ ff f ff f# " \= ro lo c gb y do b <" (n l tn ir p. t uo
                      ; )( re t ir Wt e g. es no p se r = t uo r e ti rW tn i rP
                           { no i tp ec x EO I ,n o it pe cx E te lv r eS s wo r ht
                                        ) es no ps e r es no p se Rt e lv re Sp t tH
                     , ts eu q er t se u qe Rt e lv re Sp t tH ( te G od d i ov c il b up
                       { t el vr e Sp tt H s dn et x e te lv r eS re n na B ss a lc c il b up
                can be dispatched from either method in a calling servlet.      t el v re Sr en n aB
   . Note that both the        and            t so P od       te Go d
                                            methods are implemented because                     t el
 v re S re nn a B
The banner for the Duke’s Bookstore application is generated by
                affects the headers of the response.
) that   e ik o oC te s
              • It cannot set headers or call any method (for example,
              • It can write to the body of the response and commit a response.
in what it can do with the response object:
let. An included Web component has access to the request object, but it is limited
then include the result of the execution in the response from the containing serv-
the request to the included Web component, execute the Web component, and
includes. If the resource is a Web component, the effect of the method is to send
If the resource is static, the                        e du lc ni
                                       method enables programmatic server-side
                                       JAVA SERVLET TECHNOLOGY                                         236
                                            INVOKING OTHER WEB RESOURCES                             237


Each servlet in the Duke’s Bookstore application includes the result from                     na B
             with the following code:
t e lv re Sr e n

                                             = r eh ct ap s id r eh c ta ps i Dt se uq e R
     ; )" re nn a b/ "( r eh ct ap s iD ts e uq eR te g .) (t xe t no Ct e lv re St e g
                                                        )l l un = ! r eh ct a ps id ( f i
                           ; )e sn o ps er ,t se uq e r( ed ul c ni .r e hc ta ps i d
                                                                                         }

Transferring Control to Another Web Component
In some applications, you might want to have one Web component do prelimi-
nary processing of a request and have another component generate the response.
For example, you might want to partially process a request and then transfer to
another component depending on the nature of the request.
To transfer control to another Web component, you invoke the                method
                                                                               d r aw ro f
of a                       . When a request is forwarded, the request URL is set to
     r eh ct a ps iD ts e uq eR
the path of the forwarded page. If the original URL is required for any process-
ing, you can save it as a request attribute. The             servlet, used by a ver-
                                                         re h ct ap si D
sion of the Duke’s Bookstore application described in the section A Template
Tag Library, page (308), saves the path information from the original URL,
retrieves a
      re h ct ap s iD ts eu q eR   from the request, and then forwards to the JSP
page                 .
                     p s j. et al p me t

             { t el v re Sp tt H s dn e tx e re h ct ap si D s sa l c ci lb u p
        , ts eu q er t se u qe Rt e lv re Sp t tH (t eG o d di o v ci lb u p
                       { ) e sn op se r e sn op s eR te l vr eS pt t H
            , "n ee r cS de t ce le s" ( et ub ir t tA te s .t se uq e r
                        ; )) (h t aP te lv r eS te g .t se uq e r
           .t se uq e r = r eh ct ap s id r eh c ta ps i Dt se uq e R
     ; )" ps j .e ta lp m et /" ( re hc ta p si Dt s eu qe Rt e g
                                    )l l un = ! r eh ct a ps id ( f i
     ; )e sn o ps er , t se uq e r( dr aw r of .r e hc ta ps i d
                                                                           }
      , t se uq e r ts eu q eR te l vr eS pt t H( ts oP o d di o v ci lb u p
                                                                         ...
                                                                              }

The           method should be used to give another resource responsibility for
      d r aw ro f
replying to the user. If you have already accessed a                           or
                                                                   m a er tS t up tu Ot e lv re S
              object within the servlet, you cannot use this method; it throws an
                re t ir Wt ni r P
                          .
n oi tp ec x Ee ta t Sl ag el l I
                                                                                         }
                                                                                      }
                                                                               . ..
                      ; )) (g n ir tS o t. )( re f fu Bt eg . ws (g o l. tx et n oc
                                                                               . ..
                                           ; )) (r et n uo Cc n i. re tn u oc
                 + " :s i s ti h f o re bm u n eh T" ( nl tn i rp .r et i rw
                                                                               . ..
                                   ; )" re t nu oC ti h "( et u bi rt tA t eg
                             . t xe tn o c) re tn u oC ( = r et nu o c re tn u oC
                                              ; )( tx e tn oC t el vr eS t eg
                        .g if n oC re t li f = t xe tn oc tx et n oC te lv r eS
                   ; )w s( re t ir Wt n ir P we n = r et i rw r e ti rW tn i rP
                         ; )( r et ir W gn ir tS we n = w s re t ir Wg ni r tS
                                                                               . ..
                        { no i tp ec x Et el vr e S ,n oi t pe cx E OI s wo r ht
              ) ni a hc n ia h Cr et l iF , es n op se r e sn op s eR te lv r eS
                     , ts e uq er t s eu qe R te lv re S (r et li F od d i ov c il b up
                          ; ll un = gi fn o Cr et li f g if no C re tl i F et av i rp
          { r et li F s tn em e lp mi r e tl iF r et nu oC t iH s s al c la n if c il b up
is recorded with the context’s    method.              go l
with the context’s                                     et u bi rt tA t eg
                                  method. The incremented value of the counter
by servlets that are running concurrently. A filter retrieves the counter object
counter’s access methods are synchronized to prevent incompatible operations
from Controlling Concurrent Access to Shared Resources, page (220) that the
Responses, page (228). The filters store a counter as a context attribute. Recall
         and                                                  re t li Fr ed r O
                           , discussed in the section Filtering Requests and            r et l iF
 r et n uo Ct i H. sr et l if
The Web context is used by the Duke’s Bookstore filters
                                   Logging capabilities                                   •
                                   Object-valued attributes                               •
                                   Resources associated with the Web context              •
                                   Initialization parameters                              •
        method. The Web context provides methods for accessing:                        tx et n oC
 t el v re St e ginterface. You retrieve the Web context with the           tx et n oC te lv r eS
The context in which Web components execute is an object that implements the
                                    Accessing the Web Context
                                   JAVA SERVLET TECHNOLOGY                                          238
                                             MAINTAINING CLIENT STATE                      239


Maintaining Client State
  Many applications require a series of requests from a client to be associated with
  one another. For example, the Duke’s Bookstore application saves the state of a
  user’s shopping cart across requests. Web-based applications are responsible for
  maintaining such state, called a session, because the HTTP protocol is stateless.
  To support applications that need to maintain state, Java Servlet technology pro-
  vides an API for managing sessions and allows several mechanisms for imple-
  menting sessions.

  Accessing a Session
  Sessions are represented by an                    object. You access a session by
                                          n oi s se Sp tt H
  calling the             method of a request object. This method returns the cur-
                n oi s se St eg
  rent session associated with this request, or, if the request does not have a ses-
  sion, it creates one. Since                may modify the response header (if
                                     n oi ss eS t eg
  cookies are the session tracking mechanism), it needs to be called before you
  retrieve a              or
              re t ir Wt ni r P                       .
                                   ma er t St up t uO te lv r eS


  Associating Attributes with a Session
  You can associate object-valued attributes with a session by name. Such
  attributes are accessible by any Web component that belongs to the same Web
  context and is handling a request that is part of the same session.
  The Duke’s Bookstore application stores a customer’s shopping cart as a session
  attribute. This allows the shopping cart to be saved between requests and also
  allows cooperating servlets to access the cart.                      adds items to the
                                                          te lv re S go la t aC
  cart;
  t el vr e St ra Cw o hS    displays, deletes items from, and clears the cart; and
                     retrieves the total cost of the books in the cart.
          t el vr e Sr ei hs a C

       { te l vr eS p tt H sd n et xe te lv re S re ih sa C s sa l c ci lb u p
       , t se uq e r ts eu q eR te l vr eS pt t H( t eG o d di o v ci lb u p
                          ) e sn op se r e sn op s eR te l vr eS pt t H
             { n oi t pe cx E OI , no i tp ec xE t el vr e S sw or h t

                  t ra c g ni pp o hs d n a no is s es s 'r e su e h t te G / /
                  ; )( n oi ss eS t eg .t s eu qe r = n oi ss e s no i ss eS pt t H
                                                        = t ra c t ra C gn ip po h S
                                             . n oi ss es ) tr aC g ni pp oh S (
240                                       JAVA SERVLET TECHNOLOGY


                                    ;) "t ra c "( et u bi rt tA t eg
                                                                                       . ..
                       sk o ob s ' re su e h t fo ec ir p l at ot e h t en i mr et eD //
                                               ;) ( la to Tt e g. tr ac = la t ot e lb u od

      Notifying Objects That Are Associated with a Session
      Recall that your application can notify Web context and session listener objects
      of servlet life-cycle events (see Handling Servlet Life-Cycle
      Events, page (216)). You can also notify objects of certain events related to their
      association with a session, such as the following:
           • When the object is added to or removed from a session. To receive this
             notification, your object must implement the               n oi s se Sp t tH .p tt h .x av a j
                                 interface
               re ne t si Lg n id ni B            .
           • When the session to which the object is attached will be passivated or acti-
             vated. A session will be passivated or activated when it is moved between
             virtual machines or saved to and restored from persistent storage. To
             receive this notification, your object must implement the
                                                                interface
               r en e ts iL no i ta vi t cA no is s eS pt tH . pt th . xa va j           .


      Session Management
      Since there is no way for an HTTP client to signal that it no longer needs a ses-
      sion, each session has an associated timeout so that its resources can be
      reclaimed. The timeout period can be accessed with a session’s                  I xa M ]t es | te g[
                         methods. You can also set the timeout period in
      l av re t nI ev it c an                                                         :
                                                                                      l o ot yo lp e d
           1. Select the WAR.
           2. Select the General tab.
           3. Enter the timeout period in the Advanced box.
      To ensure that an active session is not timed out, you should periodically access
      the session via service methods because this resets the session’s time-to-live
      counter.
      When a particular client interaction is finished, you use the session’s                    i l av ni
      e t admethod to invalidate a session on the server side and remove any session
      data.
      lows:
      If cookies are turned off, the session is encoded in the Check Out URL as fol-
                                                               ; )" > gn or t s/ <> a/ < "
                         + )" tr aC r ae lC " (g ni rt S te g. se g as se m + " >" \ "
                                                 + ) "r a el c= ra e lC ?t r ac wo hs / "
                          + ) (h t aP tx et n oC te g .t se uq e r( LR Ue d oc ne . es no ps e r
                                                                    + " "\ = fe rh a < "
                                            + "; ps bn & ; ps bn & ; ps b n& > a/ < "
                           + ) "t uo k ce hC " (g ni rt S te g. se g as se m + " >" \ "
      + ) "r e ih sa c/ " + ) (h t aP tx et n oC te g .t se uq e r( LR Ue d oc ne . es no ps e r
                                                                    + " "\ = fe rh a < "
                                            + "; ps bn & ; ps bn & ; ps b n& > a/ < "
               + ) " gn ip p oh Se un i tn oC " (g ni rt S te g. se g as se m + " >" \ "
      + ) "g o la ta c/ " + ) (h t aP tx et n oC te g .t se uq e r( LR Ue d oc ne . es no ps e r
                          + " " \= fe r h a< >g n or ts < >p < ;p s bn & >p < "( nl t ni rp .t u o
      of the shopping cart display page as follows:
      The        method of                           t el vr e St ra Cw o hS
                                                encodes the three URLs at the bottom     t eG od
      unchanged.
      in the URL only if cookies are disabled; otherwise, it returns the URL
      method on all URLs returned by a servlet. This method includes the session ID
      ) LR U( L RU ed o cn e
      client turns off cookies. You do this by calling the response’s
      tracking is enabled by allowing the application to rewrite a URL whenever the
      If your application makes use of session objects, you must ensure that session
      rewrite any URL that is returned to the client.
      methods require the client to accept cookies or require the Web component to
      which involve passing an identifier between the client and server. The main
      A Web container can use several methods to associate a session with a user, all of
                                                                         Session Tracking
                                                                                     ...
                                                         ; )( et ad i la vn i .n oi ss e s
                    n oi ss e s eh t e ta di l av ni        d ev ie c er t n em ya P / /
                       ; )( n oi ss eS t eg .t s eu qe r = n oi ss e s no i ss eS pt t H
                       t ra c g ni pp o hs d n a no is s es s 'r e su e h t te G / /
           { n oi t pe cx EO I , no i tp ec xE t el vr e S sw or h t
                        ) es n op se r e sn op s eR te l vr eS pt t H
                         , t se uq e r ts eu q eR te l vr eS pt t H( ts oP o d di o v ci lb u p
                          { te l vr eS p tt H sd n et xe te lv re S tp ie ce R s sa l c ci lb u p
      ent’s session, so it has responsibility for invalidating the session:
      The bookstore application’s              te l vr eS tp i ec eR
                                                         is the last servlet to access a cli-
241                               MAINTAINING CLIENT STATE
242                                            JAVA SERVLET TECHNOLOGY


             ; re ih sa c /1 er o ts ko ob / 08 08 : ts oh la c ol // :p t th
                                       1b ez sf 7 o0 c= d in oi ss e sj

         If cookies are turned on, the URL is simply

             re ih sa c /1 er o ts ko ob / 08 08 : ts oh la c ol // :p t th


      Finalizing a Servlet
         When a servlet container determines that a servlet should be removed from ser-
         vice (for example, when a container wants to reclaim memory resources, or
         when it is being shut down), it calls the            method of the
                                                               y o rt se d           inter-
                                                                                    t el v re S
         face. In this method, you release any resources the servlet is using and save any
         persistent state. The following          method releases the database object cre-
                                                 y o rt se d
         ated in the t in imethod described in Initializing a Servlet, page (222):

             { )( yo r ts ed d i ov c il b up
                    ;l lu n = B Dk o ob
                                            }

         All of a servlet’s           methods should be complete when a servlet is
                                 e c iv re s
         removed. The server tries to ensure this completion by calling the                yo rt s ed
         method only after all service requests have returned or after a server-specific
         grace period, whichever comes first.
         If your servlet has potentially long-running service requests, use the techniques
         described below to do the following.
             • Keep track of how many threads are currently running the                    ec iv r es
               method
             • Provide a clean shutdown by having the            method notify long-run-
                                                                      y o rt se d
               ning threads of the shutdown and wait for them to complete
             • Have the long-running methods poll periodically to check for shutdown
               and, if necessary, stop working, clean up, and return

         Tracking Service Requests
         To track service requests, include in your servlet class a field that counts the
         number of service methods that are running. The field should have synchronized
         access methods to increment, decrement, and return its value.
                                                           ;g al f = n wo D gn it tu h s
                                  { )g al f n ae lo o b( nw oD g ni tt uh S te s d et ce to r p
                                             n wo Dg n it tu hs ro f sd o ht em ss ec cA / /
                                                                                          ...
                                                   ; n wo Dg ni t tu hs n a el oo b e ta vi r p
                                  { te l vr eS pt t H sd n et xe e l pm ax En w od tu h S ci lb u p
      The field should have the usual access methods:
      ods that it is time to shut down. For this notification, another field is required.
      is to check the service counter. Another part is to notify the long-running meth-
      resources until all of the service requests have completed. One part of doing this
      To ensure a clean shutdown, your               y or t se d
                                                   method should not release any shared
                                              Notifying Methods to Shut Down
                                                                                                    }
                                                                                                  }
                                                       ;) ( do ht eM e ci vr e Sg ni va e l
                                                                                  { y ll an if }
                                                    ;) ps e r ,q er ( ec iv r es .r ep u s
                                                                                           { yrt
                                                             ; )( d oh te Me c iv re S gn ir et n e
              { no i tp ec xE O I, no i tp ec xE t el vr e S sw or h t
                                )p se r e sn op s eR te l vr eS pt t H
                               , q er t s eu qe Rt e lv re S pt tH (e c iv re s d io v d et ce to r p
      original           method’s functionality:                                     e ci v re s
                                 ec iv re s .r ep u s
            method. The new method should call                    to preserve all of the            ec i v
       re s
      is one of the few times that your          t el v re Sp t tH
                                                    subclass should override the
      is entered and should decrement the counter each time the method returns. This
      The            method should increment the service counter each time the method     ec i vr es
                                                                                                 }
                                                                                               }
                                                         ; r et nu oC e ci vr e s nr ut e r
                                { ) (s ec iv r eS mu n t ni d e zi no rh c ny s d et ce to r p
                                                                                               }
                                                                 ; r et nu o Ce ci vr e s
                 { ) (d oh t eM ec i vr eS gn i va el di ov d e zi no rh c ny s d et ce to r p
                                                                                               }
                                                                 ; ++ r et nu o Ce ci vr e s
                { )( do ht e Me ci v re Sg ni r et ne di ov d e zi no rh c ny s d et ce to r p
                                           re t nu oC e ci vr es ro f sd o ht em ss ec cA / /
                                                                                             ...
                                                 ; 0 = r et nu o Ce ci vr e s tn i e ta vi r p
                                 { te l vr eS pt t H sd n et xe e l pm ax En w od tu h S ci lb u p
243                                      FINALIZING A SERVLET
                                                                                        }
                                                                                   }
                                                                             }
                                                                     . ..
                          { ) e n oi tp ec x Ed et pu r re tn I ( hc ta c }
                          ; ) i( no it a re pO gn i nn uR g no Lf Ot r ap
                                                                        { y rt
                                       { )+ + i ;) )( n wo Dg n it tu hS s i!
                               && )o Do T ff ut Sf O st ol < i( ( ; 0 = i( r of
                                                                                . ..
                                                     { ) . .. (t s oP od d i ov c il b up
work, if necessary.
value of the field that notifies them of shutdowns and should interrupt their
ods behave politely. Methods that might run for a long time should check the
The final step in providing a clean shutdown is to make any long-running meth-
                       Creating Polite Long-Running Methods
                                                                                       }
                                                                               }
                                                                           }
                          { ) e n oi tp ec x Ed et pu r re tn I ( hc ta c }
                                   ; ) la vr et n i( pe e ls .d ae r hT
                                                                      { y rt
                                            { )0 > )( se c iv re S mu n( el i hw
                     /* .p ot s o t sd o ht em e c iv re s e ht r o f ti aW */
                                                                                }
                                            ; )e ur t( n wo Dg n it tu hS t es
                                               { ) 0 > )( s ec iv r eS mu n( fi
          / * .p o ts o t m eh t l le t , er a er e ht f i d na , g ni nn ur */
* / sd o ht em e c iv re s l li ts er a e re ht r e ht eh w e es o t k ce hC */
                                                      { )( yo r ts ed d i ov c il b up
                                                                         down follows:
method using these fields to provide a clean shut-         y o rt se d   An example of the
                                                                                       }
                                                                                 }
                                               ; nw oD g ni tt u hs n ru t er
                              { ) (n wo D gn it tu h Ss i na e lo ob de tc et o rp
                                                                                 }
                                 JAVA SERVLET TECHNOLOGY                                     244
                 11
 JavaServer Pages™
        Technology
                                                          Stephanie Bodoff



JAVASERVER Pages™ (JSP™) technology allows you to easily create Web
content that has both static and dynamic components. JSP technology projects
all the dynamic capabilities of Java Servlet technology but provides a more natu-
ral approach to creating static content. The main features of JSP technology are:
    • A language for developing JSP pages, which are text-based documents
      that describe how to process a request and construct a response
    • Constructs for accessing server-side objects
    • Mechanisms for defining extensions to the JSP language
JSP technology also contains an API that is used by developers of Web contain-
ers, but this API is not covered in this chapter.

In This Chapter
          What Is a JSP Page? 246
          The Example JSP Pages 249
          The Life Cycle of a JSP Page 253
               Translation and Compilation 253
               Execution 254
          Initializing and Finalizing a JSP Page 256
          Creating Static Content 257

                                                                                    245
246                                         JAVASERVER PAGES™ TECHNOLOGY


                    Creating Dynamic Content 257
                        Using Objects within JSP Pages 257
                        JSP Scripting Elements 260
                    Including Content in a JSP Page 263
                    Transferring Control to Another Web Component 264
                        Param Element 265
                    Including an Applet 265
                    Extending the JSP Language 267


      What Is a JSP Page?
        A JSP page is a text-based document that contains two types of text: static tem-
        plate data, which can be expressed in any text-based format, such as HTML,
        SVG, WML, and XML; and JSP elements, which construct dynamic content. A
        syntax card and reference for the JSP elements are available at:

             x a tn ys #l m th .l a ci nh ce t /p sj / st cu do r p/ mo c .n us .a v aj // :p t th

        The Web page in Figure 11–1 is a form that allows you to select a locale and dis-
        plays the date in a manner appropriate to the locale.




        Figure 11–1 Localized Date Form

        The source code for this example is in the                                m ax e /l ai r ot ut ee 2 j
                             directory created when you unzip the tutorial bundle. The
        e ta d/ be w /c rs /s e lp
        JSP page
        p sj .x e dn i       used to create the form appears below; it is a typical mix-
        ture of static HTML markup and JSP elements. If you have developed Web
        pages, you are probably familiar with the HTML document structure statements
                    > "e ta D t eG "= e ul av " t im bu S "= em an "t im bu s "= ep y t tu pn i <
                                                                                         > tc el es / <
                                                                                                    >%
                                                                                                 }
                                                                                          }
                                                                                                    %<
                                       >n o it po / < > %e la c ol =% < >n oi tp o <
                                                                                                    >%
                                                                               { es le }
                                                                                                    %<
                        >n oi t po /< >% e la co l =% < > de t ce le s n oi tp o <
                                                                                                    >%
                                { )) el a co l( s la uq e. e la co L de tc el e s
                                            & & l lu n = ! el ac o Ld et c el es ( f i
                                      ; )( tx e n. i) gn i rt S( = el ac o l gn ir t S
                                                                 { ) )( tx e Ns ah . i( e li h w
                    ;) (r o ta re t i. )( se m aN el a co Lt eg . se la co l = i ro ta re t I
          ; )" e la co l" ( re te m ar aP te g .t se u qe r = e la co Ld e tc el e s gn ir t S
                                                                                                    %<
                                                                        >e la co l =e ma n t ce le s <
                                                                                 > b/ <: e la co L> b <
            > "t so p "= do ht e m "p s j. xe dn i "= no i tc a "m r oF el ac o l" =e m an m ro f <
                                                                    > /" se l ac oL y M" =s sa l c
                               " no it a ci lp pa " =e po c s "s el a co l" =d i n ae B es u: ps j <
                                                                    > " et ih w" = ro lo c gb y do b <
                                  > da e h/ <> el t it /< s et aD d e zi la co L >e lt i t< >d ae h <
                                                                                              >l mt h <
               > % " 5 95 88 OS I= t es ra hc ;l mt h /t xe t" = ep yT tn e tn oc eg ap @ % <
                                    >% "s el ac o Ly M, * .l it u. a va j" =t r op mi eg ap @ % <
        includes the response in the response from the calling page.
      • Thep sj .e t ad     element sends a request to another page (      ed ul c ni :p sj
                                                                                ) and
        response.
      • Expressions (                                          >% . . . =% <
                                      ) insert the value of the locale name into the
        text into the output.
        iterate over a collection of locale names, and conditionally insert HTML
      • Scriptlets (        el a co l
                                ) retrieve the value of the            > % .. . % <
                                                                   request parameter,
        locales and initializes a variable that points to that object.
      • The                                                                n ae B es u: ps j
                             element creates an object containing a collection of
        and the                                                           se la c oL yM
                              class, and set the content type returned by the page.
               li t u. av aj
      • Directives (<%@ page ... %>) import classes in the                   package
      the following types of JSP constructs:
      (        ) and a menu (                                     > tc e le s<
                                      ). The lines in bold in the example code contain          > m ro f<
      (        ,        , and so on) and the HTML statements that create a form       > y do b< > d ae h<
247                                     WHAT IS A JSP PAGE?
248                                       JAVASERVER PAGES™ TECHNOLOGY


                                              >m ro f /<
          > / "p sj .e t ad "= e ga p ed u lc ni :p s j<
                                              >y do b /<
                                              >l mt h /<

      To build, deploy, and execute this JSP page:
          1. Go to                            and build the example by executing
                      se lp ma x e/ la i ro tu te e 2j                                               tn a
                  (see How to Build and Run the Examples, page (xxii)).
             e ta d
          2. Create a J2EE application called          . p pA et aD
             a. Select File→New→Application.
             b. In the file chooser, navigate to                              m ax e /l ai r ot ut ee 2 j
                                     .
                 e ta d /b ew /c r s/ se l p
             c. In the File Name field, enter        .
                                                     pp A et aD
             d. Click New Application.
             e. Click OK.
          3. Create the WAR and add the Web components to the          application.
                                                                               pp Ae t aD
             a. Select File→New→Web Component.
             b. Select          from the Create New WAR File In Application combo
                          p pA et a D
                box.
             c. Enter          in the WAR Display Name field.
                         R A We ta D
             d. Click Edit.
             e. Navigate to                                               . Select
                      et a d/ be w/ d li ub / se lp ma x e/ la i ro tu te e 2j
                            ,          ,
                 ss al c. s el ac oL y M               , and                    and
                                                 s sa lc . et aD yM p sj .e t ad ps j .x ed n i
                click Add, then click Finish.
             f. Click Next.
             g. Click JSP in the Web Component radio button, and then click Next.
             h. Select             from the JSP Filename combo box. Click Finish.
                          ps j. xe d ni
          4. Enter the context root.
             a. Select          .
                          pp Ae t aD
             b. Select the Web Context tab.
             c. Enter      .
                         e ta d
          5. Deploy the application.
             a. Select Tools→Deploy.
             b. Click Finish.
          6. Invoke the URL       e ta d/ 0 00 8: > ts oh </ / :p tt h   in a browser.
                                            THE EXAMPLE JSP PAGES                             249


  You will see a combo box whose entries are locales. Select a locale and click Get
  Date. You will see the date expressed in a manner appropriate for that locale.


The Example JSP Pages
  To illustrate JSP technology, this chapter rewrites each servlet in the Duke’s
  Bookstore application introduced in The Example Servlets, page (211) in as a
  JSP page. Table 11–1 lists the functions and their corresponding JSP pages.


  Table 11–1 Duke’s Bookstore Example JSP Pages

   Function                                            JSP Pages

   Enter the bookstore                                 psj.erotskoob

   Create the bookstore banner                         psj.rennab

   Browse the books offered for sale                   psj.golatac

   Put a book in a shopping cart                       psj.golatac    and   psj.sliatedkoob

   Get detailed information on a specific book         psj.sliatedkoob

   Display the shopping cart                           psj.tracwohs

   Remove one or more books from the shopping cart     psj.tracwohs

   Buy the books in the shopping cart                  psj.reihsac

   Receive an acknowledgement for the purchase         psj.tpiecer



  The data for the bookstore application is still maintained in a database. However,
  two changes are made to the database helper object                       :
                                                             BD k oo B. e sa ba ta d
      • The database helper object is rewritten to conform to JavaBeans compo-
        nent design patterns as described in . This change is made so that JSP
        pages can access the helper object using JSP language elements specific
        to JavaBeans components.
      • Instead of accessing the bookstore database directly, the helper object goes
        through an enterprise bean. The advantage of using an enterprise bean is
        that the helper object is no longer responsible for connecting to the data-
250                                          JAVASERVER PAGES™ TECHNOLOGY



               base; this job is taken over by the enterprise bean. Furthermore, because
               the EJB container maintains the pool of database connections, an enter-
               prise bean can get a connection quicker than the helper object can. The rel-
               evant interfaces and classes for the enterprise bean are the
                                            home interface,
                               em oH B JE BD ko o B. es a ba ta d                   remote
                                                                    B J EB Dk oo B .e sa b at ad
               interface, and the
               B J EB Dk oo B .e sa b at ad              implementation class, which con-
               tains all the JDBC calls to the database.
      The implementation of the database helper object follows. The bean has two
      instance variables: the current book and a reference to the database enterprise
      bean.

                                 { BD k oo B ss a lc c il b up
                   ;" 0" = dI ko ob gn ir t S et av i rp
           ; ll un = es ab a ta d BJ E BD ko o B et av i rp

                              { no it p ec xE s w or ht ) ( B Dk o oB c il b up
                                                                                  }
                          { )d I ko ob gn ir tS ( dI ko oB t es d i ov c il b up
                                              ;d Ik oo b = d I ko ob .s i ht
                                                                                  }
                { )e s ab at ad BJ EB D ko oB (e s ab at aD t es d i ov c il b up
                                       ; es a ba ta d = e sa b at ad .s i ht
                                                                                  }
                              ) ( sl ia t eD ko oB t eg s li a te Dk o oB c il b up
                                                  { n o it pe c xE s wo r ht
                                                                      { y rt
                          . es ab at a d) sl ia t eD ko o B( n ru t er
                     ; ) dI ko ob ( sl ia t eD ko oB t eg
                      { ) xe n o it pe cx E dn uo Ft o Nk oo B ( hc ta c }
                                                          ;x e wo r ht
                                                                           }
                                                                                  }
                                                                               . ..
           }

      Finally, this version of the example contains an applet to generate a dynamic dig-
      ital clock in the banner. See Including an Applet, page (265) for a description of
      the JSP element that generates HTML for downloading the applet.
      The source code for the application is located in the                  m ax e /l ai r ot ut ee 2 j
                                directory created when you unzip the tutorial bun-
      2 e ro ts k oo b/ be w /c rs /s e lp
                                            THE EXAMPLE JSP PAGES                                              251


dle (see Downloading the Examples, page (xxii)). To build, deploy, and run the
example:
   1. Go to
        s el pm a xe /l ai r ot ut e e2 j           and build the example by running                    t na
                        .         2 er ot s ko ob
   2.   Start the      server.
                    e e2 j
   3.   Start             .
              l oo ty ol p ed
   4.   Start the Cloudscape database by executing                ep a cs du ol c         tr at s   .
   5.   If you have not already created the bookstore database, run                        et ae r c t na
        .b d b ew
   6. Create a J2EE application called              pp A 2e ro t sk oo B     .
      a. Select File→New→Application.
      b. In the file chooser, navigate                              to           ma xe / la ir o tu te e2 j
                                       .
           2 er ot s ko ob / be w/ cr s /s el p
      c. In the File Name field, enter            pp A 2e ro ts k oo B   .
      d. Click New Application.
      e. Click OK.
   7. Add the              WAR to the
                    RA W2 e ro ts ko o B                   p pA 2e r ot sk oo B      application.
      a. Select File→Add→Web WAR.
      b. In the Add Web WAR dialog box, navigate to              ma xe / la ir o tu te e2 j
                                    . Select
           2 er ot sk o ob /b e w/ dl iu b /s el p                                          . Click Add
                                                                               r aw . 2e ro t sk oo b
         Web WAR.
   8. Add the             enterprise bean to the application.
                    B JE BD ko o B
      a. Select File→New Enterprise Bean.
      b. Select Bookstore2App from the Create New JAR File In Application
         combo box.
      c. Type             in the JAR Display Name field.
                    R AJ BD ko o B
      d. Click Edit to add the content files.
      e. In the Edit Archive Contents dialog box, navigate to                 the
                                                        directory and add the
           b je / be w/ dl i ub /s el p ma xe / la ir ot u te e2 j
                    and             packages. Click Next.
                                 no it p ec xe        es a ba ta d
      f. Chose Session and Stateless for the Bean Type.
      g. Select                               for Enterprise Bean Class.
                     l p mI BJ EB D ko oB . es ab at a d
      h. In the Remote Interfaces box, select                                 for
                                                  e m oH BJ EB D ko oB . es ab at a d
         Remote Home Interface and                              for Remote Inter-
                                                                     B JE BD ko o B. es a ba ta d
         face.
252                                   JAVASERVER PAGES™ TECHNOLOGY



         i. Enter            for Enterprise Bean Name.
                     B JE B Dk oo B
         j. Click Next and then click Finish.
      9. Add a resource reference for the Cloudscape database to the                      BJ EB D ko oB
         bean.
         a. Select the            enterprise bean.
                          B JE B Dk oo B
         b. Select the Resource Refs tab.
         c. Click Add.
         d. Select                          from the Type column.
                     e cr u oS at aD . lq s. xa v aj
         e. Enter               in the Coded Name field.
                     B Dk oo B /c bd j
      10.Save            .
              RA J BD ko oB
         a. Select            .
                     RA JB Dk o oB
         b. Select File→Save As.
         c. Navigate to the directory        b j e/ be w /d li ub / se lp m ax e   .
         d. Enter               in the File Name field.
                     ra j. B Dk oo b
         e. Click Save EJB JAR As.
      11.Add a reference to the enterprise bean            .
                                                          B JE B Dk oo B
         a. Select                 .
                     R AW 2 er ot sk o oB
         b. Select the EJB Refs tab.
         c. Click Add.
         d. Enter                  in the Coded Name column.
                     B JE BD ko o B/ bj e
         e. Select Session in the Type column.
         f. Select Remote in the Interfaces column.
         g. Enter                              in the Home Interface column.
                     em oH B JE BD k oo B. es a ba ta d
         h. Enter                         in the Local/Remote Interface column.
                     B JE BD k oo B. es a ba ta d
      12.Specify the JNDI Names.
         a. Select                 .
                     p pA 2 er ot sk o oB
         b. In the Application table, locate the EJB component and enter                       D ko o B
            BJ E Bin the JNDI Name column.
         c. In the References table, locate the EJB Ref and enter        in the    B JE B Dk oo B
            JNDI Name column.
         d. In the References table, locate the Resource component and enter
                               in the JNDI Name column.
            e p ac sd uo l C/ cb d j
                                       THE LIFE CYCLE OF A JSP PAGE                            253


      13.Enter the context root.
         a. Select the Web Context tab.
         b. Enter              .
                   2 er ot s ko ob
      14.Deploy the application.
         a. Select Tools→Deploy.
         b. Click Finish.
      15.Open the bookstore URL                                                            .
                                     re tn e/ 2 er ot s ko ob /0 0 08 :> t so h < // : pt th
  See Troubleshooting, page (215) for help with diagnosing common problems.


The Life Cycle of a JSP Page
  A JSP page services requests as a servlet. Thus, the life cycle and many of the
  capabilities of JSP pages (in particular the dynamic aspects) are determined by
  Java Servlet technology and much of the discussion in this chapter refers to func-
  tions described in chapter 10.
  When a request is mapped to a JSP page, it is handled by a special servlet that
  first checks whether the JSP page’s servlet is older than the JSP page. If it is, it
  translates the JSP page into a servlet class and compiles the class. During devel-
  opment, one of the advantages of JSP pages over servlets is that the build pro-
  cess is performed automatically.

  Translation and Compilation
  During the translation phase, each type of data in a JSP page is treated differ-
  ently. Template data is transformed into code that will emit the data into the
  stream that returns data to the client. JSP elements are treated as follows:
         • Directives are used to control how the Web container translates and
           executes the JSP page.
         • Scripting elements are inserted into the JSP page’s servlet class. See
           JSP Scripting Elements, page (260) for details.
         • Elements of the form                       are converted into method
                                     > / . .. X X X : ps j<
           calls to JavaBeans components or invocations of the Java Servlet API.
254                                       JAVASERVER PAGES™ TECHNOLOGY



      For a JSP page named         em aN e ga p   , the source for a JSP page’s servlet is kept in
      the file

                         / b ew / t so h /y ro t is op er / EM OH _E E 2J
          av a j. ps j _ e ma Ne g ap f2 00 0 _ / to o r_ tx et n oc

      For example, the source for the index page (named                ) for the
                                                                            ps j .x ed ni             et a d
      localization example discussed at the beginning of the chapter would be named

          av a j. ps j_x ed ni f 20 00 _/ e ta d/ b ew / t so h /y ro t is op er / EM OH _E E 2J

      Both the translation and compilation phases can yield errors that are only
      observed when the page is requested for the first time. If an error occurs while
      the page is being translated (for example, if the translator encounters a mal-
      formed JSP element), the server will return a                    , and the servlet
                                                                 no it pe c xE es r aP
      class source file will be empty or incomplete. The last incomplete line will give a
      pointer to the incorrect JSP element.
      If an error occurs while the JSP page is being compiled (for example, there is a
      syntax error in a scriptlet), the server will return a                and a mes-
                                                                      no it p ec xE re p sa J
      sage that includes the name of the JSP page’s servlet and the line where the error
      occurred.
      Once the page has been translated and compiled, the JSP page’s servlet for the
      most part follows the servlet life cycle described in the section Servlet Life
      Cycle, page (216):
          1. If an instance of the JSP page’s servlet does not exist, the container:
             a. Loads the JSP page’s servlet class
             b. Instantiates an instance of the servlet class
             c. Initializes the servlet instance by calling the          method
                                                                            t in Ip s j
          2. Invokes the      e ci v re Sp s j_   method, passing a request and response object.
      If the container needs to remove the JSP page’s servlet, it calls the                  yo rt s eD ps j
      method.

      Execution
      You can control various JSP page execution parameters using by         directives.  eg ap
      The directives that pertain to buffering output and handling errors are discussed
      here. Other directives are covered in the context of specific page authoring tasks
      throughout the chapter.
                                             THE LIFE CYCLE OF A JSP PAGE                             255


Buffering
When a JSP page is executed, output written to the response object is automati-
cally buffered. You can set the size of the buffer with the following     direc-      e ga p
tive:

     > % " bk xx x | e no n" =r e ff ub eg ap @ % <

A larger buffer allows more content to be written before anything is actually sent
back to the client, thus providing the JSP page with more time to set appropriate
status codes and headers or to forward to another Web resource. A smaller buffer
decreases server memory load and allows the client to start receiving data more
quickly.

Handling Errors
Any number of exceptions can arise when a JSP page is executed. To specify that
the Web container should forward control to an error page if an exception occurs,
include the following      directive at the beginning of your JSP page:
                          eg a p

     > % " e m an _e li f "= eg aP r or re eg ap @ % <

The Duke’s Bookstore application page             p sj .y o rt se d ti ni   contains the directive

     > %" p sj .e g ap ro rr e "= eg aP r or re eg ap @ % <

The beginning of      ps j. e ga pr o rr e   indicates that it is serving as an error page
with the following            directive:
                                   e ga p

     > % " es la f |e ur t" = eg aP ro r rE si eg ap @ % <

This directive makes the exception object (of type             xE ps J .p sj . te lv re s .x av a j
         ) available to the error page, so that you can retrieve, interpret, and pos-
n oi tp e c
sibly display information about the cause of the exception in the error page.

   Note: You can also define error pages for the WAR that contains a JSP page. If error
   pages are defined for both the WAR and a JSP page, the JSP page’s error page takes
   precedence.
                                                                                            }
                                                                                        }
                                                                                  }
                                            ;) ) (e ga s se Mt eg . xe
                      +" . BJ EB Dk o oB /b je / vn e/ p mo c: av a j"
                            + " : e mo h pu k oo l o t el ba n U"
                                                (n lt n ir p. t uo .m et s yS
                                     { )x e no i tp ec xE g ni ma N ( hc ta c }
                                            ;) ) (e ga s se Mt eg . xe
                 + " .n a eb e sa b at ad e t ae rc t’ nd lu o C"
                                                (n lt n ir p. t uo .m et s yS
                                     { )x e no i tp ec xE e ta er C ( hc ta c }
                                            ;) ) (e ga s se Mt eg . xe
                 + " .n a eb e sa b at ad e t ae rc t’ nd lu o C"
                                                (n lt n ir p. t uo .m et s yS
                                     { )x e no i tp ec xE e to me R ( hc ta c }
                                                            ; ) BJ EB Dk o ob
       ," BJ E BD ko ob " (e tu b ir tt At e s. )( tx e tn oC t el vr eS t eg
                                     ;) (e t ae rc .e m oh = BJ EB Dk o ob
                ; )s s al c. e mo HB JE B Dk oo B .e sa ba t ad
                                          ,f eR j bo (w or r an
              .t c ej bO e to me Re l ba tr oP ) em oH B JE BD ko o B(
                                              = e mo h e mo H BJ EB Dk o oB
                      ;) " BJ EB Dk o oB /b je / vn e/ p mo c: av a j"
                                     (p uk o ol .c i = f eR j bo t ce j bO
             ; )( tx et n oC la i ti nI w e n = ci tx et n oC la it i nI
                                                                            { y rt
                                                      { ) ll un = = B JE B Dk oo b( fi
                                     ;) "B J EB Dk oo b "( et u bi rt tA t eg
                                        .) (t xe t no Ct el v re St e g) BD ko o B(
                                                                          = BJ EB Dk o ob
                                                            { )( ti n Ip sj d i ov c il b up
                                                    ;B JE BD k oo b B JE BD ko o B et av i rp
      . The enterprise bean is created using the techniques described in .                 B J EB
 D ko o b
bookstore database;                                p s j. yo rt s ed ti n i
                                          stores a reference to the bean in
                      B JE B Dk oo B .e sa ba t ad
retrieve or create an enterprise bean                             that accesses the
            t in I ps j
The bookstore example page             ps j .y or ts e dt in i
                                                    defines the          method to
JSP declarations, discussed in Declarations, page (260).
release resources using the                       y or t se Dp sj
                                         method. The methods are defined using
                  e g aP ps J
activities by overriding the                        t i nI ps j
                                        method of the             interface. You
tent configuration data, initialize resources, and perform any other one-time
You can customize the initialization process to allow the JSP page to read persis-
                  Initializing and Finalizing a JSP Page
                                JAVASERVER PAGES™ TECHNOLOGY                                        256
                                            CREATING STATIC CONTENT                                  257


  When the JSP page is removed from service, the                y or t se Dp s j   method releases
  the          variable:
     BJ EB D ko oB

      { ) (y o rt se Dp s j di o v ci lb u p
              ; ll u n = B JE BD ko o b
                                           }

  Since the enterprise bean is shared between all the JSP pages, it should be initial-
  ized when the application is started, instead of in each JSP page. Java Servlet
  technology provides application life cycle events and listener classes for this
  purpose. As an exercise, you can move the code that manages the creation of the
  enterprise bean to a context listener class. See Handling Servlet Life-Cycle
  Events, page (216) for the context listener that initializes the Java Servlet version
  of the bookstore application.


Creating Static Content
  You create static content in a JSP page by simply writing it as if you were creat-
  ing a page that consisted only of that content. Static content can be expressed in
  any text-based format, such as HTML, WML, and XML. The default format is
  HTML. If you want to use a format other than HTML, you include a             direc-  e g ap
  tive with the                 attribute set to the format type at the beginning of
                  e py T tn et n oc
  your JSP page. For example, if you want a page to contain data expressed in the
  wireless markup language (WML), you need to include the following directive:

      > % "l mw .p a w. dn v /t xe t" = ep yT tn e tn oc eg ap @ % <

  A registry of content type names is kept by the IANA at:

      s ep y t ai de m /s tn e mn gi ss a /a na i /s et on ni /u de . is i. p tf // :p t f


Creating Dynamic Content
  You create dynamic content by accessing Java programming language objects
  from within scripting elements.

  Using Objects within JSP Pages
  You can access a variety of objects, including enterprise beans and JavaBeans
  components, within a JSP page. JSP technology automatically makes some
258                                 JAVASERVER PAGES™ TECHNOLOGY



      objects available, and you can also create and access application-specific
      objects.

      Implicit Objects
      Implicit objects are created by the Web container and contain information related
      to a particular request, page, or application. Many of the objects are defined by
      the Java Servlet technology underlying JSP technology and are discussed at
      length in Chapter 10. Table 11–2 summarizes the implicit objects.


      Table 11–2 Implicit Objects

       Variable       Class                 Description

                                            The context for the JSP page’s servlet and any Web
                      .telvres.xavaj
       noitacilppa                          components contained in the same application. See
                      txetnoCtelvreS
                                            Accessing the Web Context, page (238).

                      .telvres.xavaj
       gifnoc                               Initialization information for the JSP page’s servlet.
                       gifnoCtelvreS

                      .gnal.avaj            Accessible only from an error page. See Handling
       noitpecxe       elbaworhT            Errors, page (255).

                      .telvres.xavaj
       tuo                                  The output stream.
                       retirWpsJ.psj

                                            The instance of the JSP page’s servlet processing
                      .gnal.avaj
       egap                                 the current request. Not typically used by JSP page
                          tcejbO
                                            authors.

                                            The context for the JSP page. Provides a single API
                                            to manage the various scoped attributes described
                       .telvres.xavaj
       txetnoCegap                          in Sharing Information, page (218).
                      txetnoCegaP.psj
                                            This API is used extensively when implementing
                                            tag handlers (see Tag Handlers, page (289)).

                      subtype of            The request triggering the execution of the JSP
       tseuqer        .telvres.xavaj        page. See Getting Information from
                      tseuqeRtelvreS        Requests, page (223).

                      subtype of
                                            The response to be returned to the client. Not typi-
       esnopser        .telvres.xavaj
                                            cally used by JSP page authors.
                      esnopseRtelvreS
                                         CREATING DYNAMIC CONTENT                                  259


Table 11–2 Implicit Objects (Continued)

 Variable          Class                    Description

                     .telvres.xavaj         The session object for the client. See Accessing the
 noisses
                   noisseSpttH.ptth         Web Context, page (238).



Application-Specific Objects
When possible, application behavior should be encapsulated in objects so that
page designers can focus on presentation issues. Objects can be created by devel-
opers who are proficient in the Java programming language and in accessing
databases and other services. There are four ways to create and use objects
within a JSP page:
   • Instance and class variables of the JSP page’s servlet class are created in
       declarations and accessed in scriptlets and expressions.
   • Local variables of the JSP page’s servlet class are created and used in
       scriptlets and expressions.
   • Attributes of scope objects (see Using Scope Objects, page (219)) are cre-
       ated and used in scriptlets and expressions.
   • JavaBeans components can be created and accessed using streamlined JSP
       elements. These elements are discussed in the chapter 12. You can also
       create a JavaBeans component in a declaration or scriptlet and invoke the
       methods of a JavaBeans component in a scriptlet or expression.
Declarations, scriptlets, and expressions are described in JSP Scripting
Elements, page (260).

Shared Objects
The conditions affecting concurrent access to shared objects described in Shar-
ing Information, page (218) apply to objects accessed from JSP pages that run as
multithreaded servlets. You can indicate how a Web container should dispatch
multiple client requests with the following      directive:
                                                   eg ap

    >% " e sl af | eu rt "= e fa Sd ae r hT si eg ap @ % <

When                  is set to
       ef aS da e rh Ts i            , the Web container may choose to dispatch
                                    eu rt
multiple concurrent client requests to the JSP page. This is the default setting. If
using eu rt, you must ensure that you properly synchronize access to any shared
objects defined at the page level. This includes objects created within declara-
260                                      JAVASERVER PAGES™ TECHNOLOGY



      tions, JavaBeans components with page scope, and attributes of the                  eg a p   scope
      object.
      If                 is set to
         e fa Sd a er hT s i            , requests are dispatched one at a time, in the
                                       e s la f
      order they were received, and access to page-level objects does not have to be
      controlled. However, you still must ensure that access to attributes of the              i l pp a
              or
      n oi t ac            scope objects and to JavaBeans components with application
                   n o is se s
      or session scope is properly synchronized.

      JSP Scripting Elements
      JSP scripting elements are used to create and access objects, define methods, and
      manage the flow of control. Since one of the goals of JSP technology is to sepa-
      rate static template data from the code needed to dynamically generate content,
      very sparing use of JSP scripting is recommended. Much of the work that
      requires the use of scripts can be eliminated by using custom tags, described in
      Extending the JSP Language, page (267).
      JSP technology allows a container to support any scripting language that can call
      Java objects. If you wish to use a scripting language other than the default,   ,            a va j
      you must specify it in a       directive at the beginning of a JSP page:
                                   eg ap

           > % "e ga u gn al gn it pi r cs "= e ga ug na l e ga p @ %<

      Since scripting elements are converted to programming language statements in
      the JSP page’s servlet class, you must import any classes and packages used by a
      JSP page. If the page language is       , you import a class or package with the
                                                  a va j
      e g apdirective:

           > % " em an s sa lc _d e if il a uq _y ll u f ,* . em an eg a kc ap " =t ro pm i e ga p @ %<

      For example, the bookstore example page                    imports the classes
                                                            p s j. tr ac w oh s
      needed to implement the shopping cart with the following directive:

           >% " *. t ra c , *. li tu . av aj " =t ro pm i e ga p @ %<

      Declarations
      A JSP declaration is used to declare variables and methods in a page’s scripting
      language. The syntax for a declaration is as follows:

           > % n oi ta r al ce d e ga ug n al g ni t pi rc s ! %<
                                             CREATING DYNAMIC CONTENT                               261


When the scripting language is the Java programming language, variables and
methods in JSP declarations become declarations in the JSP page’s servlet class.
The bookstore example page                        defines an instance variable
                                         p sj .y o rt se d ti ni
named
B JE BD k oo b   and the initialization and finalization methods          and         t in Ip s j
           discussed earlier in a declaration:
        y o rt se Dp s j

     !%<
           ; BJ EB Dk o ob B JE B Dk oo B e ta vi r p

               { ) (t in Ip s j di o v ci lb u p
                                       ...
                                                }
           { ) (y o rt se Dp s j di o v ci lb u p
                                       ...
                                                }
     >%

Scriptlets
A JSP scriptlet is used to contain any code fragment that is valid for the scripting
language used in a page. The syntax for a scriptlet is as follows:

     %<
           s t ne me ta t s eg au g na l g ni tp ir c s
     >%

When the scripting language is set to      , a scriptlet is transformed into a Java
                                                av aj
programming language statement fragment and is inserted into the service
method of the JSP page’s servlet. A programming language variable created
within a scriptlet is accessible from anywhere within the JSP page.
The JSP page                    contains a scriptlet that retrieves an iterator from
                   p s j. tr a cw oh s
the collection of items maintained by a shopping cart and sets up a construct to
loop through all the items in the cart. Inside the loop, the JSP page extracts prop-
erties of the book objects and formats them using HTML markup. Since the
e li h wloop opens a block, the HTML markup is followed by a scriptlet that
closes the block.

     %<
                         ; )( ro ta r et i. ) (s me tI t eg .t ra c = i ro ta re t I
                                                         { ) )( tx e Ns ah . i( e li h w
                                              = m et i me t It ra C gn ip po h S
                                 ; ) (t xe n .i )m et I tr aC g ni pp oh S (
           ; )( me t It eg .m e ti )s l ia te Dk o oB ( = d b sl i at eD ko o B
     >%
scripting language is the Java programming language, an expression is trans-
converted into a string, into the data stream returned to the client. When the
A JSP expression is used to insert the value of a scripting language expression,
                                                                                 Expressions
                                              Figure 11–2 Duke’s Bookstore Shopping Cart
                                                       The output appears in Figure 11–2.
                                                                                       >%
                                                                                   }
                                                                  e li hw fo d nE //
                                                                                       %<
                                                                               . ..
                                                                            >d t /<
  >g no rt s /< >a / <> %) (e l ti Tt e g. db =% < >" >% )( d Ik oo B te g. db = %<
      = dI k oo b? s li at ed k oo b/ > %) (h ta P tx et no C te g. t se uq er = %<
                                                         "= f er h a <> gn or t s<
                                                 > "a af ff f #" =r o lo cg b d t<
                                                                            >d t /<
                                               > % )( yt it n au Qt e g. me ti = %<
                           >" f ff ff f #" =r ol o cg b "t h gi r" = ng il a d t<
                                                                             > r t<
                             JAVASERVER PAGES™ TECHNOLOGY                                      262
                                              INCLUDING CONTENT IN A JSP PAGE                            263


  formed into a statement that converts the value of the expression into a                   g ni rt S
  object and inserts it into the implicit  object.
                                                tu o
  The syntax for an expression is as follows:

       > % n oi ss e rp xe e g au gn al gn it p ir cs = % <

  Note that a semicolon is not allowed within a JSP expression, even if the same
  expression has a semicolon when you use it within a scriptlet.
  The following scriptlet retrieves the number of items in a shopping cart:

       %<
            tr ac g n ip po h s eh t f o yr am m us a tn ir P / /
                  ; ) (s me t If Or eb m uN te g. t ra c = m un t n i
                                                  { ) 0 > m un ( f i
       >%

  Expressions are then used to insert the value of       into the output stream and
                                                               mu n
  determine the appropriate string to include after the number:

                                                                 >" 2 +" =e z is t no f <
              > %m u n= %< >% )" st n et no C tr aC "( g ni rt St e g. se g as se m= % <
       : > %) " me tI t ra C" (g n ir tS t eg .s eg a ss em =% < ? 1 = =m un (= % <
                >t no f /< >% )) " sm et I tr aC "( g ni rt St e g. se g as se m= % <


Including Content in a JSP Page
  There are two mechanisms for including another Web resource in a JSP page: the
           directive and the
  e du lc n i                            element.
                                     ed ul c ni :p sj
  The  ed ul c nidirective is processed when the JSP page is translated into a servlet
  class. The effect of the directive is to insert the text contained in another file—
  either static content or another JSP page—in the including JSP page. You would
  probably use the              directive to include banner content, copyright infor-
                        ed ul cn i
  mation, or any chunk of content that you might want to reuse in another page.
  The syntax for the             directive is as follows:
                         e d ul cn i

       >% "e ma ne l if "= el i f ed u lc ni @ % <

  For example, all the bookstore application pages include the file                    p sj .r e nn ab
  containing the banner content with the following directive:

       >% " p sj .r en n ab "= el i f ed u lc ni @ % <
264                                         JAVASERVER PAGES™ TECHNOLOGY



        In addition, the pages                ,                   ,            , and
                                      p s j. go l at ac p s j. sl i at ed ko o b ps j .e ro ts k oo b
                        include JSP elements that create and destroy a database bean
        ps j .t ra cw o hs
        with the following directive:

              > % " ps j. y or ts ed t in i" = el if e d ul cn i @ %<

        Because you must statically put an            directive in each file that reuses the
                                                     ed ul c ni
        resource referenced by the directive, this approach has its limitations. For a more
        flexible approach to building pages out of content chunks, see A Template Tag
        Library, page (308).
        The
        e d ul cn i: p sj     element is processed when a JSP page is executed. The
                  action allows you to include either a static or dynamic resource in a JSP
                     ed ul c ni
        file. The results of including static and dynamic resources are quite different. If
        the resource is static, its content is inserted into the calling JSP file. If the
        resource is dynamic, the request is sent to the included resource, the included
        page is executed, and then the result is included in the response from the calling
        JSP page. The syntax for the                 element is as follows:
                                             e du lc n i: ps j

              > / " eg a Pd ed ul c ni "= e ga p ed u lc ni :p s j<

        The       application introduced at the beginning of this chapter includes the
              et ad
        page that generates the display of the localized date with the following state-
        ment:

              > / "p sj .e t ad "= e ga p ed u lc ni :p s j<


      Transferring Control to Another Web
      Component
        The mechanism for transferring control to another Web component from a JSP
        page uses the functionality provided by the Java Servlet API as described in
        Transferring Control to Another Web Component, page (237) in . You access
        this functionality from a JSP page with the           element:
                                                                 d ra wr of : ps j

              > / " ps j. ni a m/ "= e ga p dr a wr of :p s j<

        Note that if any data has already been returned to a client, the             dr aw ro f :p sj   ele-
        ment will fail with an                           .
                                    n oi tp ec x Ee ta t Sl ag el l I
      URL where the plug-in can be downloaded.
      the plug-in required. The l ru ni g ul pe i
                                                and     lr un ig u lp sn
                                                                 attributes specify the
      configuration data for the presentation of the element as well as the version of
                     n i gu lp :p s j
      priate for the requesting client. The attributes of the              tag provide
      The             > de bm e< >t ce j bo <
                        tag is replaced by either an          or                    n i gu lp : ps j
                                                                          tag as appro-
                                                                               >n ig u lp :p sj / <
                 } >k c ab ll a f: ps j/ < t xe t _y ra rt i br a >k c ab ll a f: ps j< {
                                                                      } >s ma r ap :p sj / <
      +} >/ " eu l aV ma r ap "= eu l av " e ma Nm ar a p " =e ma n m ar a p: ps j< {
                                                                        > sm ar a p: ps j< {
                                                          > } " lr u " = lr un i gu lp ei {
                                                             } " lr u " = lr un i gu lp sn {
                                                                   } " h td iw " =h td iw {
                                                                } " ec a ps v " = ec ap sv {
                                                        } " e ma Nt ne n op mo c "= em an {
                                                   } " n oi s re ve rj " =n oi s re ve rj {
                                                                } " ec a ps h " = ec ap sh {
                                                                } " th g ie h " = th gi eh {
                                                      } " t s iL ev ih c ra "= e vi hc ra {
                                                             } " tn em n gi la " =n gi la {
                                                      " e sa b ed oC tc e jb o " = es ab ed o c
                                                                   " ed o Ct ce j bo "= ed o c
                                                                  "t el p pa |n a eb "= ep y t
                                                                                   ni g ul p: ps j <
                    element is as follows:                                               n i gu lp :p s j
      nent and subsequent execution of any client-side component. The syntax for the
      in the download of the Java Plug-in software (if required) and client-side compo-
                         > de bm e <     > t ce jb o<
      ate client-browser-dependent constructs (            or          ) that will result
                    element. This element generates HTML that contains the appropri-     n i gu lp :p s j
      You can include an applet or JavaBeans component in a JSP page by using the
                                                               Including an Applet
                                                                              > ed ul c ni :p sj / <
                                > / "1 eu la v "= eu l av ” 1m a ra p” =e m an m a ra p: ps j <
                                                             > ". . ." =e ga p e du l cn i: ps j <
                    m ar a p: ps j
      you can append parameters to the request object with the              element:
      provided to the target page. If you wish to provide additional data to that page,
      When an            or                                        dr a wr of     ed u lc ni
                                      element is invoked, the original request object is
                                                                            Param Element
265                                     INCLUDING AN APPLET
266                                       JAVASERVER PAGES™ TECHNOLOGY



      The              elements specify parameters to the applet or JavaBeans compo-
                        m a ra p: ps j
      nent. The
            kc ab l la f: p sj  element indicates the content to be used by the client
      browser if the plug-in cannot be started (either because          or          is
                                                                              >t ce jb o <   > de bm e<
      not supported by the client or because of some other problem).
      If the plug-in can start but the applet or JavaBeans component cannot be found
      or started, a plug-in-specific message will be presented to the user, most likely a
      pop-up window reporting a                               .
                                         no i tp ec x Ed nu oF t oN ss a lC
      The Duke’s Bookstore page                              that creates the banner displays a
                                                     ps j. r en na b
      dynamic digital clock generated by    k co lC l at ig iD      (Figure 11–3).




      Figure 11–3 Duke’s Bookstore with Applet

      The   n i gu lp :p s j   element used to download the applet follows:
                                                                                    >r t <
                                                                                                   >%
                                                                                     ...
                                        ; ) (t xe n .i )m et I tr aC g ni pp oh S (
                                                      = m et i me t It ra C gn ip po h S
                                                                { ) )( tx e Ns ah . i( e li h w
                                  ; )( ro ta r et i. ) (s me tI t eg .t ra c = i ro ta re t I
                                                                                                   %<
      the Duke’s Bookstore shopping cart:
      For example, recall the scriptlet used to loop through and display the contents of
      bring the benefits of another level of componentization to JSP pages.
      objects that are accessed through extensions to the JSP language. Custom tags
      called custom tags, that allows you to encapsulate dynamic functionality in
      difficult to maintain. Alternatively, JSP technology provides a mechanism,
      the drawbacks of scriptlets, however, is that they tend to make JSP pages more
      flow control, with JavaBeans components in conjunction with scriptlets. One of
      databases, using enterprise services such as e-mail and directories, and managing
      You can perform a wide variety of dynamic processing tasks including accessing
                                           Extending the JSP Language
                                                                                   >n ig u lp :p sj / <
                                                                          > k ca bl l af :p sj / <
                                            >p / <. ni gu l p tr at s o t e lb an U> p <
                                                                     > kc ab l la f: ps j <
                                                                              >s ma r ap :p sj / <
                       > / " 66 00 CC " =e ul a v "r ol o cg f" =e m an m a ra p: ps j <
                       > / " FF FF FF " =e ul a v "r ol o cg b" =e m an m a ra p: ps j <
        > / " >% )( y rt nu oC t eg .) (e l ac oL t eg .t se u qe r= % <" =e ul a v
                                                    "y rt n uo c" =e m an m a ra p: ps j <
       >/ " > %) (e g au gn aL t eg .) (e l ac oL t eg .t se u qe r= % <" =e ul a v
                                                  " eg au g na l" =e m an m a ra p: ps j <
                                                                               > sm a ra p: ps j <
                    > " 1, 0 ,3 ,1 =n o is re V #b ac .2 3 ni w 10 _ 03 1 l la ts ni j /
        1 0_ 0. 3 .1 /n ig u lp /s t cu do rp / mo c. n us .a va j // :p tt h "= lr u ni gu lp e i
                                                          " lm th .l l at sn i n ig ul p /
        1 0_ 0. 3 .1 /n ig u lp /s t cu do rp / mo c. n us .a va j // :p tt h "= lr u ni gu lp s n
                                      " 00 3" = ht di w " 52 "= t hg ie h " re tn e c" =n gi l a
                                                                         "3 . 1" =n o is re ve r j
                                                               " 2 er ot sk o ob /" = es ab ed o c
                                                           "s sa l c. kc ol C la ti g iD "= ed o c
                                                                              "t el p pa "= ep y t
                                                                                      ni g ul p: ps j <
267                            EXTENDING THE JSP LANGUAGE
268                                         JAVASERVER PAGES™ TECHNOLOGY


                         >" f ff ff f #" =r ol o cg b "t h gi r" = ng il a d t<
                                             > % )( yt it n au Qt e g. me ti = %<
                                                                          >d t /<
                                                                             . ..
           %<
                 }
           >%

      An    et a re ti   custom tag eliminates the code logic and manages the scripting
      variable
           me ti         that references elements in the shopping cart:

                                   "m e ti "= d i et ar e ti :c ig o l<
              > "> %) ( sm et It e g. tr ac = %< "= n oi tc el l oc
                                                             > r t<
           >" f ff ff f #" =r ol o cg b "t h gi r" = ng il a d t<
                               > % )( yt it n au Qt e g. me ti = %<
                                                            >d t /<
                                                               . ..
                                                >e ta re t i: ci go l /<

      Custom tags are packaged and distributed in a unit called a tag library. The syn-
      tax of custom tags is the same as that used for the JSP elements, namely,
                      ; however, for custom tags,
      >g a t: xi fe r p<                                   is defined by the user of the
                                                              x i fe rp
      tag library and      is defined by the tag developer. Chapter 13 explains how to
                           g at
      use and develop custom tags.
                 12
     JavaBeans™
Components in JSP™
             Pages
                                                                Stephanie Bodoff



J AVABEANS components are Java classes that can be easily reused and com-
posed together into applications. Any Java class that follows certain design con-
ventions can be a JavaBeans component.
JavaServer Pages™ technology directly supports using JavaBeans components
with JSP language elements. You can easily create and initialize beans and get
and set the values of their properties. This chapter provides basic information
about JavaBeans components and the JSP language elements for accessing Java-
Beans components in your JSP pages. For further information about the Java-
Beans component model, see                                                 .
                             sn ae b av aj /s t cu do r p/ mo c. n us .a v aj // :p t th

In This Chapter
          JavaBeans Component Design Conventions 270
          Why Use a JavaBeans Component? 271
          Creating and Using a JavaBeans Component 272
          Setting JavaBeans Component Properties 273
          Retrieving JavaBeans Component Properties 275


                                                                                           269
270                                           JAVABEANS™ COMPONENTS IN JSP™ PAGES



      JavaBeans Component Design
      Conventions
        JavaBeans component design conventions govern the properties of the class, and
        govern the public methods that give access to the properties.
        A JavaBeans component property can be
             • Read/write, read-only, or write-only
             • Simple, which means it contains a single value, or indexed, which means
               it represents an array of values
        There is no requirement that a property be implemented by an instance variable;
        the property must simply be accessible using public methods that conform to
        certain conventions:
             • For each readable property, the bean must have a method of the form
                 } . .. { )( y tr ep or P te g ss a lC yt r ep or P
             • For each writable property, the bean must have a method of the form                         tes
                 } .. . { ) c p ss al C yt re po r P( yt r ep or P
        In addition to the property methods, a JavaBeans component must define a con-
        structor that takes no parameters.
        The Duke’s Bookstore application JSP pages                  ,                 ,
                                                                   p sj . sl ia te d ko ob p sj .r e tn e
                      , and
               p s j. go la t ac              use the
                                     p sj . tr ac w oh s           a ta d   and     B Dk o oB .e s ab at ad
                            JavaBeans components.
        sl ia te D ko oB .e s ab                             provides a JavaBeans com-                 BD k oo B
        ponent front end to the enterprise bean                 . Both beans are used             B J EB Dk oo B
        extensively by bean-oriented custom tags (see Tags That Define Scripting
        Variables, page (298)). The JSP pages                     and
                                                               p sj .t r ac wo hs   use    ps j. r ei hs a c
                             to represent a user’s shopping cart.
        t ra Cg ni p po hS .t r ac
        The JSP pages                     ,
                               ps j .g ol at a c           , and
                                                     p sj . tr ac wo h s            use the
                                                                                    p sj .r e ih sa c
                          JavaBeans component to format currency in a locale-sensitive
        y cn e rr uC .l i tu
        manner. The bean has two writable properties,            and         , and one read-
                                                                       e l ac ol       t nu om a
        able property,         . The
                         t am ro f            property does not correspond to any instance
                                            t a mr of
        variable, but returns a function of the         andel ac o l properties.
                                                                           t nu o ma

                { yc ne r ru C ss a lc c il b up
             ; el ac ol el ac o L et av i rp
             ; tn uo ma el bu o d et av i rp
                  { )( y cn er r uC c il b up
                   ;l lu n = e la c ol
                    ; 0. 0 = t nu o ma
                                                                   > /" n oi ss e s" =e po c s
                        " tr a Cg ni p po hS .t r ac "= s sa lc " t ra c" =d i n ae B es u: ps j <
                                        n a eB es u
      scriptlet with the much more concise JSP           element:
      store pages p sj .t r ac wo h s,       ps j. go l at ac p s j. sl ia t ed ko o b
                                                    , and                  replace the
      use JSP elements to create and access the object. For example, the Duke’s Book-
      If the shopping cart object conforms to JavaBeans conventions, JSP pages can
                                                                                              >%
                                                                                          }
                                ;) t ra c , "t ra c" ( et ub ir t tA te s .n oi ss e s
                                              ; )( tr a Cg ni pp o hS w e n = tr a c
                                                               { ) ll u n == tr ac ( f i
                         en o w en a e t ae rc ,t ra c o n sa h r es u e ht f I / /
                                                      ; )" tr ac " (e tu b ir tt At e g
                            .n o is se s) t ra Cg n ip po hS ( = t ra c t ra C gn ip po h S
                                                                                              %<
      shopping cart and stores it as a session attribute:
      within a declaration or scriptlet. The following scriptlet creates the bookstore
      A JSP page can create and use any type of Java programming language object
                     Why Use a JavaBeans Component?
                                                                                                }
                                                                                          }
                                                ;) tn u om a( ta m ro f. f n nr ut e r
                ; ) el ac ol ( ec na ts n Iy cn e rr uC te g .t am r oF re bm u N
                                                             = f n t am r oF re bm u N
                                                    { )( ta m ro Ft eg gn ir t S ci lb u p
                                                                                          }
                                                                      ;a = tn uo m a
                                           { ) a e lb uo d( t nu om At e s di o v ci lb u p
                                                                                          }
                                                                      ;l = el ac o l
                                           { ) l e la co L( e la co Lt e s di o v ci lb u p
                                                                                          }
271                   WHY USE A JAVABEANS COMPONENT?
272                                              JAVABEANS™ COMPONENTS IN JSP™ PAGES



      Creating and Using a JavaBeans
      Component
        You declare that your JSP page will use a JavaBeans component using either one
        of the following formats:

                                                      " e ma N na eb " =d i na e Be su :p s j<
              > /" e po cs " =e po cs " e ma n ss al c_ d ei fi la u q_ yl l uf "= ss a lc

        or

                                                    " e ma N na eb " =d i na e Be su :p s j<
              >" e po cs " =e po cs " e ma n ss al c_ d ei fi la u q_ yl l uf "= ss a lc
                                                      > /. .. y t re po r Pt es :p s j<
                                                                        >n ae B es u: ps j /<

        The second format is used when you want to include                      yt r ep or Pt e s: ps j   state-
        ments, described in the next section, for initializing bean properties.
        The                element declares that the page will use a bean that is stored
               na e Be su : ps j
        within and accessible from the specified scope, which can be                    ,    n oi t ac il pp a
                 ,         , or
        t se uq er no is s es       . If no such bean exists, the statement creates the
                                        e g ap
        bean and stores it as an attribute of the scope object (see Using Scope
        Objects, page (219)). The value of the      attribute determines the name of the
                                                            di
        bean in the scope and the identifier used to reference the bean in other JSP ele-
        ments and scriptlets.

             Note: In the section JSP Scripting Elements, page (260) we mentioned that you
             must import any classes and packages used by a JSP page. This rule is slightly
             altered if the class is only referenced by         elements. In these cases, you must
                                                           naeBesu
             only import the class if the class is in the unnamed package. For example, in What
             Is a JSP Page?, page (246), the page              imports the
                                                        psj.xedni                      class. How-
                                                                                 selacoLyM
             ever, in the Duke’s Bookstore example, all classes are contained in packages and
             thus are not explicitly imported.


        The following element creates an instance of         if none exists, stores it as
                                                                 yc n er ru C
        an attribute of the        object, and makes the bean available throughout the
                                           no i ss es
        session by the identifier         :
                                   yc ne rr u c

              "y c ne rr u C. li tu " =s sa l c "y cn e rr uc " =d i na e Be su :p s j<
                                                         >/ " no is s es "= ep o cs
                                                SETTING JAVABEANS COMPONENT PROPERTIES                       273


Setting JavaBeans Component Properties
  There are two ways to set JavaBeans component properties in a JSP page: with
  the                  element or with a scriptlet
      y tr ep o rP te s :p sj

       > % ; ) e u la v ( em a Np or P t e s. em a Nn ae b % <

  The syntax of the                   element depends on the source of the prop-
                         y tr e po rP t es :p sj
  erty value. Table 12–1 summarizes the various ways to set a property of a Java-
  Beans component using the                    element.
                                      y tr e po rP te s :p sj


  Table 12–1 Setting JavaBeans Component Properties

   Value Source                   Element Syntax

                                                 "emaNnaeb"=eman ytreporPtes:psj<
   String constant
                                  >/"tnatsnoc gnirts"=eulav "emaNporp"=ytreporp

                                           "emaNnaeb"=eman ytreporPtes:psj<
   Request parameter
                                  >/"emaNmarap"=marap "emaNporp"=ytreporp

                                  "emaNnaeb"=eman ytreporPtes:psj<
   Request parameter name
                                           >/"emaNporp"=ytreporp
   matches bean property          "emaNnaeb"=eman ytreporPtes:psj<
                                                  >/"*"=ytreporp

                                  "emaNnaeb"=eman ytreporPtes:psj<
   Expression                                "emaNporp"=ytreporp
                                     >/">% noisserpxe =%<"=eulav

          1. emaNnaeb    must be the same as that specified for the
                                                                 di  attribute in a
                                                                                  naeBesu   ele-
          ment.
          2. There must be aemaNporPtes        method in the JavaBeans component.
          3. emaNmarap    must be a request parameter name.




  A property set from a constant string or request parameter must have a type
  listed in Table 12–2. Since both a constant and request parameter are strings, the
  Web container automatically converts the value to the property’s type; the con-
  version applied is shown in the table.
                                g n ir tS       values can be used to assign values
  to a property that has a                 class. When that is the case, the
                                      r ot i dE yt re p or P                                       sA te s
                   method is used. A conversion failure arises if the method throws
  ) gn i rt S( tx e T
274                                             JAVABEANS™ COMPONENTS IN JSP™ PAGES



      an                                . The value assigned to an indexed property
         n oi t pe cx Et n em ug rA l ag el l I
      must be an array, and the rules just described apply to the elements.


      Table 12–2 Valid Value Assignments

       Property Type                     Conversion on String Value

       Bean property                     Uses   )laretil gnirts(txeTsAtes

       naeloob         or   naelooB      As indicated in   )gnirtS(fOeulav.naelooB.gnal.avaj

       etyb   or   etyB                  As indicated in   )gnirtS(fOeulav.etyB.gnal.avaj

       rahc   or   retcarahC             As indicated in   )0(tArahc.gnirtS.gnal.avaj

       elbuod      or   elbuoD           As indicated in   )gnirtS(fOeulav.elbuoD.gnal.avaj

       tni   or   regetnI                As indicated in   )gnirtS(fOeulav.regetnI.gnal.avaj

       taolf      or   taolF             As indicated in   )gnirtS(fOeulav.taolF.gnal.avaj

       gnol   or   gnoL                  As indicated in   )gnirtS(fOeulav.gnoL.gnal.avaj

       trohs      or   trohS             As indicated in   )gnirtS(fOeulav.trohS.gnal.avaj

       tcejbO                            )laretil gnirts(gnirtS wen



      You would use a runtime expression to set the value of a property whose type is
      a compound Java programming language type. Recall from the section
      Expressions, page (262) that a JSP expression is used to insert the value of a
      scripting language expression, converted into a        , into the stream returned
                                                      gn ir tS
      to the client. When used within a                 element, an expression simply
                                                             y tr ep o rP te s
      returns its value; no automatic conversion is performed. As a consequence, the
      type returned from an expression must match or be castable to the type of the
      property.
      The Duke’s Bookstore application demonstrates how to use the                      yt re p or Pt e s
      element and a scriptlet to set the current book for the database helper bean. For
      example,                                    uses the form
                       ps j. s li at e dk oo b/ 3 er ot sk o ob

          >/ "d I ko ob " =y tr ep o rp " B Dk oo b" = em an yt re po r Pt es :p s j<

      whereas      p sj . sl ia t ed ko ob / 2e ro ts k oo b   uses the form
                                              RETRIEVING JAVABEANS COMPONENT PROPERTIES               275


      > % ; )d Ik oo b (d Ik oo B te s. B Dk oo b % <

  The following fragments from the page                                    illustrate
                                                     p sj . tr ac wo h s/ 3e r ot sk oo b
  how to initialize a currency bean with a          object and amount determined el a co L
  by evaluating request-time expressions. Because the first initialization is nested
  in a          element, it is only executed when the bean is created.
      n ae B es u

              " yc n er ru C .l it u" = ss al c " yc ne r ru c" =d i n ae B es u: ps j <
                                                           >" n oi ss e s" =e po c s
      " el ac o l" =y t re po rp "y cn e rr uc "= e ma n yt r ep or P te s: ps j <
                     > /" > % )( e la co Lt e g. ts eu q er = % <" =e ul a v
                                                                   > na eB e su :p sj / <

      " tn uo m a" =y t re po rp "y cn e rr uc "= e ma n yt r ep or P te s: ps j <
                                >/ " >% )( la t oT te g. t ra c= % <" =e ul a v


Retrieving JavaBeans Component
Properties
  There are several ways to retrieve JavaBeans component properties. Two of the
  methods (the                     element and an expression) convert the value of
                    y tr e po rP t eg :p sj
  the property into a          and insert the value into the current implicit
                         g ni rt S                                                             t uo
  object:
      > / " e ma N po rp "= y tr ep o rp " em a Nn ae b "= em an yt re po r Pt eg : ps j< •
                                              > % )( e ma Np or P te g . em a Nn ae b = %< •
  For both methods,           must be the same as that specified for the
                    em a Nn ae b                                                                di
  attribute in a      element, and there must be a
                              na eB e su                      method in the
                                                                   e ma Np o rP te g
  JavaBeans component.
  If you need to retrieve the value of a property without converting it and inserting
  it into thetu oobject, you must use a scriptlet:

      > % ;) ( e m aN po r P t eg . e m aN na eb = o t ce jb O % <

  Note the differences between the expression and the scriptlet; the expression has
  an after the opening and does not terminate with a semicolon, as does the
     =                          %
  scriptlet.
  The Duke’s Bookstore application demonstrates how to use both forms to
  retrieve the formatted currency from the currency bean and insert it into the
  page. For example,                            uses the form
                           ps j. tr a cw oh s/ 3 er ot s ko ob
276                                      JAVABEANS™ COMPONENTS IN JSP™ PAGES


           >/ "t am r of "= y tr ep or p " yc n er ru c" = em an yt re po r Pt eg :p s j<

      whereas   p sj .t r ac wo hs / 2e ro ts k oo b   uses the form

           > % )( t am ro F te g. yc n er ru c = %<

      The Duke’s Bookstore application page                                  uses the
                                                           p sj .t r ac wo hs / 2e ro t sk oo b
      following scriptlet to retrieve the number of books from the shopping cart bean
      and open a conditional insertion of text into the output stream:

           %<
                t ra c g ni pp o hs e ht fo y ra m mu s a t ni rP //
                       ; )( sm e tI fO re b mu Nt eg . tr ac = mu n t ni
                                                       { )0 > mu n( fi
           >%

      Although scriptlets are very useful for dynamic processing, using custom tags
      (see Chapter 13) to access object properties and perform flow control is consid-
      ered to be a better approach. For example,                              replaces
                                                            p s j. tr ac w oh s/ 3 er ot sk o ob
      the scriptlet with the following custom tags:

           > / " sm et I fO re bm u n" =y t re po rp "t ra c "= em an "m un " =d i en i fe d: na e b<
                                          > " 0" =e u la v " mu n" =e m an n a hT re ta e rg :c ig o l<

      Figure 12–1 summarizes where various types of objects are stored and how those
      objects can be accessed from a JSP page. Objects created by the                     na e Be su :p s j
      tag are stored as attributes of the scope objects and can be accessed by
                                 tags and in scriptlets and expressions. Objects created
      yt re p or P] te s |t eg [: p sj
      in declarations and scriptlets are stored as variables of the JSP page’s servlet
      class and can be accessed in scriptlets and expressions.
                                   RETRIEVING JAVABEANS COMPONENT PROPERTIES   277




Figure 12–1 Accessing Objects From a JSP Page
278   JAVABEANS™ COMPONENTS IN JSP™ PAGES
                  13
Custom Tags in JSP™
              Pages
                                                         Stephanie Bodoff



THE standard JSP tags for invoking operations on JavaBeans™ components
and performing request dispatching simplify JSP page development and mainte-
nance. JSP technology also provides a mechanism for encapsulating other types
of dynamic functionality in custom tags, which are extensions to the JSP lan-
guage. Custom tags are usually distributed in the form of a tag library, which
defines a set of related custom tags and contains the objects that implement the
tags.
Some examples of tasks that can be performed by custom tags include operations
on implicit objects, processing forms, accessing databases and other enterprise
services such as e-mail and directories, and performing flow control. JSP tag
libraries are created by developers who are proficient at the Java programming
language and expert in accessing data and other services, and are used by Web
application designers who can focus on presentation issues rather than being
concerned with how to access enterprise services. As well as encouraging divi-
sion of labor between library developers and library users, custom tags increase
productivity by encapsulating recurring tasks so that they can be reused across
more than one application.




                                                                                   279
280                                        CUSTOM TAGS IN JSP™ PAGES



        Tag libraries are receiving a great deal of attention in the JSP technology com-
        munity. For more information about tag libraries and for pointers to some freely-
        available libraries see

            lm th . se ir a rb il ga t /p sj / st cu do r p/ mo c .n us .a v aj // :p t th

        In This Chapter
                   What is a Custom Tag? 280
                   The Example JSP Pages 281
                   Using Tags 285
                       Declaring Tag Libraries 285
                       Types of Tags 286
                   Defining Tags 289
                       Tag Handlers 289
                       Tag Library Descriptors 290
                       Simple Tags 293
                       Tags with Attributes 294
                       Tags With Bodies 296
                       Tags That Define Scripting Variables 298
                       Cooperating Tags 302
                   Examples 304
                       An Iteration Tag 304
                       A Template Tag Library 308
                   How Is a Tag Handler Invoked? 313


      What is a Custom Tag?
        A custom tag is a user-defined JSP language element. When a JSP page contain-
        ing a custom tag is translated into a servlet, the tag is converted to operations on
        an object called a tag handler. The Web container then invokes those operations
        when the JSP page’s servlet is executed.
        Custom tags have a rich set of features. They can
            •   Be customized via attributes passed from the calling page.
            •   Access all the objects available to JSP pages.
            •   Modify the response generated by the calling page.
            •   Communicate with each other. You can create and initialize a JavaBeans
                component, create a variable that refers to that bean in one tag, and then
                use the bean in another tag.
                                        THE EXAMPLE JSP PAGES                                     281


      • Be nested within one another, allowing for complex interactions within a
        JSP page.


The Example JSP Pages
  This chapter describes the tasks involved in using and defining tags. The chapter
  illustrates the tasks with excerpts from the JSP version of the Duke’s Bookstore
  application discussed in Chapter 11 rewritten to take advantage of two tag librar-
  ies: Struts and tutorial-template. The section in this chapter entitled
  Examples, page (304), describes some tags in detail: the          tag from Struts
                                                                e ta r et i
  and the set of tags in the tutorial-template tag library.
  The Struts tag library provides a framework for building internationalized Web
  applications that implement the Model-View-Controller design pattern. Struts
  includes a comprehensive set of utility custom tags for handling
      •   HTML forms
      •   Templates
      •   JavaBeans components
      •   Logic processing
  The Duke’s Bookstore application uses tags from the Struts             n ae b   and   c ig ol
  sublibraries.
  The tutorial-template tag library defines a set of tags for creating an application
  template. The template is a JSP page with placeholders for the parts that need to
  change with each screen. Each of these placeholders is referred to as a parameter
  of the template. For example, a simple template could include a title parameter
  for the top of the generated screen and a body parameter to refer to a JSP page
  for the custom content of the screen. The template is created with a set of nested
  tags—               ,        , and
          ne e rc s no i ti ni f ed             —that are used to build a table of
                                      r et em ar a p
  screen definitions for Duke’s Bookstore and with an            tag to insert param-
                                                          t r es ni
  eters from the table into the screen.
282                                       CUSTOM TAGS IN JSP™ PAGES



      Figure 13–1 shows the flow of a request through the following Duke’s Bookstore
      Web components:
           •                 , which determines the structure of each screen. It uses the
               p s j. et a lp me t
                     tag to compose a screen from subcomponents.
                         t re sn i
           •                            , which defines the subcomponents used by
               p sj . sn oi ti n if ed n ee rc s
             each screen. All screens have the same banner, but different title and body
             content (specified by the JSP Pages column in Table 11–1).
           •              , a servlet, which processes requests and forwards to
               re hc t ap si D                                                       m et
                        .
                p sj . et al p




      Figure 13–1 Request Flow through Duke’s Bookstore Components

      The source for the Duke’s Bookstore application is located in the
                                                       directory created when you
      3e ro ts k oo b/ b ew /c rs / se lp m ax e/ la i ro tu te e 2j
      unzip the tutorial bundle (see Downloading the Examples, page (xxii)). To build,
      deploy, and run the example:
           1. Go to
               se lp ma x e/ la i ro tu te e 2j    and build the application by executing
                                     (see How to Build and Run the Examples, page (xxii)).
                                   3 er o ts ko o b tn a
                                         THE EXAMPLE JSP PAGES                                                283


2. Download and unpack Struts version 1.0 from
     /0.1v/esaeler/sturts atrakaj/sdliub/gro.ehcapa.atrakaj//:ptth

     Copy
     ra j. st u rt s                 ,                            , and
                              dl t. c ig ol st ur ts dl t .n ae b s tu rt s                            from
                                         to
     3e r ot sk o ob /b ew / dl iu b /s el pm a xe  b i l/ 0. 1 s tu rt s a tr ak a j
3.   Start the      server.
                 e e2 j
4.   Start             .
            l oo ty ol p ed
5.   Start the Cloudscape database by executing               ep a cs du ol c            tr at s   .
6.   If you have not already created the bookstore database, run                           et ae r c t na
     .b d b ew
7. Create a J2EE application called              pp A 3e ro t sk oo B      .
   a. Select File→New Application.
   b. In the file chooser, navigate                             to              ma xe / la ir o tu te e2 j
                                    .
         3 er ot s ko ob / be w/ cr s /s el p
   c. In the File Name field, enter             pp A 3e ro ts k oo B   .
   d. Click New Application.
   e. Click OK.
8. Create the WAR and add the                             Web component and all
                                             t el vr e Sr eh ct a ps iD
   of the Duke’s Bookstore content to                       .
                                          p pA 3 er ot s ko oB
   a. Select File→New→Web Component.
   b. Click the Create New WAR File in Application radio button and select
                         from the combo box. Enter
         p pA 3e ro t sk oo B                                               in the
                                                                               RA W3 e ro ts k oo B
       field labeled WAR Display Name.
   c. Click Edit to add the content files. In the Edit Contents dialog box, nav-
       igate to                                                         . Select
                  3 e ro ts k oo b/ be w /d li u b/ se lp m ax e/ l ai ro tu t ee 2j
       Dispatcher.class and click Add. Add the JSP pages
          ko ob ps j .r en na b                                           ,
                   ,                   ,                ,                ,
          hs ac p s j. tr ac w oh s ps j. g ol at ac p sj . sl ia t ed ko ob p sj . er ot s
                 ,
         ps j. e ta lp me t         ,
                                  ps j .y or ts e dt in i     ,ps j .t pi ec e r ,    p s j. re i
                                  ,
                      p s j. eg ap r or reand                         .       Add
                                                                p sj . sn oi t in if ed n ee rc s
                         ,                     ,                    ,
         la ir o tu t dl t. c ig ol st ur ts d l t. na eb st ur ts f i g. sk oo b .e ku d
                      , and              . Add the
         se ga s se m , es ab at a d t r ac               ,
                                                        ra j. s tu rt s          ,
                                                                               dl t. et a lp me t
               , and       packages. Click OK.                             l it u       b il ga t
   d. Click Next.
   e. Select the Servlet radio button.
   f. Click Next.
   g. Select                 from the Servlet Class combo box.
                  r e hc ta ps i D
284                                  CUSTOM TAGS IN JSP™ PAGES



         h. Click Next twice.
         i. In the Component Aliases pane, click Add and then type          r et ne /          in the
            Alias field. Repeat to add the aliases             ,                                    ,
                                                                     s li a te dk oo b / go l at ac /
                       ,         , and
            r e ih sa c/ tr a cw oh s /         .t pi ec e r/
         j. Click Finish.
      9. Add the              enterprise bean that you created in the section The
                     BJ EB D ko oB
         Example JSP Pages, page (249).
         a. Select File→Add→EJB JAR.
         b. Navigate to the directory                           .
                                               b j e/ be w /d li ub / se lp m ax e
         c. Select             .
                     r aj .B Dk o ob
         d. Click Add EJB JAR.
      10.Add a reference to the enterprise bean            .
                                                           B JE B Dk oo B
         a. Select                 .
                     R AW 3 er ot sk o oB
         b. Select the EJB Refs tab.
         c. Click Add.
         d. Enter                  in the Coded Name column.
                     B JE BD ko o B/ bj e
         e. Enter Session in the Type column.
         f. Select Remote in the Interfaces column.
         g. Enter                              in the Home Interface column.
                     em oH B JE BD k oo B. es a ba ta d
         h. Enter                         in the Local/Remote Interface column.
                     B JE BD k oo B. es a ba ta d
      11.Add the tag library URI to location mappings (see Declaring Tag
         Libraries, page (285)):
         a. Select the File Refs tab
         b. Click the Add button in the JSP Tag Libraries subpane.
         c. Enter the relative URI                        in the Coded Reference
                                            et a lp me t l ai ro t ut /
            field.
         d. Enter the absolute location                                    in the
                                                d lt .e t al pm et la ir o tu t/ FN I B EW /
            Tag Library field.
         e. Repeat for                    to
            dl t. na e b st ur t s/ FN I B EW /       n a eb s tu r ts /     and
                             to                               .
                             dl t. ci g ol s t ur ts /F N I BE W/ ci go l s tu rt s /
      12.Specify the JNDI names.
         a. Select                 .
                     p pA 3 er ot sk o oB
         b. In the Application table, locate the EJB component and enter                    D ko o B
            BJ E Bin the JNDI Name column.
                                            USING TAGS                                               285


          c. In the References table, locate the EJB Ref and enter     in the  BJ EB D ko oB
             JNDI Name column.
          d. In the References table, locate the Resource component and enter
                                in the JNDI Name column.
              ep a cs du ol C /c bd j
       13.Enter the context root.
          a. Select the Web Context tab.
          b. Enter              .
                     3 er ot s ko ob
       14.Deploy the application.
          a. Select Tools→Deploy.
          b. Click Finish.
       15.Open the bookstore URL         re tn e/ 3 er ot s ko ob /0 0 08 :> t so h < // : pt th.
  See Troubleshooting, page (215) for help with diagnosing common problems.


Using Tags
  This section describes how a page author specifies that a JSP page is using a tag
  library and introduces the different types of tags.

  Declaring Tag Libraries
  You declare that a JSP page will use tags defined in a tag library by including a
         directive in the page before any custom tag is used:
  bi lg a t

       > % "t t "= xi f er p "d l t. et a lp me t l ai ro t ut /F NI BE W/ "= i ru b i lg at @ % <

  The  ir u  attribute refers to a URI that uniquely identifies the tag library descrip-
  tor (TLD), described in the section Tag Library Descriptors, page (290). This
  URI can be direct or indirect. The            attribute defines the prefix that distin-
                                           xi fe r p
  guishes tags defined by a given tag library from those provided by other tag
  libraries.
  Tag library descriptor file names must have the extension        . TLD files are
                                                                           d lt .
  stored in the         directory of the WAR or in a subdirectory of
                 F NI BE W                                                   . You  F NI B EW
  can reference a TLD directly and indirectly.
  The following    bi lg a t   directive directly references a TLD filename:

       > % "t t "= xi f er p "d l t. et a lp me t l ai ro t ut /F NI BE W/ "= i ru b i lg at @ % <
286                                        CUSTOM TAGS IN JSP™ PAGES



      This   b i lg at   directive uses a short logical name to indirectly reference the TLD:

          >% " t t" =x i fe rp " e ta lp m et l ai r ot ut / "= ir u b il ga t @ %<

      A logical name must be mapped to an absolute location in the Web application
      deployment descriptor. To map the logical name
                             e t al pm e t la ir o tu t/                    to the
      absolute location                                  ,
                                                    d l t. et al p me t l ai ro tu t /F NI BE W/
          1. Select                  .
                         RA W3 er o ts ko o B
          2. Select the File Refs tab
          3. Click the Add button in the JSP Tag Libraries subpane.
          4. Enter the relative URI                          in the Coded Reference
                                                e ta lp m et l a ir ot ut /
             field.
          5. Enter the absolute location                                     in the
                                                     d l t. et a lp me t l ai ro t ut /F NI BE W/
             Tag Library field.

      Types of Tags
      JSP custom tags are written using XML syntax. They have a start tag and end
      tag, and possibly a body:

           > ga t: t t<
            y d ob
          >g at :t t /<

      A custom tag with no body is expressed as follows:

          > / ga t: t t<

      Simple Tags
      A simple tag contains no body and no attributes:

          > / e lp mi s: t t<

      Tags With Attributes
      A custom tag can have attributes. Attributes are listed in the start tag and have
      the syntax               . Attribute values serve to customize the behavior of a
                    " e ul av " =r tt a
      custom tag just as parameters are used to customize the behavior of a method.
      You specify the types of a tag’s attributes in a tag library descriptor (see Tag
      Library Descriptors, page (290)).
                                            USING TAGS                                                     287


You can set an attribute value from a           constant or a runtime expression.
                                                g n ir tS
The conversion process between the constants and runtime expressions and
attribute types follows the rules described for JavaBeans component properties
in Setting JavaBeans Component Properties, page (273).
The attributes of the Struts               tag determine whether the body of
                                  tn es e rp :c i go l
the tag is evaluated. In the following example, an attribute specifies a request
parameter named         :
                     r a el C

    > "r ae l C" =r et e ma ra p t ne se r p: ci go l <

The Duke’s Bookstore application page                 uses a runtime expression
                                                  ps j. go l at ac
to set the value of the attribute that determines the collection of books over
which the Struts                 tag iterates:
                    e t ar et i :c ig ol

    " >% )( s ko oB t eg .B Dk o ob =% < "= no it c el lo c e ta re t i: ci go l <
                  > "s li a te Dk o oB .e sa b at ad "= e py t " ko ob "= d i

Tags with Bodies
A custom tag can contain custom and core tags, scripting elements, HTML text,
and tag-dependent body content between the start and end tag.
In the following example, the Duke’s Bookstore application page                      p sj .t r ac wo h s
uses the Struts                 tag to clear the shopping cart and print a message
                 tn es e rp :c ig o l
if the request contains a parameter named          :r ae lC

                    > "r ae l C" =r et e ma ra p t ne se r p: ci go l <
                                     > % ;) ( ra el c .t ra c % <
    > gn or ts < >" 2+ " =e zi s " 00 00 ff # "= ro l oc t no f <
          ! tr a c gn i pp oh s r uo y de r ae lc ts uj u o Y
                    >t n of /< >r b <; ps bn & >r b< > gn or ts / <
                                               >t n es er p :c ig ol / <

Choosing between Passing Information as Attributes or Body
As shown in the last two sections, it is possible to pass a given piece of data as an
attribute of the tag or as the tag’s body. Generally speaking, any data that is a
simple string or can be generated by evaluating a simple expression is best
passed as an attribute.

Tags That Define Scripting Variables
A custom tag can define a variable that can be used in scripts within a page. The
following example illustrates how to define and use a scripting variable that con-
288                                      CUSTOM TAGS IN JSP™ PAGES



      tains an object returned from a JNDI lookup. Examples of such objects include
      enterprise beans, transactions, databases, environment entries, and so on:

           " no it ca s na rT r es U" =e p yt " x t" =d i p uk oo l: t t<
               > / " no i tc as na r Tr es U/ p mo c: a va j" =e m an
                                                > % ;) (n i ge b. xt %<

      In the Duke’s Bookstore application, several pages use bean-oriented tags from
      Struts to define scripting variables. For example,                         uses the
                                                                        p sj . sl ia te d ko ob
                        tag to create the           scripting variable and set it to the
                                                   dI ko o b
                                re te m ar ap :n a eb
      value of the          request parameter. The
                           dI ko o b                                       statement also
                                                                 y tr e po rP te s :p sj
      sets the
      B Dk oo b       property of the
                                  d Ik oo b    object to the value of the         request  dI k oo b
      parameter. The
                en if e d: na e b    tag retrieves the value of the bookstore database
      property                and defines the result as the scripting variable
                         sl i at eD k oo b                                         :            ko o b

                                   > / " dI ko ob " =e ma n " dI ko o b" =d i r et em a ra p: na e b<
                          >/ "d I ko ob " =y tr ep o rp " B Dk oo b" = em an yt re po r Pt es :p s j<
           " s li at e Dk oo b" = yt re p or p "B D ko ob " =e ma n " ko ob " =d i en i fe d: na e b<
                                                      > /" sl ia t eD ko oB . es ab a ta d" =e p yt
                  >2 h /< >" el t it "= y tr ep or p " ko o b" =e ma n y tr e po rP te g :p sj <> 2 h<

      Cooperating Tags
      Customer tags can cooperate with each other through shared objects. In the fol-
      lowing example,       creates an object called
                            1g at                        , which is then reused by
                                                                    1j bo
          .
      2 g at

           > / "e u la v" = 1e ul av "1 jb o "= 1r tt a 1 ga t: t t<
                                  >/ "1 jb o "= 1r tt a 2 ga t: t t<

      In the next example, an object created by the enclosing tag of a group of nested
      tags is available to all inner tags. Since the object is not named, the potential for
      naming conflicts is reduced. This example illustrates how a set of cooperating
      nested tags would appear in a JSP page.

                  > ga T re tu o: t t<
           > / ga T re nn i: t t<
                >g aT r et uo :t t /<

      The Duke’s Bookstore page                     uses a set of cooperating tags to
                                           p sj .e t al pm e t
      define the screens of the application. These tags are described in the section A
      Template Tag Library, page (308).
                                              DEFINING TAGS                                             289


Defining Tags
  To define a tag, you need to:
        • Develop a tag handler and helper classes for the tag
        • Declare the tag in a tag library descriptor
  This section describes the properties of tag handlers and TLDs and explains how
  to develop tag handlers and library descriptor elements for each type of tag intro-
  duced in the previous section.

  Tag Handlers
  A tag handler is an object invoked by a Web container to evaluate a custom tag
  during the execution of the JSP page that references the tag. Tag handlers must
  implement either the      or
                           g aT         interface. Interfaces can be used to take an
                                   ga T yd oB
  existing Java object and make it a tag handler. For newly created handlers, you
  can use the               and
                t ro p pu Sg a T                     classes as base classes. These
                                                                         tr op p uS ga Ty d oB
  classes and interfaces are contained in the
                                         tx eg a t. ps j .t el vr e s. xa va j pack-
  age.
  Tag handler methods defined by the        andg aT      interfaces are called by the
                                                         g a Ty do B
  JSP page’s servlet at various points during the evaluation of the tag. When the
  start tag of a custom tag is encountered, the JSP page’s servlet calls methods to
  initialize the appropriate handler and then invokes the handler’s                   g aT tr a tS od
  method. When the end tag of a custom tag is encountered, the handler’s                dn Eo d
  gaT  method is invoked. Additional methods are invoked in between when a tag
  handler needs to interact with the body of the tag. For further information, see
  How Is a Tag Handler Invoked?, page (313). In order to provide a tag handler
  implementation, you must implement the methods, summarized in Table 13–1,
  that are invoked at various stages of processing the tag.


  Table 13–1 Tag Handler Methods

   Tag Handler Type                         Methods

   Simple                                   esaeler ,gaTdnEod ,gaTtratSod

                                                     ,gaTdnEod ,gaTtratSod
   Attributes
                                            esaeler ,N...1etubirttAteg/tes

   Body, evaluation and no interaction      esaeler ,gaTdnEod ,gaTtratSod
290                                        CUSTOM TAGS IN JSP™ PAGES


      Table 13–1 Tag Handler Methods (Continued)

       Tag Handler Type                           Methods

                                                  ,gaTdnEod ,ydoBretfAod ,gaTtratSod
       Body, iterative evaluation
                                                                             esaeler

                                                    ,esaeler ,gaTdnEod ,gaTtratSod
       Body, interaction
                                                  esaeler ,ydoBretfAod ,ydoBtinIod



      A tag handler has access to an API that allows it to communicate with the JSP
      page. The entry point to the API is the page context object (                       v re s .x av a j
                              ), through which a tag handler can retrieve all the other
      tx e tn oC eg a P. ps j. t el
      implicit objects (request, session, and application) accessible from a JSP page.
      Implicit objects can have named attributes associated with them. Such attributes
      are accessed using                       methods.
                               et u bi rt tA ] te g| t es [
      If the tag is nested, a tag handler also has access to the handler (called the parent)
      associated with the enclosing tag.
      A set of related tag handler classes (a tag library) is usually packaged and
      deployed as a JAR archive.

      Tag Library Descriptors
      A tag library descriptor (TLD) is an XML document that describes a tag library.
      A TLD contains information about a library as a whole and about each tag con-
      tained in the library. TLDs are used by a Web container to validate the tags and
      by JSP page development tools.
      TLD file names must have the extension        . TLD files are stored in the
                                                              dl t.                                  B EW
         directory of the WAR file or in a subdirectory of
      F NI                                                             . When you add a
                                                                          FN I B EW
      TLD to a WAR using               , it automatically puts it into
                                   lo o ty ol p ed                             .      F NI B E W
      A TLD must begin with an XML document prolog that specifies the version of
      XML and the document type definition (DTD):

                                       > ? " 1 95 88 OS I" = gn id oc n e "0 . 1" =n oi s re v lm x ?<
             ga T P S J D TD // . cn I , sm e ts ys or c iM nu S/ / " CI LB U P b il ga t EP YT CO D !<
                                                                                  "N E/ /2 . 1 yr ar b iL
                           >" dt d. 2 _1 _y r ar bi lg a tp sj be w/ dt d /m oc . nu s. av a j/ /: pt t h"
                                              DEFINING TAGS                                              291


The J2EE SDK version 1.3 can understand version 1.1 and 1.2 DTDs. However,
this chapter documents the 1.2 version because you should use the newer version
in any tag libraries that you develop. The template library TLD,                 me t l ai ro t ut
            , conforms to the 1.2 version. The Struts library TLDs conform to the
d lt .e ta l p
1.1 version of the DTD, which has fewer elements and uses slightly different
names for some of the elements.
The root of a TLD is the         bi l ga t   element. The subelements of        bi lg a t   are listed
in Table 13–2:


Table 13–2       bi lg a t   Subelements

 Element                Description

 noisrev bilt           The tag library’s version

 noisrev psj            The JSP specification version that the tag library requires

 eman trohs             Optional name that could be used by a JSP page authoring tool to create
                        names with a mnemonic value

 iru                    A URI that uniquely identifies the tag library

 eman yalpsid           Optional name intended to be displayed by tools

 noci llams             Optional small icon that can be used by tools

 noci egral             Optional large icon that can be used by tools

 noitpircsed            Optional tag-specific information

 renetsil               See listener Element, page (291)

 gat                    See tag Element, page (292)




listener Element
A tag library can specify some classes that are event listeners (see Handling
Servlet Life-Cycle Events, page (216)). The listeners are listed in the TLD as
           elements, and the Web container will instantiate the listener classes
re ne ts i l
and register them in a way analogous to listeners defined at the WAR level.
Unlike WAR-level listeners, the order in which the tag library listeners are regis-
tered is undefined. The only subelement of the               element is the
                                                              re n et si l                      si l
292                                       CUSTOM TAGS IN JSP™ PAGES



      s s al c re n et   element, which must contain the fully qualified name of the
      listener class.

      tag Element
      Each tag in the library is described by giving its name and the class of its tag
      handler, information on the scripting variables created by the tag, and informa-
      tion on the tag’s attributes. Scripting variable information can be given directly
      in the TLD or through a tag extra info class (see Tags That Define Scripting
      Variables, page (298)). Each attribute declaration contains an indication of
      whether the attribute is required, whether its value can be determined by request-
      time expressions, and the type of the attribute (see Tags with
      Attributes, page (294)).
      A tag is specified in a TLD in a        g at   element. The subelements of       ga t   are listed
      in Table 13–3:


      Table 13–3    g at   Subelements

       Element              Description

       eman                 The unique tag name

       ssalc gat            The fully-qualified name of the tag handler class

       ssalc iet            Optional subclass of  ofnIartxEgaT.txegat.psj.telvres.xavaj            .
                            See TagExtraInfo Class, page (301)

       tnetnoc ydob         The body content type. See body-content Element, page (293) and body-
                            content Element, page (298)

       eman yalpsid         Optional name intended to be displayed by tools.

       noci llams           Optional small-icon that can be used by tools.

       noci egral           Optional large-icon that can be used by tools.

       noitpircsed          Optional tag-specific information.

       elbairav             Optional scripting variable information. See variable Element, page (300).

       etubirtta            Tag attribute information. See attribute Element, page (294).
                                           DEFINING TAGS                                            293


The following sections describe the methods and TLD elements that you need to
develop for each type of tag introduced in Using Tags, page (285).

Simple Tags
Tag Handlers
The handler for a simple tag must implement the                  and
                                                                   ga Tt ra t So d   g aT dn E od
methods of the      interface. The
                     g aT                    method is invoked when the start
                                                 ga Tt ra t So d
tag is encountered. This method returns            because a simple tag has no
                                          Y D OB _P IK S
body. The             method is invoked when the end tag is encountered. The
               g aT dn E od
           method needs to return
ga Td nE o d                                if the rest of the page needs to be
                                              EG AP _L A VE
evaluated; otherwise, it should return         .
                                          E GA P _P IK S
The simple tag discussed in the first section,

     >/ e l pm is :t t <

would be implemented by the following tag handler:

                            { tr o pp uS g aT s dn e tx e ga T el pm i S ci lb u p
          { n oi t pe cx Ep s J sw o rh t )( g aT tr at S od t n i ci lb u p
                                                                  { yrt
         ;) ". o ll eH "( t ni rp . )( tu Ot e g. tx e tn oC eg a p
                                    { ) x e no it p ec xE ( h ct ac }
     + " :g aT e lp mi S" ( no it p ec xE ga T ps J w en w or h t
                                 ; )) ( eg as s eM te g. x e
                                                                        }
                                               ; YD O B_ PI K S nr ut e r
                                                                            }
                                            { ) (g aT dn E od t n i ci lb u p
                                               ; EG A P_ LA V E nr ut e r
                                                                            }
                                                                                 }

body-content Element
Tags without bodies must declare that their body content is empty using the
              element:
t ne t no c yd o b

     > t ne tn o c yd ob / <y tp me > tn et n oc y do b <
294                                      CUSTOM TAGS IN JSP™ PAGES



      Tags with Attributes
      Defining Attributes in a Tag Handler
      For each tag attribute, you must define a property and    and     methods that
                                                                             te g    te s
      conform to the JavaBeans architecture conventions in the tag handler. For exam-
      ple, the tag handler for the Struts                tag,
                                               t ne s er p: ci g ol

           >" ra e lC "= re t em ar a p tn es e rp :c ig o l<

      contains the following declaration and methods:

                          ; ll un = re te m ar ap gn ir tS de tc et o rp
                                { )( re te m ar aP t eg g ni r tS c il b up
                                     ;) r et em ar a p. si h t( n ru t er
                                                                           }
           { ) r et em ar a p gn i rt S( re t em ar a Pt es d i ov c il b up
                                ; re te m ar ap = re te m ar ap .s i ht
                                                                           }

      Note that if your attribute is named     and your tag handler inherits from the
                                                    di
                   class, you do not need to define the property and set and get meth-
      t ro pp uS g aT
      ods because these are already defined by              .
                                                           tr op p uS ga T
      A tag attribute whose value is a            can name an attribute of one of the
                                                gn i rt S
      implicit objects available to tag handlers. An implicit object attribute would be
      accessed by passing the tag attribute value to the [                      method
                                                                       e tu bi r tt A] t eg |t es
      of the implicit object. This is a good way to pass scripting variable names to a
      tag handler where they are associated with objects stored in the page context (see
      Tags That Define Scripting Variables, page (298)).

      attribute Element
      For each tag attribute, you must specify whether the attribute is required,
      whether the value can be determined by an expression, and, optionally, the type
      of the attribute in an           element. For static values the type is always
                                          e t ub ir tt a
                           . If the
      gn ir tS . gn al .a v aj                element is
                                 eu l av rp xe t r             or    , then the
                                                                         eu rt      se y            ep yt
      element defines the return type expected from any expression specified as the
      value of the attribute.
                                              DEFINING TAGS                                                295


                                                               >e t ub ir tt a <
                                               >e ma n /< 1r t ta >e ma n <
              > de ri u qe r/ < on |s ey | es la f| e ur t> d er iu qe r <
     >e ul a vr px et r /< on | se y| es l af |e ur t >e ul a vr px et r <
                      > ep yt / < e py t_ d ei fi la u q_ yl l uf >e py t <
                                                             > et u bi rt ta / <

If a tag attribute is not required, a tag handler should provide a default value.
The   ga t  element for the                      tag declares that the
                                     t ne s er p: ci g ol                                r et em a ra p
attribute is not required (because the tag can also test for the presence of other
entities such as bean properties) and that its value can be set by a runtime expres-
sion.

                                                            > ga t <
                               >e ma n/ < tn es e rp >e ma n <
     . bi l ga t. s tu rt s. e hc ap a. g ro >s s al c ga t <
           > ss al c g at /< ga T tn es e rP .c ig o l
            >t ne t no c yd o b/ <P SJ > tn et n oc y do b <
                                                          ...
                                              >e t ub ir tt a <
                     > e ma n/ <r e te ma r ap >e ma n <
              > de ri u qe r/ <e s la f> d er iu qe r <
      > eu l av rp xe t r/ <e ur t >e ul a vr px et r <
                                            > et u bi rt ta / <
                                                          ...
                                                          >g at / <

Attribute Validation
The documentation for a tag library should describe valid values for tag
attributes. When a JSP page is translated, a Web container will enforce any con-
straints contained in the TLD element for each attribute.
The attributes passed to a tag can also be validated at translation time with the
          method of a class derived from
d il aV s i                                              . This class is also used
                                                       of n Ia rt x Eg aT
to provide information about scripting variables defined by the tag (see Tags
That Define Scripting Variables, page (298)).
The           method is passed the attribute information in a
      d i la Vs i                                                            object,
                                                                                   a ta Dg a T
which contains attribute-value tuples for each of the tag’s attributes. Since the
validation occurs at translation time, the value of an attribute that is computed at
request time will be set to                                  .
                                   EU L AV _E M IT _T SE U QE R. a ta Dg aT
The tag       > /" 1e u la v" = 1r tt a aw t: t t<   has the following TLD         e tu bi rt t a   ele-
ment:
296                                       CUSTOM TAGS IN JSP™ PAGES


                                      > e tu bi rt t a<
                      > em a n/ <1 r tt a> em a n<
           > de r iu qe r/ < eu rt > de ri uq e r<
                  >a /< eu r t> eu l av rp xe t r<
                                      e t ub ir tt a /<

      This declaration indicates that the value of          1 r tt a   can be determined at runtime.
      The following           method checks that the value of
                        d il aV s i                                   is a valid Bool-
                                                                              1 rt t a
      ean value. Note that since the value of          can be computed at runtime,
                                                            1 r tt a
               must check whether the tag user has chosen to provide a runtime value.
      di la V si

                                    { of nI ar t xE ga T s dn et x e IE T aw T ss a lc c il b up
                                     { )a t ad a t ad ga T( d il aV si na el o ob c il b up
                               ;) "1 r tt a" ( et ub ir t tA te g. a ta d = o t ce j bO
           { ) EU L AV _E M IT _T SE U QE R. a ta Dg aT =! o & & l lu n = ! o( fi
                         | | ) "e ur t "( sl au q e. )( es a Cr ew o Lo t. o( fi
                        ) )" e sl af "( s la uq e. ) (e sa C re wo Lo t .o
                                                          ;e u rt n ru t er
                                                                            e s le
                                                        ; es l af n ru t er
                                                                                        }
                                                                                   e s le
                                                                 ;e u rt n ru t er
                                                                                          }
                                                                                               }

      Tags With Bodies

      Tag Handlers
      A tag handler for a tag with a body is implemented differently depending on
      whether the tag handler needs to interact with the body or not. By interact, we
      mean that the tag handler reads or modifies the contents of the body.

      Tag Handler Does Not Interact with the Body
      If the tag handler does not need to interact with the body, the tag handler should
      implement the       interface (or be derived from
                        ga T                          t r op pu Sg a T). If the body of the
      tag needs to be evaluated, the                         method needs to return
                                                                   ga Tt r at So d
                            ; otherwise, it should return
      E DU LC NI _ YD OB _L A VE                                    .
                                                       Y D OB _P I KS
      If a tag handler needs to iteratively evaluate the body, it should implement the
                       interface or be derived from
           ga T no it ar e tI                                        . It should return
                                                                t r op pu S ga T
                          from the
      N IA GA _ YD OB _L A VE                    and
                                          g aT tr a tS od           methods if it deter-
                                                                  y d oB re tf A od
      mines that the body needs to be evaluated again.
                                                DEFINING TAGS                                           297


Tag Handler Interacts with the Body
If the tag handler needs to interact with the body, the tag handler must implement
g aT yd o B(or be derived from                   ). Such handlers typically imple-
                                        tr o pp uS ga T yd oB
ment the                 and the
              yd oB t in Io d                    methods. These methods interact
                                         y do Br et f Ao d
with body content passed to the tag handler by the JSP page’s servlet.
Body content supports several methods to read and write its contents. A tag han-
dler can use the body content’s                  or              methods to extract
                                                      re d ae Rt eg       gn ir t St eg
information from the body, and the                        method to write the body
                                                               ) tu o (t uO et i rw
contents to an out stream. The writer supplied to the
                                           t uO et i rw                   method is
obtained using the tag handler’s                       method. This method is used
                                                                  t u Os uo i ve rP te g
to ensure that a tag handler’s results are available to an enclosing tag handler.
If the body of the tag needs to be evaluated, the                                method needs to
                                                                       g aT tr a tS od
return                      ; otherwise, it should return
        D ER EF FU B _Y DO B _L AV E                             YD OB _P I KS      .
y d oB ti nI o d   Method
The              method is called after the body content is set but before it is
      y d oB ti nI o d
evaluated. You generally use this method to perform any initialization that
depends on the body content.
yd o Br et fA o d   Method
The
y do Br et f Ao d  method is called after the body content is evaluated. Like the
             method,
       g a Tt ra tS o d              must return an indication of whether to con-
                            y do B re tf Ao d
tinue evaluating the body. Thus, if the body should be evaluated again, as would
be the case if you were implementing an iteration tag,                     should    yd oB re t fA od
return                       ; otherwise
        D ER EF FU B _Y DO B _L AV E                   should return
                                                     y do Br et f Ao d          .
                                                                            Y DO B_ PI K S
e sa el e r   Method
A tag handler should reset its state and release any private resources in the
        method.
e sa el e r
The following example reads the content of the body (which contains a SQL
query) and passes it to an object that executes the query. Since the body does not
need to be reevaluated,                 returns
                                y d oB re tf A od         .Y DO B_ P IK S

              { tr op p uS ga Ty d oB s d ne tx e g aT yr eu Q s sa l c ci lb u p
      { no i tp ec x Eg aT ps J s wo r ht ) (y d oB re tf A od t n i ci lb u p
                      ; ) (t ne t no Cy do B te g = c b tn e tn oC yd o B
                                        gn i rt s sa cb e h t te g / /
                             ;) ( gn ir tS t eg .c b = y re u q gn ir t S
                                                           pu na el c / /
                                                    ; ) (y do B ra el c. c b
298                                      CUSTOM TAGS IN JSP™ PAGES


                                                                                             { y rt
                      ; )( tn e me ta tS e ta er c .n oi tc e nn oc = tm ts tn em et a tS
                                         ; )y re u q( yr eu Q et uc ex e .t mt s = t lu s er
                                                            { )e no it pe c xE LQ S ( hc ta c }
                                + " :g a Ty re u Q" (n oi t pe cx Eg a Tp sJ we n wo r ht
                                                             ;) ) (e ga s se Mt eg . e
                                                                                                   }
                                                                           ;Y D OB _P I KS n ru t er
                }
           }

      body-content Element
      For tags that have a body, you must specify the type of the body content using
      the                element:
          t n et no c y do b

           >t ne t no c yd o b/ <t n ed ne pe d ga t| P SJ >t ne t no c yd o b<

      Body content containing custom and core tags, scripting elements, and HTML
      text is categorized as        . This is the value declared for the Struts
                                       PSJ
      l                tag. All other types of body content—for example, SQL state-
      t ne se r p: ci g o
      ments passed to the query tag—would be labeled                .t n ed ne p ed ga t
      Note that the value of the                  element does not affect the interpreta-
                                       t ne tn o c yd ob
      tion of the body by the tag handler; the element is only intended to be used by an
      authoring tool for rendering the body content.

      Tags That Define Scripting Variables
      Tag Handlers
      A tag handler is responsible for creating and setting the object referred to by the
      scripting variable into a context accessible from the page. It does this by using
      the
      , em an ( et ub ir t tA te s .t xe tn o Ce ga p           , eu la v or) ep o cs          n oC e ga p
                                             methods. Typically, an attribute passed to
             )e u la v , e ma n( e tu bi rt t At es .t x et
      the custom tag specifies the name of the scripting variable object; this name can
      be retrieved by invoking the attribute’s          method described in Defining
                                                              t eg
      Attributes in a Tag Handler, page (294).
      If the value of the scripting variable is dependent on an object present in the tag
      handler’s context, it can retrieve the object using the                   t At e g. tx e tn oC eg a p
                                 method.
      ) ep o cs , em a n( et ub i rt
                                            DEFINING TAGS                                              299


The usual procedure is that the tag handler retrieves a scripting variable, per-
forms some processing on the object, and then sets the scripting variable’s value
using the                                               method.
           ) tc e jb o ,e ma n (e tu b ir tt At e s. tx e tn oC eg a p
The scope that an object can have is summarized in Table 13–4. The scope con-
strains the accessibility and lifetime of the object.


Table 13–4 Scope of Objects

 Name              Accessible From                           Lifetime

                                                             Until the response has been sent back
 egap              Current page                              to the user or the request is passed to
                                                             a new page

                   Current page and any included or          Until the response has been sent back
 tseuqer
                   forwarded pages                           to the user

                   Current request and any subsequent
 noisses           request from the same browser             The life of the user’s session
                   (subject to session lifetime)

                   Current and any future request from
 noitacilppa                                                 The life of the application
                   the same Web application




Providing Information about the Scripting Variable
The example described in Tags That Define Scripting Variables, page (287)
defines a scripting variable that is used for accessing book information:
                                  ko o b

    "s l ia te D ko ob "= y tr ep o rp " BD k oo b" = em an " k oo b" =d i e ni f ed :n ae b <
                                              > / "s li at e Dk oo B. e sa ba t ad "= ep y t
                                                     > "2 +" =e z is " de r "= ro l oc t no f <
                                > %) "d e vo me R tr aC "( g ni rt St e g. se g as se m= % <
                                   " ko o b" =e m an y tr e po rP te g :p sj < >g no rt s <
                                   > g no rt s /< >/ "e l ti t" = yt re po r p
                                                                           > rb <; p sb n& >r b <
                                                                                      > tn of / <

When the JSP page containing this tag is translated, the Web container generates
code to synchronize the scripting variable with the object referenced by the vari-
300                                         CUSTOM TAGS IN JSP™ PAGES



      able. To generate the code, the Web container requires certain information about
      the scripting variable:
          •     Variable name
          •     Variable class
          •     Whether the variable refers to a new or existing object
          •     The availability of the variable
      There are two ways to provide this information: by specifying the                         el ba i ra v
      TLD subelement or by defining a tag extra info class and including the                     iet
      ss a lc element in the TLD. Using the         element is simpler, but slightly
                                                      e lb ai r av
      less flexible.

      variable Element
      The         element has the following subelements:
           el ba ir a v
          •                  : The variable name as a constant
                ne vi g e ma n
          •                             : The name of an attribute whose translation-time
                e t ub ir tt a m or f e ma n
                value will give the name of the variable
      One of               or
                n e vi g em a n      e tu bi rt t a mo rf em an   is required. The following sub-
      elements are optional:
          •                  : The fully qualified name of the class of the variable.
                   s sa l c el b ai ra v
                                is the default.
                g ni rt S .g na l .a va j
          •          : Whether the variable refers to a new object.
                e r al ce d                                             is the default.
                                                                                   eu rT
          •       : The scope of the scripting variable defined.
                ep oc s                                                     is default.
                                                                                    D ET SE N
            Table 13–5 describes the availability of the scripting variable and the
            methods in which the value of the variable must be set or reset.


      Table 13–5 Scripting Variable Availability

       Value              Availability            Methods

                          Between the start       In ydoBretfAod     and
                                                                    ydoBtinIod          for a tag handler
       DETSEN
                          tag and the end tag     implementinggaTydoB      ; otherwise, in gaTtratSod

                          From the start tag      In              ,
                                                     ydoBretfAod ydoBtinIod        , andgaTdnEod     for a
       NIGEB_TA           until the end of the    tag handler implementing
                                                  gaTydoB                              ; otherwise, in
                          page                         gaTdnEod andgaTtratSod
                                            DEFINING TAGS                                                     301


Table 13–5 Scripting Variable Availability (Continued)

 Value             Availability             Methods

                   After the end tag
 DNE_TA            until the end of the     In   gaTdnEod
                   page



The implementation of the Struts                tag conforms to the JSP specifi-
                                           en i fe d: na e b
cation version 1.1, which requires you to define a tag extra info class. The JSP
specification version 1.2 adds the           element. You could define the fol-
                                             e lb ai r av
lowing            element for the
         e lb ai ra v                           tag:
                                          en if ed : na eb

                                                                                            > ga t <
                                                                               > e lb ai ra v <
                 > et ub i rt ta m o rf e m an /< di > et ub ir t ta m o rf e ma n <
     > s sa lc e l ba ir a v/ <s li a te Dk o oB .e sa b at ad >s s al c e lb ai ra v <
                                                    >e r al ce d/ < eu rt > er al ce d <
                                                    >e p oc s/ <N I GE B_ T A> ep oc s <
                                                                             >e l ba ir av / <
                                                                                          >g at / <

TagExtraInfo Class
You define a tag extra info class by extending the class                                 vr es . xa va j
                       . A
of nI ar t xE ga T .p sj .t e l         must implement the
                                                    o fn Ia rt x Eg aT                   ir aV t eg
           method to return an array of
                   of nI el b a                  objects containing the
                                      o fn Ie l ba ir a V
following information:
     •   Variable name
     •   Variable class
     •   Whether the variable refers to a new object
     •   The availability of the variable
The Web container passes a parameter called             to the  at ad              o fn Ie l ba ir a Vt eg
method that contains attribute-value tuples for each of the tag’s attributes. These
attributes can be used to provide the                object with a scripting vari-
                                                 o f nI el b ai ra V
able’s name and class.
The Struts tag library provides information about the scripting variable created
by the
 i eT en i fe D        tag in the            tag extra info class. Since the name
                             e ni fe d: n ae b
(     ) and class (
 sl ia t eD ko oB . es ab a ta d            ) of the scripting variable are passed
                                               ko ob
in as tag attributes, they can be retrieved with the                   g ni rt S et ub i rt tA te g .a ta d
302                                      CUSTOM TAGS IN JSP™ PAGES



      method and used to fill in the               constructor. To allow the scripting
                                           o fn Ie l ba ir aV
      variable
      ko ob        to be used in the rest of the page, the scope of        is set to be
                                                                                     k oo b
               .
          N IG EB _ TA

                                 { of n Ia rt xE g aT s d ne tx e i eT en i fe D ss a lc c il b up
               { ) at ad at aD g aT (o fn I el ba i ra Vt eg ][ of nI e lb ai r aV c il b up
                          ; )" ep y t" (g ni r tS et u bi rt tA t eg .a ta d = e p yt g ni r tS
                                                                 )l l un = = e py t( fi
                                            ;" tc e jb O. gn a l. av a j" = e p yt
                                                 { ] [o f nI el ba i ra V w en n ru t er
          , ) "d i" ( gn ir tS e tu bi r tt At eg . at ad (o f nI el b ai ra V w en
                                                                      ,e p yt
                                                                      ,e u rt
                                           ) NI GE B_ T A. of n Ie lb ai r aV
                                                                                      ;}
                                                                                              }
                                                                                                 }

      The fully qualified name of the tag extra info class defined for a scripting vari-
      able must be declared in the TLD in the               subelement of the
                                                        s sa lc ie t                ele-         gat
      ment. Thus, the            element for
                         s sa l c ie t                    would be as follows:
                                                          i e Te ni fe D

          i eT ga Te n if eD . na eb .b i lg at . st ur ts . eh ca p a. gr o> s sa lc i e t<
                                                                           >s s al c ie t /<

      Cooperating Tags
      Tags cooperate by sharing objects. JSP technology supports two styles of object
      sharing. The first style requires that a shared object be named and stored in the
      page context (one of the implicit objects accessible to both JSP pages and tag
      handlers). To access objects created and named by another tag, a tag handler uses
      the                                                method.
          ) ep oc s , em an (e t ub ir t tA te g. t xe tn o Ce ga p
      In the second style of object sharing, an object created by the enclosing tag han-
      dler of a group of nested tags is available to all inner tag handlers. This form of
      object sharing has the advantage that it uses a private namespace for the objects,
      thus reducing the potential for naming conflicts.
      To access an object created by an enclosing tag, a tag handler must first obtain its
      enclosing tag with the static method    h ti W ro ts e cn Ad ni f .t ro p pu Sg aT
                              or the
      ) ss a lc , m or f( ss a lC                                 method. The former
                                                                           t n er aP te g .t ro p pu Sg aT
      method should be used when a specific nesting of tag handlers cannot be guaran-
      teed. Once the ancestor has been retrieved, a tag handler can access any statically
      or dynamically created objects. Statically created objects are members of the
                                                              >" s ec na la b "= di yr eu q: x <
                                                                         > .. . n oi tc e nn oc :t t <
                                                                                   >y r eu q: tt / <
            >% )( o nt su C te g. ts e uq er =% < = r eb mu n_ r em ot s uc e re h w
                                  el ba t_ t cc a M OR F ec n al ab , t nu oc c a TC EL E S
                                 > "1 0 no c" =n o it ce n no c "s e cn al ab " =d i y re uq :t t <
                   > no it ce n no c: t t/ < .. . > .. . . "1 0n o c" =d i n oi tc e nn oc :t t <
      lowing ways:
      The query tag implemented by this tag handler could be used in either of the fol-
                                                                                                 }
                                                                                               }
                                                                                        }
                  ; ) (n oi tc e nn oC te g .g aT r ot se cn a = n o it ce nn o c
                                                                                 }
                           ; ) ". ga t n oi tc e nn oc a ni ht i w
           de ts e n eb t s um e t ub ir tt a n oi t ce nn oc a
          tu o ht iw y r eu q A" ( no it p ec xE ga T ps J w en w or h t
                                           { ) ll u n == g a Tr ot s ec na ( f i
                                     ; )s sa lc . ga Tn o it ce nn o C
          ,s i ht (s sa l Ch ti Wr o ts ec n Ad ni f) g aT no i tc en no C (
                                         = ga Tr o ts ec na ga Tn o it ce nn o C
                                                                              { es le }
                                                 ;) di c (e tu b ir tt At e g
                          . tx e tn oC eg a p) no i tc en no C (= n o it ce nn o c
                                   ti es u , di n oi t ce nn oc a si er eh t / /
                                                               { )l l un = ! d ic ( f i
                                             ; ) (n oi tc e nn oC te g = d i c gn ir t S
                          { n oi t pe cx Ep s J sw o rh t )( g aT tr at S od t n i ci lb u p
                                                      ; dI no it c en no c g ni rt S e ta vi r p
                              { tr op p uS ga Ty d oB s d ne tx e g aT yr eu Q s sa l c ci lb u p
      tion object from that handler.
      first retrieves the tag handler for the enclosing tag and then retrieves the connec-
      retrieves the connection object from the page context. Otherwise, the tag handler
                      method. If the                n oi t ce nn o c
                                                     attribute has been set, the handler   g a Tt ra tS o d
                             n oi t ce nn oc
      query tag checks whether an attribute named                     has been set in the
      private object approaches to sharing objects. In the example, the handler for a
      The following example illustrates a tag handler that supports both the named and
                        .                                                           d o ht em eu la Vt e g
      stored in a tag handler with the         eu la Vt e s
                                                    method and retrieved with the
      parent. Private objects can also be created dynamically. Such objects can be
303                                            DEFINING TAGS
304                                         CUSTOM TAGS IN JSP™ PAGES


                                   e lb at _ tc ca MO RF e c na la b , tn uo c ca T CE L ES
             > %) (o n ts uC t eg .t se u qe r =% < = re b mu n_ re m ot su c er e hw
                                                                                    > yr eu q: x /<
                                                                                >n oi tc e nn oc :t t /<

        The TLD for the tag handler must indicate that the                  no it c en no c    attribute is
        optional with the following declaration:

                                                          >g a t<
                                                        . ..
                                           > e tu bi rt t a<
                 > e ma n/ <n o it ce n no c> em a n<
             >d er i uq er /< e sl af > de ri uq e r<
                                         >e t ub ir tt a /<
                                                        > ga t /<


      Examples
        The custom tags described in this section demonstrate solutions to two recurring
        problems in developing JSP applications: minimizing the amount of Java pro-
        gramming in JSP pages and ensuring a common look and feel across applica-
        tions. In doing so, they illustrate many of the styles of tags discussed in the first
        part of the chapter.

        An Iteration Tag
        Constructing page content that is dependent on dynamically generated data often
        requires the use of flow control scripting statements. By moving the flow control
        logic to tag handlers, flow control tags reduce the amount of scripting needed in
        JSP pages.
        The Struts                  tag retrieves objects from a collection stored in a Jav-
                     et a re ti : ci go l
        aBeans component and assigns them to a scripting variable. The body of the tag
        retrieves information from the scripting variable. While elements remain in the
        collection, the         tag causes the body to be reevaluated.
                          et a re ti

        JSP Page
        Two Duke’s Bookstore application pages,                   and
                                                             ps j. go l at ac       , use
                                                                                     ps j. t ra cw oh s
        the
        et a re ti : ci go l tag to iterate over collections of objects. An excerpt from
                      is shown below. The JSP page initializes the
                p s j. go la t ac                                             tag with a
                                                                                     e t ar et i
        collection (named by the             attribute) of the
                                        y tr ep or p                  bean. The
                                                                         BD k oo b                 et ar e ti
        tag sets the       scripting variable on each iteration over the collection. The
                        k o ob
      features.
      body. The following discussion is based on an implementation that uses these
      Body, page (296)) that simplify programming tags that iteratively evaluate their
      (described in the section Tag Handler Does Not Interact with the
                        class. The JSP version 1.2 specification adds features      t ro pp u Sg aT yd o B
      ties of the JSP version 1.1 specification, which requires you to extend the
      The implementation of the Struts   et a re ti : ci go l
                                                       tag conforms to the capabili-
                                                                                     Tag Handler
                                                                            >e t ar et i :c ig ol / <
                           >r t /< >d t/ < >m e/ < >/ "e ma n ru s" = yt re po r p
                                            " ko ob "= e ma n yt r ep or P te g: ps j <
                                      ;p s bn &> / "e ma Nt s ri f" = yt re po r p
                                            " ko ob "= e ma n yt r ep or P te g: ps j <
                       > m e< > % )" yB "( g ni rt S te g. se g as se m= % <; ps b n& ;p sb n &
                                                             > " ff ff ff # "= ro l oc gb d t <
                                                                                          >r t <
                                                         >r t/ <> d t/ <> a /< ;p sb n &
                         > %) "d dA t ra C" ( gn ir tS t eg .s eg a ss em = %< ;p sb n &
                                               > "> %d I ko ob =% < =d dA ? go la ta c /
                                  > %) (h t aP tx e tn oC te g .t se uq e r= %< " =f er h a <
                                            >2 =n a ps wo r " aa ff ff # "= ro l oc gb d t <
                                                                              >d t /< ;p sb n &
              > /" ta mr o f" =y t re po rp "y cn e rr uc "= e ma n yt r ep or P te g: ps j <
                                          >/ " >% )( ec i rP te g. k oo b= % <" =e ul a v
                 " tn uo m a" =y t re po rp "y cn e rr uc "= e ma n yt r ep or P te s: ps j <
                                             >2 =n a ps wo r " aa ff ff # "= ro l oc gb d t <
                      >d t /< >a /< > gn or t s/ <; ps b n& >/ "e l ti t" = yt re po r p
                               " ko o b" =e m an y tr e po rP te g :p sj < >g no rt s <
                                    > "> %d I ko ob =% < =d Ik oo b ?s li a te dk oo b /
                                  > %) (h t aP tx e tn oC te g .t se uq e r= %< " =f er h a <
                                                            > " aa ff ff # "= ro l oc gb d t <
                                                                                         >r t <
                                                  >/ "g n ir tS .g n al .a v aj "= ep y t
           "d I ko ob "= y tr ep o rp " ko o b" =e m an " dI k oo b" =d i e ni f ed :n ae b <
                                    > "s li a te Dk o oB .e sa b at ad "= e py t " ko ob "= d i
                              " sk oo b "= yt re p or p " BD ko ob " =e ma n e ta re t i: ci go l <
      links to other pages and book catalog information.
      Properties of both variables are used to dynamically generate a table containing
               property of the                                      ko ob
                                     variable is exposed as another scripting variable.           dI ko o b
305                                               EXAMPLES
306                                         CUSTOM TAGS IN JSP™ PAGES



      The                   tag supports initializing the collection in several ways: from
           et ar e ti :c i go l
      a collection provided as a tag attribute or from a collection that is a bean or a
      property of a bean. Our example uses the latter method. Most of the code in
                    is concerned with constructing an iterator over the collection object.
      g aT tr at S od
      The method first checks if the handler’s
                                   n o it ce ll o c             property is set and, if not,
      proceeds to check the        and              attributes. If the
                                                 yt r ep or p      n ae b   andn ae b      yt re p or p
      attributes are both set,               calls a utility method that uses JavaBeans
                                                         ga T tr at So d
      introspection methods to retrieve the collection. Once the collection object is
      determined, the method constructs the iterator.
      If the iterator contains more elements,               sets the value of the scripting
                                                      ga Tt r at So d
      variable to the next element and then indicates that the body should be evaluated;
      otherwise, it ends the iteration by returning            .
                                                            YD OB _P I KS
      After the body has been evaluated, the                  method retrieves the body
                                                       yd oB r et fA o d
      content and writes it to the out stream. The body content object is then cleared in
      preparation for another body evaluation. If the iterator contains more elements,
                    again sets the value of the scripting variable to the next element
                            y d oB re tf A od
      and returns
      NI AG A _Y DO B _L AV E            to indicate that the body should be evaluated
      again. This causes the reexecution of                 . When there are no remain-
                                                      y do B re tf Ao d
      ing elements,                 terminates the process by returning
                        yd o Br et fA o d                                          .
                                                                                   Y D OB _P IK S

                                       { t r op pu Sg a T sd n et xe g a Te ta r et I ss a lc c il b up
                                                ; l lu n = r ot ar e ti r ot a re tI de tc et o rp
                                                ; l lu n = n oi tc e ll oc t c ej bO de tc et o rp
                                                             ; ll un = di g n ir tS de tc et o rp
                                                          ; ll un = em an g n ir tS de tc et o rp
                                                    ;l lu n = y tr e po rp g n ir tS de tc et o rp
                                                          ; ll un = ep yt g n ir tS de tc et o rp
                                { no i tp ec xE p sJ s w or ht ) ( ga Tt ra t So d t ni c il b up
                                       ;n o it ce l lo c. si h t = no i tc el l oc t ce j bO
                                                         { ) l lu n == no it c el lo c( fi
                                                                                { y rt
           ;) em a n( et u bi rt tA d ni f. t xe tn oC e ga p = na eb t ce j bO
                                                     { )l l un = = n ae b( fi
                                         n oi tp ec x e na wo rh t . ..
                                                                                }
                                                  )l lu n = = yt r ep or p( fi
                                               ; na e b = n oi tc el l oc
                                                                           e s le
                                                         = n oi tc el l oc
                                               .s li t Uy tr ep o rP
                 ; ) yt re p or p ,n a eb (y t re po rP t eg
                                           { ) l lu n == no it c el lo c( fi
                                         n oi tp ec x e na wo rh t . ..
                                                                                }
      attributes and used to fill in the       o fn Ie l ba ir a V
                                                      constructor.
      info class. The name and class of the scripting variable are passed in as tag
                ie T et ar et I
      Information about the scripting variable is provided in the          tag extra
                                                                         Tag Extra Info Class
                                                                                              }
                                                                                          }
                                                                                      }
                                                    ; )Y DO B _P IK S ( nr ut e r
                                                                               es le }
                                           ;) NI A GA _Y DO B _L AV E ( nr ut e r
                      ; )t ne m el e ,d i (e tu b ir tt At e s. tx e tn oC eg a p
                              ; )( tx en . ro ta r et i = t ne me l e tc ej b O
                                                  { )) ( tx eN sa h .r ot a re ti ( f i
                                                                                      }
                                                                                }
                                                                       ...
                                           { )e no it pe c xE OI ( h ct ac }
                                      ; )( y do Br ae l c. tn e tn oC yd o b
                     ;) ) (g ni rt S te g. t ne tn oC y do b( t ni rp .t u o
                        ; )( tu Os u oi ve r Pt eg = tu o r et ir Wp s J
                                                                           { yrt
                                                 { ) ll u n =! t n et no C yd ob ( f i
                        { no it p ec xE ps J s wo r ht ) (y d oB re tf A od t n i ci lb u p
                                                                                              }
                                                      ; )Y DO B _P IK S ( nr ut e r
                                                                                es le }
                                             ;) NI A GA _Y DO B _L AV E ( nr ut e r
                        ; )t ne m el e ,d i (e tu b ir tt At e s. tx e tn oC eg a p
                                ; )( tx en . ro ta r et i = t ne me l e tc ej b O
                                                   { )) ( tx eN sa h .r ot a re ti ( f i
                                                en on f i y do b e ht p i ks r o / /
                              , et au l av e d na e ul a v ts ri f e ht er ot S / /
                                                                                       }
                                                                              ...
                                ; no it ce l lo c ) ro ta re t I( = ro ta re t i
                           ) ro ta re t I fo e cn at sn i n oi tc e ll oc ( f i es l e
        ; )( r ot ar e ti .) no i tc el lo c ) no i tc el lo C (( = ro ta re t i
                                )n oi t ce ll o C fo ec n at sn i n oi tc e ll oc ( f i
                     no it c el lo c s ih t r of r ot a re ti n a t cu r ts no C / /
                                                                                       }
                                                                             }
                         yt r ep or P te g. sl i tU yt r ep or P y b
                                 n w or ht sn oi tp e cx e h ct ac . . .
                                                                     h ct ac }
307                                               EXAMPLES
308                                        CUSTOM TAGS IN JSP™ PAGES


                         { o fn I ar tx Eg a T sd n et xe i e Te ta r et I ss a lc c il b up
           { ) at ad at aD g aT (o fn I el ba i ra Vt eg ][ of nI e lb ai r aV c il b up
                    ; )" ep y t" (g ni r tS et u bi rt tA t eg .a ta d = e p yt g ni r tS
                                                                  )l l un = = e py t( fi
                                             ;" tc e jb O. gn a l. av a j" = e p yt

                                                         { ] [o f nI el ba i ra V w en n ru t er
                  , ) "d i" ( gn ir tS e tu bi r tt At eg . at ad (o f nI el b ai ra V w en
                                                                              ,e p yt
                                                                              ,e u rt
                                                   ) NI GE B_ T A. of n Ie lb ai r aV
                                                                                         ;}
                                                                                               }
           }

      A Template Tag Library
      A template provides a way to separate the common elements that are part of each
      screen from the elements that change with each screen of an application. Putting
      all the common elements together into one file makes it easier to maintain and
      enforce a consistent look and feel in all the screens. It also makes development
      of individual screens easier because the designer can focus on portions of a
      screen that are specific to that screen while the template takes care of the com-
      mon portions.
      The template is a JSP page with placeholders for the parts that need to change
      with each screen. Each of these placeholders is referred to as a parameter of the
      template. For example, a simple template could include a title parameter for the
      top of the generated screen and a body parameter to refer to a JSP page for the
      custom content of the screen.
      The template uses a set of nested tags—           ,        , and
                                                         ne e rc s n oi ti ni f ed—       re te ma r ap
      to define a table of screen definition for an application screen and uses an
              tag to insert parameters from a screen definition into the application
      t re s ni
      screen.

      JSP Page
      The template for the Duke’s Bookstore example,                       , is shown
                                                                          p sj .e t al pm e t
      below. This page includes a JSP page that creates the screen definition and then
      uses the        tag to insert parameters from the definition into the application
                  t r es ni
      screen.
                                 p s j. et a lp me t
      Finally, the servlet dispatches the request to              :
      instead reflects the path (     p sj .e t al pm e t/ 3e ro t sk oo b /
                                                              ) of the forwarded page.
           g ol at a c/ 3e r ot sk oo b /
      doesn’t contain the original request (for example,                           ) but
                              p sj . et al pm e t
      because when the request is forwarded to                      , the request URL
      requested screen and stores it as an attribute of the request. This is necessary
                     re h ct ap si D
      The template is instantiated by the       re h ct ap s iD
                                                     servlet.              first gets the
                                                                              >n o it in i fe d: tt / <
                                                                                       ...
                                                                   > / "e ur t "= tc er i d
          "> %) "g o la ta C ko oB el t iT "( g ni rt St e g. se ga s se m= % <" =e ul a v
                                                 " el ti t "= em an re te m ar ap :t t <
                                                         >" go l at ac /" = di n e er cs :t t <
                                                                               > ne e rc s: tt / <
                      >/ "e sl a f" =t ce r id " p sj .e ro t sk oo b /" =e ul a v
                                                   "y do b "= em an re te m ar ap :t t <
                          > /" e sl af "= t ce ri d " ps j. r en na b /" =e ul a v
                                                "r en na b "= em an re te m ar ap :t t <
                    > /" eu rt " =t ce ri d " er o ts ko oB s' ek u D" =e ul a v
                                                 " el ti t "= em an re te m ar ap :t t <
                                                             >" r et ne /" = di n e er cs :t t <
                                >" >% )" \n e er cS de t ce le s" \ (e tu b ir tt At e g
                                                    . ts eu qe r )g ni rt S ( =% < "= ne er c s
                                                     " er o ts ko ob " =e ma n n oi ti n if ed :t t <
                                                                                         :n ee rc S de tc el e s
      creates a screen definition based on a request attribute                 p sj .s no i ti ni f ed ne er c s
                                                                                       > lm th / <
                                                                                  > yd ob / <
                                                    >/ "y d ob "= r et em ar a p
                                   " er ot s ko ob "= n oi ti ni f ed t r es ni :t t <
                                                 >/ "r en n ab "= r et em ar a p
                                   " er ot s ko ob "= n oi ti ni f ed t r es ni :t t <
                                                                                  > da eh / <
                                                                          >e lt it / <
                                           > /" el t it "= r et em ar a p
                            " er ot sk o ob "= n oi ti ni f ed t r es ni :t t <
                                                                           > el ti t <
                                                                                    >d ae h <
                       >l mt h <> % " ps j. sn o it in i fe dn ee r cs "= el i f ed u lc ni @ % <
                                         >% " p sj .e g ap ro rr e "= eg aP r or re eg ap @ % <
                 >% "t t" =x i fe rp "d lt .e t al pm e t la ir o tu t/ "= i ru b i lg at @ % <
309                                                  EXAMPLES
                                                                                            }
                                                    ; ED U LC NI _Y D OB _L A VE n ru t er
                             ;) E PO CS _N O IT AC IL P PA .t x et no Ce g ap
      ,) (p a Mh sa H w en , " sn ee r cs "( et u bi rt tA t es .t x et no Ce g ap
                                                            ) ll un == s n ee rc s( fi
                                    ;) E PO CS _N O IT AC IL P PA .t x et no Ce g ap
     ," s ne er cs " (e tu b ir tt At e g. tx e tn oC eg a p )p aM h sa H( = sn ee r cs
                                                       ; l lu n = s ne er c s pa Mh s aH
                                                         { ) ( ga Tt r at So d t ni c il b up
screen identifier and a set of parameters associated with the screen.
contains a hash table of screen definitions. A screen definition consists of a
In   sn e er cs ,                                        g aT no i ti ni fe D g a Tt ra t So d
                                    creates a public object named         that
              g a Tt re sn I
a public named object called                   no i ti ni fe d
                                           that is used by         .
        g aT no i ti ni fe D
nested tag handlers that share public and private objects.              creates
erating tags.         g aT re t em ar a P
                              ,               g aT n ee rc S g aT n oi ti n if eD
                                          , and               comprise a set of
           ,                , and           ga Tt r es nI       g aT r et em a ra P ga Tn ee r cS
                                             —that demonstrate the use of coop-
g aT n oi ti ni f eD
The template tag library contains four tag handlers—                          ,
                                                                             Tag Handlers
                                                                                          }
                                                                                       }
                  ;) es n op se r , ts eu q er (d ra w ro f. r eh ct ap s id
                                                ) l lu n =! re hc t ap si d( fi
     ; )" ps j .e ta lp m et /" ( re hc ta p si Dt se u qe Rt e g. ts eu q er
                                     = re hc ta p si d re h ct ap s iD ts eu q eR
                                     ;) )( h ta Pt el v re St e g. ts eu q er
                         ," ne e rc Sd e tc el es " (e tu bi r tt At e s. ts eu q er
                      { ) es no ps e r es no p se Rt e lv re Sp t tH
                   , ts eu q er t se u qe Rt e lv re Sp t tH (t so P od d i ov c il b up
                                                                                       }
                  ;) es n op se r , ts eu q er (d ra w ro f. r eh ct ap s id
                                                ) l lu n =! re hc t ap si d( fi
     ; )" ps j .e ta lp m et /" ( re hc ta p si Dt se u qe Rt e g. ts eu q er
                                     = re hc ta p si d re h ct ap s iD ts eu q eR
                                     ;) )( h ta Pt el v re St e g. ts eu q er
                         ," ne e rc Sd e tc el es " (e tu bi r tt At e s. ts eu q er
                             { ) es no ps e r es no p se Rt e lv re Sp t tH
                     ,t se u qe r ts e uq eR t el vr eS p tt H( te G od d i ov c il b up
                          { te l vr eS pt t H sd n et xe r e hc ta p si D ss a lc c il b up
                                   CUSTOM TAGS IN JSP™ PAGES                                        310
                  t x et no c e ga p eh t n i n oi ti ni f ed e h t tu p / /
               ; )) ( tx en .r i ) re te m ar aP ( (m ar aP t es .n o it in if e d
                                 ) )( t xe Ns a h. ri & & ) ll un =! r i (( e li h w
                                               ;) ( ro ta re t i. sm a ra p = r i
                                                            ) ll un =! s m ar ap ( f i
                                                            ; ll un = ri ro ta re t I
                                                                              ...
                                                            ) ll un == s m ar ap ( f i
                                                                              ...
                                                                                    es l e
               ; )d I ne er cs ( te g. sn e er cs )t si Ly a rr A( = sm ar a p
                                                           )l lu n = ! sn e er cs ( f i
                           ; )E PO C S_ NO I TA CI LP P A. tx e tn oC eg a p
                            ," s ne er cs " (e tu b ir tt At e g. tx e tn oC eg a p
                                                            ) pa Mh s aH ( = s ne er c s
                                                   ;l lu n = n ee r cs t r op pu Sg a T
                                                    ; ll u n = sm a ra p t si Ly ar r A
                                                   ;l lu n = s ne e rc s e lb at hs a H
                         ; ) (n oi ti n if eD we n = n oi ti ni f ed n o it in if e D
                                                                                         { yrt
                               { n oi t pe cx Eg a Tp sJ sw or ht ) (g aT dn E od t n i ci lb u p
                                       n oi ti n if eD
      the request, and uses it to initialize the             object.
      selects a screen definition from the     sn ee rc s
                                                      object based on the URL passed in
      no it i ni fe D
      In            ,                                           g aT no i ti ni fe D ga Td n Eo d
                                          creates a public object of class            ,
             psj.tpiecer/            psj.rennab/                      tpieceR            tpiecer/
             psj.reihsac/            psj.rennab/                      reihsaC            reihsac/
           psj.tracwohs/             psj.rennab/       traC gnippohS ruoY               tracwohs/
        psj.sliatedkoob/             psj.rennab/          noitpircseD kooB          sliatedkoob/
             psj.golatac/            psj.rennab/               golataC kooB              golatac/
          psj.erotskoob/             psj.rennab/          erotskooB s'ekuD                  retne/
                        Body               Banner                         Title          Screen Id
                                                                  Table 13–6 Screen Definitions
      screen definitions hash table for the Duke’s Bookstore application.
      text provided as attributes to these tags. Table 13–6 shows the contents of the
           ga Tr e te ma ra P     ga T ne er cS
      The table of screen definitions is filled in by         and               from
311                                               EXAMPLES
312                                      CUSTOM TAGS IN JSP™ PAGES


                           ( et u bi rt tA t es .t x et no Ce g ap
                ;) no it i ni fe d , em aN n oi ti ni f ed
                                   { ) xe n oi t pe cx E ( hc ta c }
                                  ;) (e ca r Tk ca t St ni rp . xe
                                                                      }
                                              ;E G AP _L A VE n ru t er
          }

      If the URL passed in the request is /        r et n e, the   no it i ni fe D   contains the items
      from the first row of Table 13–6:


      Table 1

       Title                         Banner                   Body

       erotskooB s’ekuD              psj.rennab/              psj.erotskoob/



      The definition for the URL          is shown in Table 13–7. The definition spec-
                                    r et ne /
      ifies that the value of the     parameter, Duke’s Bookstore, should be inserted
                                         el ti T
      directly into the output stream, but the values of          and       should be
                                                                      r e nn aB        yd oB
      dynamically included.


      Table 13–7 Screen Definition for the URL         re t ne /

       Parameter
       Name                 Parameter Value               isDirect

       eltit                erotskooB s'ekuD              eurt

       rennab               psj.rennab/                   eslaf

       ydob                 psj.erotskoob/                eslaf



                  uses
      ga Tt re s nI                        to insert parameters of the screen definition into
                               n oi t in if eD
      the response. In the ga T tr at So d     method, it retrieves the definition object from
      the page context.
                                 Here is a typical tag handler method invocation sequence:
      tees that                                                                    e s ae le r
                       will be invoked on the tag handler before the end of the page.
      setting methods before calling            g aT tr a tS od
                                                . The JSP page’s servlet also guaran-
                      tn er a Pt es tx et no C eg aP t es
      The JSP page’s servlet invokes the                   ,           , and attribute
      start and end tags are encountered.
      page’s servlet. It defines the life cycle and the methods to be invoked when the
      The       interface defines the basic protocol between a tag handler and a JSP             gaT
                                   How Is a Tag Handler Invoked?
                                                                                                  }
                                                                       ; EG A P_ LA V E nr ut e r
                                                                                                }
                       ; )) ( eg as se M te g. x e( no it p ec xE ga T ps J w en w or h t
                                                            { ) x e no it p ec xE ( h ct ac }
                                                                                         }
           ;) ) (e ul aV t eg .r et e ma ra p (e du lc n i. tx e tn oC eg a p
                            ) )l lu n = ! ) (e ul aV t eg .r e te ma ra p (
                                           & & )l l un = ! r et em a ra p( ( f i
                                                                                  { es l e
       ;) )( e ul aV t eg .r et e ma ra p( t ni rp . )( tu Ot e g. tx e tn oC eg a p
                              )l lu n = ! re t em ar ap && e du l cn It c er id ( f i
                                                                                         { yrt
                                { n oi t pe cx Eg a Tp sJ sw or ht ) (g aT dn E od t n i ci lb u p
      and the response is dynamically included into the overall response.
      directly inserted into the response; otherwise, the request is sent to the parameter
      The                                                                              g aT d nE od
                      method inserts the parameter value. If the parameter is direct, it is
                                                                                                   }
                                                                       ; YD O B_ PI K S nr ut e r
                                ;) (t c er iD s i. re te m ar ap = ed ul c nI tc er i d
                                                               ) l lu n =! re te m ar ap ( f i
                                              ; )e m aN re te m ar ap ( ma ra Pt e g
                                     . n oi ti n if ed )r e te ma ra P ( = r et em ar a p
                     ) ll u n =! no it in i fe d & & ll un =! e ma N re te m ar ap ( f i
                                                                   re te ma r ap e h t te g / /
                                             ; ) em aN no i ti ni fe d (e tu b ir tt At e g
                                     . tx et n oC eg a p )n oi t in if eD ( = n o it in if e d
                             t xe t no c eg a p eh t m or f n oi ti ni f ed e h t te g / /
                                                                { )( g aT tr at S od t n i ci lb u p
313                         HOW IS A TAG HANDLER INVOKED?
                                                                           ;) ( es ae le r .t
                                                        ;) ( yd oB p op .t xe t no Ce ga p .t
                                                                         ; )( g aT dn Eo d .t
                                                                     ;) (y do B re tf Ao d .t
                                                                                         . ..
                                                     no it a ul av e y do b e ta re ti //
                 ew D E RE FF U B_ YD OB _ LA VE sn ru te r y do B re tf Ao d e li hw //
                                                                     ;) (y do B re tf Ao d .t
                                                                      ; )( yd o Bt in Io d .t
te s s i tn e tn oc y d ob r e tf a de d ee n n oi ta zi l ai ti n i yn a m ro fr ep //
                                                           ; )t uo ( tn et no C yd oB te s .t
                                                ; )( yd oB h su p. t xe tn oC e ga p = t uo
                                                                      ; )( ga T tr at So d .t
                                            A typical invocation sequence is as follows:
                                 : Called after evaluation of the tag body        y d oB re tf A od
                                : Called before evaluation of the tag body         y do Bt in I od
                : Creates body content and adds to the tag handler           tn et n oC yd oB t es
handler access its body. The interface provides three new methods:
The          interface extends                         ga T
                                     by defining additional methods that let a tagg aT yd oB
                                                                            ;) ( es ae le r .t
                                                                          ; )( g aT dn Eo d .t
                                                                       ; )( ga T tr at So d .t
                                                         ;) 2 eu la v (2 et ub i rt tA te s .t
                                                         ;) 1 eu la v (1 et ub i rt tA te s .t
                                                                    ; ). .. (t n er aP te s .t
                                                            ; ). .. ( tx et no C eg aP te s .t
                                                               ; )( g aT A we n = t g a TA
                                  CUSTOM TAGS IN JSP™ PAGES                                           314
                                           14
                                 Transactions
                                                                   Dale Green



A typical enterprise application accesses and stores information in one or more
databases. Because this information is critical for business operations, it must be
accurate, current, and reliable. Data integrity would be lost if multiple programs
were allowed to simultaneously update the same information. It would also be
lost if a system that failed while processing a business transaction were to leave
the affected data only partially updated. By preventing both of these scenarios,
software transactions ensure data integrity. Transactions control the concurrent
access of data by multiple programs. In the event of a system failure, transac-
tions make sure that after recovery the data will be in a consistent state.

In This Chapter
          What Is a Transaction? 316
          Container-Managed Transactions 316
               Transaction Attributes 317
               Rolling Back a Container-Managed Transaction 321
               Synchronizing a Session Bean’s Instance Variables 322
               Methods Not Allowed in Container-Managed Transactions 323
          Bean-Managed Transactions 323
               JDBC Transactions 324
               JTA Transactions 325
               Returning without Committing 326
               Methods Not Allowed in Bean-Managed Transactions 327
          Summary of Transaction Options for Enterprise Beans 327
          Transaction Timeouts 328
          Isolation Levels 329
          Updating Multiple Databases 329                                             315
316                                        TRANSACTIONS


                   Transactions in Web Components 331



      What Is a Transaction?
        To emulate a business transaction, a program may need to perform several steps.
        A financial program, for example, might transfer funds from a checking account
        to a savings account with the steps listed in the following pseudocode.

                         n oi tc as n ar t ni g eb
            t nu o cc a g ni kc eh c t ib ed
            t nu o cc a s gn iv as ti de rc
                   go l y ro ts ih et ad pu
                       n o it ca sn a rt t im m oc

        Either all three of these steps must complete, or none of them at all. Otherwise,
        data integrity is lost. Because the steps within a transaction are a unified whole, a
        transaction is often defined as an indivisible unit of work.
        A transaction can end in two ways: with a commit or a rollback. When a transac-
        tion commits, the data modifications made by its statements are saved. If a state-
        ment within a transaction fails, the transaction rolls back, undoing the effects of
        all statements in the transaction. In the pseudocode, for example, if a disk drive
        crashed during the            step, the transaction would roll back and undo the
                               t id er c
        data modifications made by the               statement. Although the transaction
                                                     ti be d
        failed, data integrity would be intact because the accounts still balance.
        In the preceding pseudocode, the         and
                                                n ig eb      statements mark the bound-
                                                               ti m mo c
        aries of the transaction. When designing an enterprise bean, you determine how
        the boundaries are set by specifying either container-managed or bean-managed
        transactions.


      Container-Managed Transactions
        In an enterprise bean with container-managed transactions, the EJB™ container
        sets the boundaries of the transactions. You can use container-managed transac-
        tions with any type of enterprise bean: session, entity, or message-driven. Con-
        tainer-managed transactions simplify development because the enterprise bean
        code does not explicitly mark the transaction’s boundaries. The code does not
        include statements that begin and end the transaction.
                                           CONTAINER-MANAGED TRANSACTIONS              317


Typically, the container begins a transaction immediately before an enterprise
bean method starts. It commits the transaction just before the method exits. Each
method can be associated with a single transaction. Nested or multiple transac-
tions are not allowed within a method.
Container-managed transactions do not require all methods to be associated with
transactions. When deploying a bean, you specify which of the bean’s methods
are associated with transactions by setting the transaction attributes.

Transaction Attributes
A transaction attribute controls the scope of a transaction. Figure 14–1 illustrates
why controlling the scope is important. In the diagram,              begins a trans-
                                                             A d oh te m
action and then invokes              of
                             B d oh te m       . When
                                             2 na eB              executes, does it
                                                               B d o ht em
run within the scope of the transaction started by method-A or does it execute
with a new transaction? The answer depends on the transaction attribute of
          .
B do ht e m




Figure 14–1 Transaction Scope

A transaction attribute may have one of the following values:
    •         d er i uq eR
    •    w e Ns er i uq eR
    •        yr ot a dn aM
    •   de t ro pp u St oN
    •         s tr o pp uS
    •              r ev eN
318                                        TRANSACTIONS



      Required
      If the client is running within a transaction and invokes the enterprise bean’s
      method, the method executes within the client’s transaction. If the client is not
      associated with a transaction, the container starts a new transaction before run-
      ning the method.
      The              attribute will work for most transactions. Therefore, you may
            de ri u qe R
      want to use it as a default, at least in the early phases of development. Because
      transaction attributes are declarative, you can easily change them at a later time.

      RequiresNew
      If the client is running within a transaction and invokes the enterprise bean’s
      method, the container takes the following steps:
           1.   Suspends the client’s transaction
           2.   Starts a new transaction
           3.   Delegates the call to the method
           4.   Resumes the client’s transaction after the method completes
      If the client is not associated with a transaction, the container starts a new trans-
      action before running the method.
      You should use the                attribute when you want to ensure that the
                                  w e Ns er iu q eR
      method always runs within a new transaction.

      Mandatory
      If the client is running within a transaction and invokes the enterprise bean’s
      method, the method executes within the client’s transaction. If the client is not
      associated with a transaction, the container throws the     e ri u qe Rn o it ca sn a rT
                   .
      n oi tp ec x Ed
      Use the               attribute if the enterprise bean’s method must use the trans-
                 y ro t ad na M
      action of the client.

      NotSupported
      If the client is running within a transaction and invokes the enterprise bean’s
      method, the container suspends the client’s transaction before invoking the
      method. After the method has completed, the container resumes the client’s
      transaction.
      If the client is not associated with a transaction, the container does not start a
      new transaction before running the method.
                                           CONTAINER-MANAGED TRANSACTIONS               319


Use the                  attribute for methods that don’t need transactions.
               d et ro pp u St oN
Because transactions involve overhead, this attribute may improve performance.

Supports
If the client is running within a transaction and invokes the enterprise bean’s
method, the method executes within the client’s transaction. If the client is not
associated with a transaction, the container does not start a new transaction
before running the method.
Because the transactional behavior of the method may vary, you should use the
          attribute with caution.
st ro pp u S

Never
If the client is running within a transaction and invokes the enterprise bean’s
method, the container throws a                      . If the client is not associated
                                       n oi tp e cx Ee to m eR
with a transaction, the container does not start a new transaction before running
the method.

Summary of Transaction Attributes
Table 14–1 summarizes the effects of the transaction attributes. Both the T1 and
T2 transactions are controlled by the container. A T1 transaction is associated
with the client that calls a method in the enterprise bean. In most cases, the client
is another enterprise bean. A T2 transaction is started by the container just before
the method executes.
In the last column of Table 14–1, the word “None” means that the business
method does not execute within a transaction controlled by the container. How-
ever, the database calls in such a business method might be controlled by the
transaction manager of the DBMS.


Table 14–1 Transaction Attributes and Scope

 Transaction             Client’s          Business Method’s
 Attribute               Transaction       Transaction

 deriuqeR                None              T2

                         T1                T1
320                                   TRANSACTIONS


      Table 14–1 Transaction Attributes and Scope (Continued)

       Transaction       Client’s            Business Method’s
       Attribute         Transaction         Transaction

       weNseriuqeR       None                T2

                         T1                  T2

       yrotadnaM         None                error

                         T1                  T1

       detroppuStoN      None                None

                         T1                  None

       stroppuS          None                None

                         T1                  T1

       reveN             None                None

                         T1                  Error



      Setting Transaction Attributes
      Because transaction attributes are stored in the deployment descriptor, they can
      be changed during several phases of J2EE™ application development: enterprise
      bean creation, application assembly, and deployment. However, as an enterprise
      bean developer, it is your responsibility to specify the attributes when creating
      the bean. The attributes should be modified only by an application developer
      who is assembling components into larger applications. Do not expect the person
      who is deploying the J2EE application to specify the transaction attributes.
      You can specify the transaction attributes for the entire enterprise bean or for
      individual methods. If you’ve specified one attribute for a method and another
      for the bean, the attribute for the method takes precedence. When specifying
      attributes for individual methods, the requirements differ with the type of bean.
      Session beans need the attributes defined for business methods, but do not allow
      them for the          methods. Entity beans require transaction attributes for the
                        et ae r c
      business,          ,       , and finder methods. Message-driven beans require
                e vo m er e t ae rc
      transaction attributes (either            or
                                       de r iu qe R              ) for the
                                                      d et ro p pu St oN    eg as s eM no
      method.
                                                                                                         }
                                                                                               }
                                                        ; ) )( eg as s eM te g. x e +
                    " :n oi tp e cx EL Q S ot e u d de l ia f no i tc as na r T" (
                                                        n o it pe cx E BJ E we n w or h t
                                                       { ) xe n oi t pe cx EL Q S( h c ta c }
                                                ; ) ec na l aB gn iv a s( gn iv a Se ta d pu
                                                                                           }
                       ; )( no i tp ec x Ee cn al a Bt ne i ci ff us n I we n w or ht
                                               ;) ( yl nO k ca bl lo R te s. tx e tn oc
                                               { ) 00 .0 < ec na l aB gn ik c eh c( fi
                                          ; )e cn a la Bg n ik ce hc ( gn ik ce h Ce ta d pu
                                                                                          { yr t
                                                                 ;t nu om a = + ec n al aB g ni va s
                                                             ; t nu om a = ec na l aB gn i kc eh c
                                                   { n oi t pe cx Ee c na la Bt n ei ci f fu sn I
                            s wo rh t ) tn u om a el b uo d( g ni va So T re fs na r t di o v ci lb u p
      method:
      g ni va S oT re f sn ar t
      matically roll back the transaction. Here is the code for the
      Because the                                                          no it pe c xE BJ E
                                  is a system exception, it causes the container to auto-
      no it p ec xE BJ E
                      and the                         gn i va So Tr e fs na r t
                                                     method throws an                   . n oi t pe cx EL Q S
      methods update database tables. If the updates fail, these methods throw a
      g ni va S et ad p u
      (                           g n ik ce h Ce ta dp u
                                          ). The                   no it p ec xE e cn al aB t ne ic if f us nI
                                                                     and
            invokes                                                yl nO kc a Bl lo R te s
                                            and throws an application exception                            gni
       va So T re fs n ar t
                      method. If a negative checking balance occurs,                         y ln O kc ab ll o R
       te s                     method of the BJ Ek n aB                        g n iv aS o Tr ef sn a rt
                                                          example illustrates the                            The
      j                             directory.                         s ra e/ se l pm ax e /l ai ro t ut ee 2
      tables, type          ra e. pp A kn aB
                                          . A sample          e lb a t kn a b et ae r c t na
                                                                   file is in the
                                        k na b t na
                              directory and type                              s el pm ax e /l ai r ot ut ee 2 j
                                                        . To create the database
                           directory. To compile the code, go to the                 k na b /b je / cr s/ se l p
       ma xe / la ir o tu te e2 j
      The source code for the following example is in the
      cation exceptions, see Handling Exceptions, page (116).
      be initiated by a call to                            y ln O kc ab ll o Rt es
                                                . For a description of system and appli-
      the bean throws an application exception, the rollback is not automatic, but may
      interface, the bean method instructs the container to roll back the transaction. If
      t xe tn o CB JE
      tion. Second, by invoking the          y ln Ok ca b ll oR te s
                                                           method of the
      tem exception is thrown, the container will automatically roll back the transac-
      There are two ways to roll back a container-managed transaction. First, if a sys-
               Rolling Back a Container-Managed Transaction
321                           CONTAINER-MANAGED TRANSACTIONS
322                                       TRANSACTIONS



      When the container rolls back a transaction, it always undoes the changes to data
      made by SQL calls within the transaction. However, only in entity beans will the
      container undo changes made to instance variables. (It does so by automatically
      invoking the entity bean’s            method, which loads the instance variables
                                        d a oL bj e
      from the database.) When a rollback occurs, a session bean must explicitly reset
      any instance variables changed within the transaction. The easiest way to reset a
      session bean’s instance variables is by implementing the                  a zi n or hc n yS no is s eS
      n o itinterface.

      Synchronizing a Session Bean’s Instance Variables
      The                             interface, which is optional, allows you to syn-
           no it az i no rh cn y Sn oi s se S
      chronize the instance variables with their corresponding values in the database.
      The container invokes the                                methods—
                                       n oi ta zi n or hc n yS no is s eS            ,       n ig e Br et fa
                          , and
      no it el p mo Ce ro f eb                     —at each of the main stages of a
                                                     n o it el p mo Cr et f a
      transaction.
      The              method informs the instance that a new transaction has begun.
                              ni g eB re t fa
      The container invokes
      n ig e Br et fa                     immediately before it invokes the business
      method. The              method is a good place to load the instance variables
                   n ig eB r et fa
      from the database. The
        na e Bk na B                    class, for example, loads the                     l aB g ni kc e hc
           and                 variables in the
                   e cn al aB g ni va s      e c na         method:
                                                           ni ge Br e tf a

           { )( n ig eB r et fa d i ov c il b up

                                        ;) ") ( ni ge B re tf a" ( nl tn i rp .t uo . me ts yS
                                                                                       { y rt
                                   ; )( gn ik c eh Ct c el es = ec na l aB gn ik c eh c
                                         ; )( g ni va S tc el es = ec n al aB gn i va s
                                                    { )x e no i tp ec x EL QS ( h ct ac }
               + " :n oi tp e cx E n ig eB re t fa "( n oi tp ec x EB JE we n wo r ht
                                                        ;) )( eg a ss eM t eg .x e
                                                                                             }
           }

      The container invokes the                         method after the business method
                                       n oi t el pm o Ce ro fe b
      has finished, but just before the transaction commits. The                    no it e lp mo C er of eb
      method is the last opportunity for the session bean to roll back the transaction
      (by calling                   ). If it hasn’t already updated the database with the
                    y l nO kc a bl lo Rt e s
      values of the instance variables, the session bean may do so in the                     m oC e ro fe b
      no it e lpmethod.
      The  n o it el pm o Cr et f amethod indicates that the transaction has completed. It
      has a single
              n ae l oo b        parameter, whose value is      if the transaction was com-
                                                                   e ur t
                                              BEAN-MANAGED TRANSACTIONS                                   323


  mitted and         if it was rolled back. If a rollback occurred, the session bean
               e sl a f
  can refresh its instance variables from the database in the                   n oi te l pm oC r et fa
  method:

      { ) d et ti m mo c na e lo ob ( no it el p mo Cr et f a di o v ci lb u p

                     ; )d e tt im mo c + " :n oi te l pm oC r et fa "( n lt ni rp . tu o. m et sy S
                                                               { ) es la f = = de t ti mm o c( f i
                                                                                        { y rt
                                      ;) (g n ik ce hC t ce le s = e cn a la Bg ni k ce hc
                                            ; )( gn iv a St ce l es = e c na la Bg n iv as
                                                       { ) xe no it pe c xE LQ S( hc ta c }
          : no it p ec xE L QS no it el p mo Cr e tf a" (n o it pe c xE BJ E w en wo r ht
                                                      ; )) (e ga s se Mt e g. xe + "
                                                                                             }
                                                                                                  }
      }

  Methods Not Allowed in Container-Managed
  Transactions
  You should not invoke any method that might interfere with the transaction
  boundaries set by the container. The list of prohibited methods follows:
      • The               ,
          ti m mo Co t uA te s t im mo c        , and   k c ab ll or   methods of    no C. l qs .a v aj
                                   no i tc en
      • The    no i tc as na r Tr es U te g   method of     t x et no CB J E. bj e. x av aj
      • Any method of         n oi tc a sn ar Tr e sU .n o it ca sn a rt .x a va j
  You may, however, use these methods to set boundaries in bean-managed trans-
  actions.


Bean-Managed Transactions
  In a bean-managed transaction, the code in the session or message-driven bean
  explicitly marks the boundaries of the transaction. An entity bean cannot have
  bean-managed transactions; it must use container-managed transactions instead.
  Although beans with container-managed transactions require less coding, they
  have one limitation: When a method is executing, it can be associated with either
  a single transaction or no transaction at all. If this limitation will make coding
  your bean difficult, you should consider using bean-managed transactions.
324                                       TRANSACTIONS



      The following pseudocode illustrates the kind of fine-grained control you can
      obtain with bean-managed transactions. By checking various conditions, the
      pseudocode decides whether to start or stop different transactions within the
      business method.

                     n oi tc as n ar t ni g eb
                                          . ..
                          a el b at e ta d pu
                                          . ..
                       )x n oi t id no c( fi
               no it c as na rt ti mm oc
               )y n o it id no c ( fi e s le
                     b e lb at et ad pu
               no it c as na rt ti mm oc
                                        e s le
           n o it ca s na rt k c ab ll or
                n oi t ca sn ar t n ig eb
                     c e lb at et ad pu
               no it c as na rt ti mm oc

      When coding a bean-managed transaction for session or message-driven beans,
      you must decide whether to use JDBC or JTA transactions. The sections that fol-
      low discuss both types of transactions.

      JDBC Transactions
      A JDBC transaction is controlled by the transaction manager of the DBMS. You
      may want to use JDBC transactions when wrapping legacy code inside a session
      bean. To code a JDBC transaction, you invoke the              and  t i mm oc  meth-
                                                                                        kc a bl lo r
      ods of the                           interface. The beginning of a transaction is
                    n oi t ce nn o C. lq s. a va j
      implicit. A transaction begins with the first SQL statement that follows the most
      recent         ,          , or
              kc ab ll o r ti mm oc           statement. (This rule is generally true, but
                                           t ce nn o c
      may vary with DBMS vendor.)

      Source Code
      The source code for the following example is in the                        m ax e /l ai r ot ut ee 2 j
                                 directory. To compile the code, go to the
                           e su oh e ra w/ bj e /c rs /s e lp
                              directory and type          . To create the database
                             se lp m ax e/ la i ro tu te e 2j                              kn ab tn a
      tables, type  c
      e lb a t es uo h er aw et ae r tn a      . A sample                    file is
                                                                   r a e. pp A es uo he r aW
      in the j                             directory.
             s ra e/ s el pm ax e /l ai r ot ut ee 2
      The following code is from the                example, a session bean that uses
                                              BJ E es uo he r aW
      the             interface’s methods to delimit bean-managed transactions. The
          no i tc en no C
                                          BEAN-MANAGED TRANSACTIONS                                 325


pi h smethod starts by invoking                       on the
                                          ti mm oC o tu At e s              object
                                                                         n oi t ce nn o C
named       . This invocation tells the DBMS not to automatically commit every
         no c
SQL statement. Next, the         method calls routines that update the
                                pi h s                                            m et i_ r ed ro
and              database tables. If the updates succeed, the transaction is com-
     yr o tn ev ni
mitted. If an exception is thrown, however, the transaction is rolled back.

     t ni ,d Ir ed r o gn i rt S ,d I tc ud o rp g ni r tS ( pi h s di o v ci lb u p
                                                                    { ) yt it na u q

                                                                                    { yr t
                                               ; )e s la f( ti m mo Co tu A te s. n oc
                              ;) d Ir ed ro ,d It c ud or p( m et Ir ed r Oe ta d pu
                            ; )y t it na uq ,d It c ud or p( y ro tn ev n Ie ta d pu
                                                                  ; )( ti m mo c. n oc
                                                      { )x e n oi tp ec x E( h c ta c }
                                                                             { yrt
                                                         ;) (k c ab ll or . no c
         + " : d el ia f n oi tc a sn ar T" ( no it p ec xE BJ E w en w o rh t
                                                 ;) ) (e ga ss e Mt eg .x e
                                         { ) xq s n oi tp ec x EL QS ( h ct ac }
           + " :d el ia f k ca b ll oR "( n oi tp e cx EB JE we n wo r ht
                                              ;) )( e ga ss eM t eg .x qs
                                                                                    }
                                                                                         }
     }

JTA Transactions
JTA is the abbreviation for the Java™ Transaction API. This API allows you to
demarcate transactions in a manner that is independent of the transaction man-
ager implementation. The J2EE SDK implements the transaction manager with
the Java Transaction Service (JTS). But your code doesn’t call the JTS methods
directly. Instead, it invokes the JTA methods, which then call the lower-level JTS
routines.
A JTA transaction is controlled by the J2EE transaction manager. You may want
to use a JTA transaction because it can span updates to multiple databases from
different vendors. A particular DBMS’s transaction manager may not work with
heterogeneous databases. However, the J2EE transaction manager does have one
limitation—it does not support nested transactions. In other words, it cannot start
a transaction for an instance until the previous transaction has ended.
The source code for the following example is in the                   ma xe / la ir o tu te e2 j
                       directory. To compile the code, go to the
   r el le t /b je / cr s/ se l p
                       directory and type
s el pm ax e /l ai r ot ut ee 2 j                  . To create the database
                                                      re ll et t na
326                                      TRANSACTIONS



      tables, type
      re l le t k na b et a er c tn a               . A sample      r ae .p p Ar el le T   file is in the
      j                                       directory.
               sr ae /s e lp ma x e/ la ir o tu te e 2
      To demarcate a JTA transaction, you invoke the
                                          ti m mo c ni ge b     ,        , and                kc ab l lo r
      methods of the                                              interface. The follow-
                                                   no i tc as na r Tr es U .n oi tc a sn ar t .x av aj
      ing code, taken from the
                      no it c as na r Tr es U class, demonstrates the       n ae B re ll eT
      methods. The           and         invocations delimit the updates to the database.
                                                                                  ti m mo c       n ig e b
      If the updates fail, the code invokes the
                       x EB J E                           method and throws an
                                                            k c ab ll o r
               .
      no it p ec

          { ) tn uo m a el b uo d( hs a Cw ar d ht iw d i ov c il b up

               ; )( no it c as na r Tr es Ut e g. tx e tn oc = tu n o it ca sn a rT re sU

                                                                                          { y rt
                                                                            ; )( ni ge b .t u
                                                         ; )t nu om a (g ni k ce hC et a dp u
                                                      ;t n uo ma = e cn a la Be ni h ca m
                                              ;) e cn al a Be ni hc a m( en i hc aM tr e sn i
                                                                          ; ) (t im mo c .t u
                                                            { ) xe no it p ec xE ( h ct ac }
                                                                                    { y rt
                                                                 ;) ( kc ab l lo r. tu
                                          { ) xe y s no i tp ec xE m et sy S ( hc ta c }
                                                   no it p ec xE BJ E w en wo rh t
               ; )) ( eg as se M te g. x ey s + " : de l ia f kc a bl lo R "(
                                                                                          }
                                                         n oi tp ec x EB JE we n wo r ht
                    ; )) (e ga s se Mt e g. xe + " :d e li af n o it ca s na rT "(
                                                                                              }
          }

      Returning without Committing
      In a stateless session bean with bean-managed transactions, a business method
      must commit or roll back a transaction before returning. However, a stateful ses-
      sion bean does not have this restriction.
      In a stateful session bean with a JTA transaction, the association between the
      bean instance and the transaction is retained across multiple client calls. Even if
      each business method called by the client opens and closes the database connec-
      tion, the association is retained until the instance completes the transaction.
      In a stateful session bean with a JDBC transaction, the JDBC connection retains
      the association between the bean instance and the transaction across multiple
      calls. If the connection is closed, the association is not retained.
                                              SUMMARY OF TRANSACTION OPTIONS FOR ENTERPRISE BEANS327



  Methods Not Allowed in Bean-Managed
  Transactions
  Do not invoke the                    and
                            y ln O kc ab ll o Rt eg           methods of the
                                                        yl n Ok ca bl l oR te s
              interface in bean-managed transactions. These methods should be
  t x et no CB J E
  used only in container-managed transactions. For bean-managed transactions,
  invoke the             and
                 s u ta tS t eg       methods of the
                                      kc ab l lo r                      inter-
                                                                     no i tc as na r Tr es U
  face.


Summary of Transaction Options for
Enterprise Beans
  If you’re unsure about how to set up transactions in an enterprise bean, here’s a
  tip: In the bean’s deployment descriptor, specify container-managed transac-
  tions. Then, set the            transaction attribute for the entire bean. This
                             d er i uq eR
  approach will work most of the time.
  Table 14–2 lists the types of transactions that are allowed for the different types
  of enterprise beans. An entity bean must use container-managed transactions.
  With container-managed transactions, you specify the transaction attributes in
  the deployment descriptor and you roll back a transaction with the                   ll oR t es
            method of the
  yl nO kc a b                           interface.
                                  tx et no C BJ E
  A session bean may have either container-managed or bean-managed transac-
  tions. There are two types of bean-managed transactions: JDBC and JTA trans-
  actions. You delimit JDBC transactions with the        and t i mm oc  methods
                                                                            kc a bl lo r
  of the
  no it c en no C      interface. To demarcate JTA transactions, you invoke the
         ,       , and
       t im mo c n ig e b         methods of the
                            kc a bl lo r                         interface.
                                                         n oi tc a sn ar T re sU
  In a session bean with bean-managed transactions, it is possible to mix JDBC
  and JTA transactions. This practice is not recommended, however, because it
  could make your code difficult to debug and maintain.
328                                        TRANSACTIONS



        Like a session bean, a message-driven bean may have either container-managed
        or bean-managed transactions.


        Table 14–2 Allowed Transaction Types for Enterprise Beans

                                                                          Bean-Managed

            Bean Type          Container-Managed                    JTA                    JDBC

         Entity                Y                            N                          N

         Session               Y                            Y                          Y

         Message-driven        Y                            Y                          Y




      Transaction Timeouts
        For container-managed transactions, you control the transaction timeout interval
        by setting the value of the                                   property in the
                                                       tu o em it .n o it ca s na rt
                               file, which is in the
        s e it re po r p. tl ua f ed                      directory of your J2EE SDK
                                                                   g if no c
        installation. For example, you would set the timeout value to 5 seconds as fol-
        lows:

             5= tu o em it .n o it ca sn a rt

        With this setting, if the transaction has not completed within 5 seconds, the EJB
        container rolls it back.
        When the J2EE SDK is first installed, the timeout value is set to 0:

             0= tu o em it .n o it ca sn a rt

        If the value is 0, the transaction will not time out.
        Only enterprise beans with container-managed transactions are affected by the
                                 property. For enterprise beans with bean-managed JTA
        tu o em it .n o it ca sn a rt
        transactions, you invoke the                              method of the
                                                tu oe m iT no it c as na r Tt es                  r es U
                      interface.
        n o it ca sn a rT
                                              ISOLATION LEVELS                                       329


Isolation Levels
  Transactions not only ensure the full completion (or rollback) of the statements
  that they enclose but also isolate the data modified by the statements. The isola-
  tion level describes the degree to which the data being updated is visible to other
  transactions.
  Suppose that a transaction in one program updates a customer’s phone number,
  but before the transaction commits another program reads the same phone num-
  ber. Will the second program read the updated and uncommitted phone number
  or will it read the old one? The answer depends on the isolation level of the
  transaction. If the transaction allows other programs to read uncommitted data,
  performance may improve because the other programs don’t have to wait until
  the transaction ends. But there’s a trade-off—if the transaction rolls back,
  another program might read the wrong data.
  You cannot modify the isolation level of entity beans with container-managed
  persistence. These beans use the default isolation level of the DBMS, which is
  usually                 .
          D E TT IM MO C _D AE R
  For entity beans with bean-managed persistence and for all session beans, you
  can set the isolation level programmatically with the API provided by the under-
  lying DBMS. A DBMS, for example, might allow you to permit uncommitted
  reads by invoking the                               method:
                             n oi ta lo s In oi t ca sn ar T te s

                                                                          ; n oc n o it ce nn o C
                                                                                             ...
      ; ) DE TT I MM OC NU _ DA ER _ NO IT CA S NA RT ( no it al o sI no it c as na r Tt es .n o c

  Do not change the isolation level in the middle of a transaction. Usually, such a
  change causes the DBMS software to issue an implicit commit. Because the iso-
  lation levels offered by DBMS vendors may vary, you should check the DBMS
  documentation for more information. Isolation levels are not standardized for the
  J2EE platform.


Updating Multiple Databases
  The J2EE transaction manager controls all enterprise bean transactions except
  for bean-managed JDBC transactions. The J2EE transaction manager allows an
  enterprise bean to update multiple databases within a transaction. The figures
  that follow show two scenarios for updating multiple databases in a single trans-
  action.
330                               TRANSACTIONS



      In Figure 14–2, the client invokes a business method in   A na e B . The business
      method begins a transaction, updates Database X, updates Database Y, and
      invokes a business method in    B n ae B . The second business method updates
      Database Z and returns control to the business method in   A n ae B  , which com-
      mits the transaction. All three database updates occur in the same transaction.




      Figure 14–2 Updating Multiple Databases

      In Figure 14–3, the client calls a business method in        , which begins a
                                                              A n ae B
      transaction and updates Database X. Then,  A na eBinvokes a method in        ,
                                                                              B n a eB
      which resides in a remote J2EE server. The method in         updates Database
                                                             B n ae B
      Y. The transaction managers of the J2EE servers ensure that both databases are
      updated in the same transaction.
                                           TRANSACTIONS IN WEB COMPONENTS                 331




  Figure 14–3 Updating Multiple Databases across J2EE Servers


Transactions in Web Components
  You may demarcate a transaction in a Web component with either the
                           or
  n oi tc e nn oC . lq s. av a j                                      interface.
                                   n oi tc a sn ar T re sU .n o it ca sn a rt .x a va j
  These are the same interfaces that a session bean with bean-managed transac-
  tions may use. Transactions demarcated with the             interface are dis-
                                                              n oi tc en n oC
  cussed in the section JDBC Transactions, page (324) and those with the
                        interface are discussed in the section JTA
  n o it ca s na rT re s U
  Transactions, page (325). For an example of a Web component using transac-
  tions, see Accessing Databases, page (221).
332   TRANSACTIONS
                                                                    15
                                                              Security
                                                                               Eric Jendrock



T   he J2EE application programming model insulates developers from mecha-
nism-specific implementation details of application security. J2EE provides this
insulation in a way that enhances the portability of applications, allowing them
to be deployed in diverse security environments.
Some of the material in this chapter assumes that you have an understanding of
basic security concepts. To learn more about these concepts, we highly recom-
mend that you explore the Security trail in the Java Tutorial (see
                                                                          )
l mt h. x ed ni / 2. 1y ti r uc es / la ir ot u t/ sk o ob /s co d /m oc .n u s. av a j/ /: pt t h
before you begin this chapter.

In This Chapter
             Overview 334
             Security Roles 335
                 Declaring and Linking Role References 335
                 Mapping Roles to J2EE Users and Groups 337
             Web-Tier Security 337
                 Protecting Web Resources 337
                 Controlling Access to Web Resources 338
                 Authenticating Users of Web Resources 338
                 Using Programmatic Security in the Web Tier 340
                 Unprotected Web Resources 340
             EJB-Tier Security 341
                 Declaring Method Permissions 341
                 Using Programmatic Security in the EJB Tier 341
                 Unprotected EJB-Tier Resources 342
                                                                                                     333
334                                    SECURITY


                    Application Client-Tier Security 342
                         Specifying the Application Client’s Callback Handler 343
                    EIS-Tier Security 343
                         Configuring Sign-On 344
                         Container-Managed Sign-On 344
                         Component-Managed Sign-On 344
                         Configuring Resource Adapter Security 345
                    Propagating Security Identity 346
                         Configuring a Component’s Propagated Security Identity 347
                         Configuring Client Authentication 347
                    J2EE Users, Realms, and Groups 348
                         Managing J2EE Users and Groups 349
                    Setting Up a Server Certificate 350



      Overview
        The J2EE platform defines declarative contracts between those who develop and
        assemble application components and those who configure applications in oper-
        ational environments. In the context of application security, application provid-
        ers are required to declare the security requirements of their applications in such
        a way that these requirements can be satisfied during application configuration.
        The declarative security mechanisms used in an application are expressed in a
        declarative syntax in a document called a deployment descriptor. An application
        deployer then employs container-specific tools to map the application require-
        ments that are in a deployment descriptor to security mechanisms that are imple-
        mented by J2EE containers. The J2EE SDK provides this functionality with
                     .
        l oo ty ol p ed
        Programmatic security refers to security decisions that are made by security-
        aware applications. Programmatic security is useful when declarative security
        alone is not sufficient to express the security model of an application. For exam-
        ple, an application might make authorization decisions based on the time of day,
        the parameters of a call, or the internal state of an enterprise bean or Web compo-
        nent. Another application might restrict access based on user information stored
        in a database.
        J2EE applications are made up of components that can be deployed into different
        containers. These components are used to build a multitier enterprise applica-
        tion. The goal of the J2EE security architecture is to achieve end-to-end security
        by securing each tier.
                                      SECURITY ROLES                                     335


  The tiers can contain both protected and unprotected resources. Often, you need
  to protect resources to ensure that only authorized users have access. Authoriza-
  tion provides controlled access to protected resources. Authorization is based on
  identification and authentication. Identification is a process that enables recogni-
  tion of an entity by a system, and authentication is a process that verifies the
  identity of a user, device, or other entity in a computer system, usually as a pre-
  requisite to allowing access to resources in a system.
  Authorization is not required to access unprotected resources. Because authori-
  zation is built upon authentication, authentication is also not needed to access
  unprotected resources. Accessing a resource without authentication is referred to
  as unauthenticated or anonymous access.


Security Roles
  When you design an enterprise bean or Web component, you should always
  think about the kinds of users who will access the component. For example, an
            enterprise bean might be accessed by customers, bank tellers, and
  t nu oc c A
  branch managers. Each of these user categories is called a security role, an
  abstract logical grouping of users that is defined by the person who assembles
  the application. When an application is deployed, the deployer will map the roles
  to security identities in the operational environment.
  A J2EE group also represents a category of users, but it has a different scope
  from a role. A J2EE group is designated for the entire J2EE server, whereas a
  role covers only a specific application in a J2EE server.
  To create a role for a J2EE application, you declare it for the EJB JAR file or for
  the WAR file that is contained in the application. For example, you could use the
  following procedure to create a role in             .
                                          l oo t yo lp ed
       1. Select the enterprise bean’s EJB JAR file or the Web component’s WAR
          file.
       2. In the Roles tabbed pane, click Add.
       3. In the table, enter values for the Name and Description fields.

  Declaring and Linking Role References
  A security role reference allows an enterprise bean or Web component to refer-
  ence an existing security role. A security role is an application-specific logical
  grouping of users, classified by common traits such as customer profile or job
  title. When an application is deployed, roles are mapped to security identities,
336                                      SECURITY



      such as principals (identities assigned to users as a result of authentication) or
      groups, in the operational environment. Based on this, a user with a certain secu-
      rity role has associated access rights to a J2EE application. The link is the actual
      name of the security role that is being referenced.
      During application assembly, the assembler creates security roles for the applica-
      tion and associates these roles with available security mechanisms. The assem-
      bler then resolves the security role references in individual servlets and JSPs by
      linking them to roles defined for the application.
      The security role reference defines a mapping between the name of a role that is
      called from a Web component using                                     (see Using
                                                    ) em an gn i rt S( e lo Rn Ir e sU si
      Programmatic Security in the Web Tier, page (340)) or from an enterprise bean
      using                                    (see Using Programmatic Security in the
            )e ma n g ni rt S( e lo Rn I re ll aC s i
      EJB Tier, page (341)) and the name of a security role that has been defined for
      the application. For example, to map the security role reference     to the secu-
                                                                                      t su c
      rity role with role name               , you would do the following:
                                   r em ot s uC kn a b
          1. Select the Web component or enterprise bean.
          2. Select the Security tab.
          3. If the       entry does not appear in the Role Names Referenced In Code
                     t s uc
              pane, click the Add button.
          4. Enter the name of the security role reference       in the Coded Name col-
                                                                        t s uc
              umn.
          5. From the drop-down menu in the Role Name column, select the security
              role name                  that maps to the coded name.
                           r em o ts uC kn a b
             If the security role name to which you want to map the security role refer-
             ence is not listed in the Role Name column, click Edit Roles and add the
             role (see Security Roles, page (335)).
          6. Click on the folded paper icon to add a description for the                t s uc   role refer-
             ence.
          7. In the Description dialog box, enter a description.
          8. Click OK to accept the description, or Cancel to cancel it.
      In this example,                                        and
                         ) "r e mo ts uC k na b" (e l oR nI r es Us i        )" ts u c" (e l oR nI re s Us i
      will both return         for the methods indicated in the Method Permissions pane.
                                                               eu r t
      Because a coded name is linked to a role name, you can change the role name at
      a later time without having to change the coded name. For example, if you were
      to change the role name from                   to something else, you wouldn’t
                                            r e mo ts uC k na b
                                       WEB-TIER SECURITY                                   337


  need to change the      name in the code. However, you would need to relink
                        t s uc
  thets uc coded name to the new role name.

  Mapping Roles to J2EE Users and Groups
  When you are developing a J2EE application, you should know the roles of your
  users, but you probably won’t know exactly who the users will be. That’s taken
  care of in the J2EE security architecture, because after your component has been
  deployed, the administrator of the J2EE server will map the roles to the J2EE
  users (or groups) of the default realm. In the
                                              t nu oc c A bean example, the admin-
  istrator might assign the user Sally to the          role, and the users Bob, Ted,
                                                  r eg a na M
  and Clara to the         role.
                    r el le T
  An administrator can map roles to J2EE users and groups by using the following
  procedure in            :
                lo o ty ol p ed
      1.   Select the J2EE application.
      2.   In the Security tab, select the appropriate role from the Role Name list.
      3.   Click Add.
      4.   In the Users dialog box, select the users and groups that should belong to
           the role. (See Managing J2EE Users and Groups, page (349) for informa-
           tion about creating users and groups with                .)
                                                      l o ot yo lp e d


Web-Tier Security
  The following sections address protecting resources and authenticating users in
  the Web tier.

  Protecting Web Resources
  You can protect Web resources by specifying a security constraint. A security
  constraint determines who is authorized to access a Web resource collection,
  which is a list of URL patterns and HTTP methods that describe a set of
  resources to be protected. Security constraints can be defined using        ,
                                                                         lo ot y ol pe d
  as described in Controlling Access to Web Resources, page (338).
  If you try to access a protected Web resource as an unauthenticated user, the Web
  container will try to authenticate you. The container will only accept the request
  after you have proven your identity to the container and have been granted per-
  mission to access the resource.
338                                SECURITY



      Controlling Access to Web Resources
      Use the following procedure in   l oo ty o lp ed   to specify a security constraint to
      control access to a Web resource.
          1. Select the WAR containing the Web resource.
          2. Select the Security tab.
          3. Click the Add button in the Security Constraints section of the screen.
          4. Click the Edit button adjacent to the Web Resource Collection field to add
             a Web resource collection to the security constraint. The Web resource
             collection describes a URL pattern and HTTP method pair that refer to the
             resources that need to be protected.
          5. Click the Edit button adjacent to the Authorized Roles field to add one or
             more roles to the security constraint. You are specifying the set of roles
             that are allowed to access the Web resource collection.

      Authenticating Users of Web Resources
      When you try to access a protected Web resource, the Web container activates
      the authentication mechanism that has been configured for that resource. You
      can configure the following authentication mechanisms for a Web resource:
          • HTTP basic authentication
          • Form-based authentication
          • Client-certificate authentication

      Basic Authentication
      If you specify HTTP basic authentication, the Web server will authenticate a
      user by using the user name and password obtained from the Web client.

      Form-Based Authentication
      If you specify form-based authentication, you can customize the login screen
      and error pages that are presented to the end user by an HTTP browser.
      Neither form-based authentication nor HTTP basic authentication is particularly
      secure. In form-based authentication, the content of the user dialog box is sent as
      plain text, and the target server is not authenticated. Basic authentication sends
      user names and passwords over the Internet as text that is uuencoded, but not
      encrypted. This form of authentication, which uses Base64 encoding, can expose
      your user names and passwords unless all connections are over SSL. If someone
                                     WEB-TIER SECURITY                                 339


can intercept the transmission, the username and password information can eas-
ily be decoded.

Client-Certificate Authentication
Client-certificate authentication is a more secure method of authentication than
either basic or form-based authentication. It uses HTTP over SSL (HTTPS), in
which the server and, optionally, the client authenticate each other with Public
Key Certificates. Secure Sockets Layer (SSL) provides data encryption, server
authentication, message integrity, and optional client authentication for a TCP/IP
connection. You can think of a public key certificate as the digital equivalent of a
passport. It is issued by a trusted organization, which is called a certificate
authority (CA), and provides identification for the bearer. If you specify client-
certificate authentication, the Web server will authenticate the client using an
X.509 certificate, a public key certificate that conforms to a standard that is
defined by X.509 Public Key Infrastructure (PKI).

Configuring Web Resources’ Authentication Mechanism
To configure the authentication mechanism that the Web resources in a WAR
will use:
    1. Select the WAR containing the Web resource.
    2. Select the Security tab.
    3. Choose one of the following authentication mechanisms from the User
       Authentication Method pull-down menu:
       • None
       • Basic
       • Client-Certificate
       • Form Based
       a. If you choose form-based authentication, you must select Settings and
          fill in the Realm Name, Login Page, and Error Page fields in the Set-
          tings dialog. The error page is displayed when the user cannot be
          logged in.
       b. If you choose basic authentication, you must select Settings and enter
          t l ua fe Din the Realm name field in the settings dialog box.
340                                       SECURITY



      Using SSL to Enhance the Confidentiality of HTTP Basic and
      Form-Based Authentication
      Passwords are not protected for confidentiality with HTTP basic or form-based
      authentication. To overcome this limitation, you can run these authentication
      protocols over an SSL-protected session and ensure that all message content is
      protected for confidentiality.
      To configure HTTP basic or form-based authentication over SSL:
           1. Select the Web component. The Web Component inspector will be dis-
              played.
           2. From the Security tab, make sure that Basic or Form Based has been
              selected in the User Authentication Method pull-down menu.
           3. Click on the Add button in the Security Constraint section.
           4. Click on the security constraint that was added.
           5. Select CONFIDENTIAL in the Network Security Requirement pull-down
              menu.

      Using Programmatic Security in the Web Tier
      Programmatic security is used by security-aware applications when declarative
      security alone is not sufficient to express the security model of the application.
      Programmatic security consists of the following methods of the                 e lv r eS pt t H
                 interface:
      t se uq e Rt
                re s Ue to m eR te g •
                 e l oR nI r es Us i •
           l ap ic n ir Pr e sU te g •
      You can use the                   method to determine the user name with which
                                         re s Ue to me R te g
      the client authenticated. The
                           el o Rn Ir e sU si     method is used to determine if a user
      is in a specific security role. The
      l ap ic ni r Pr es U te g                                    method returns a
                                    object.   l a pi cn i rP .y ti r uc es .a v aj
      These APIs allow servlets to make business logic decisions based on the logical
      role of the remote user. They also allow the servlet to determine the principal
      name of the current user.

      Unprotected Web Resources
      Many applications feature unprotected Web content, which any caller can access
      without authentication. In the Web tier, unrestricted access is provided simply by
      not configuring an authentication mechanism.
                                            EJB-TIER SECURITY                                        341


EJB-Tier Security
  The following sections describe declarative and programmatic security mecha-
  nisms that can be used to protect resources in the EJB tier. The protected
  resources include methods of enterprise beans that are called from the applica-
  tion clients, Web components, or other enterprise beans.
  You can protect EJB-tier resources by doing the following:
        • Declaring method permissions
        • Mapping roles to J2EE users and groups

  Declaring Method Permissions
  After you’ve defined the roles, you can define the method permissions of an
  enterprise bean. Method permissions indicate which roles are allowed to invoke
  which methods.
  Use the following procedure in         lo ot y ol pe d   to specify method permissions by
  mapping roles to methods.
        1. Select the enterprise bean.
        2. Select the Security tab.
        3. In the Method Permissions table, select Sel Roles in the Availability col-
           umn.
        4. Then select a role’s checkbox if that role should be allowed to invoke a
           method.

  Using Programmatic Security in the EJB Tier
  Programmatic security in the EJB tier consists of the      l ap i cn ir P re ll aC t eg     and
  the                   methods. You can use the
      el o Rn Ir el l aC si                                                              method to
                                                                     la p ic ni rP r el la C te g
  determine the caller of the enterprise bean, and the                                   method to
                                                                     el oR nI r el la C si
  determine the caller’s role.
  The
   l ap ic ni r Pr el l aC te g method of the                   interface returns the
                                                           t xe t no CB JE
                                 object that identifies the caller of the enterprise
  la p ic ni rP . yt ir u ce s. av a j
  bean. (In this case, a principal is the same as a user.) In the following example,
342                                         SECURITY



        the         method of an enterprise bean returns the name of the J2EE user that
            re sU te g
        invoked it:

                                                   { ) ( re sU t eg g ni r tS c il b up
             ; )( e ma Nt e g. )( la p ic ni r Pr el la C te g. t xe tn oc nr ut er
                                                                                      }

        You can determine whether an enterprise bean’s caller belongs to a particular
        role by invoking the                method:
                                  e lo R nI re ll a Cs i

             ;) "r em o ts uC " (e lo Rn I re ll a Cs i. tx e tn oc = tl us e r na el o ob

        Unprotected EJB-Tier Resources
        By default, the J2EE SDK assigns the         role to a method. The
                                                           E NO Y NA              user,         ts eu g
        which is anonymous and unauthenticated, belongs to the         role. Therefore,
                                                                                    E NO Y NA
        if you do not map the roles, any user may invoke the methods of an enterprise
        bean.


      Application Client-Tier Security
        Authentication requirements for J2EE application clients are the same as the
        requirements for other J2EE components. Access to protected resources in either
        the EJB tier or the Web tier requires user authentication, whereas access to
        unprotected resources does not.
        An application client can use the Java Authentication and Authorization Service
        (JAAS) for authentication. JAAS implements a Java version of the standard
        Pluggable Authentication Module (PAM) framework, which permits applica-
        tions to remain independent from underlying authentication technologies. You
        can plug new or updated authentication technologies under an application with-
        out making any modifications to the application itself. Applications enable the
        authentication process by instantiating a                object, which, in turn,
                                                               tx e tn oC ni g oL
        references a configuration to determine the authentication technologies or login
        modules that will be used to perform the authentication.
        A typical login module could prompt for and verify a user name and password.
        Other modules could read and verify a voice or fingerprint sample.
        In some cases, a login module needs to communicate with the user to obtain
        authentication information. Login modules use a                 l la c .h tu a .y ti ru c es .x a va j
                                 for this purpose. Applications implement the
        r el d na Hk ca b ll aC .k c ab                                 l la C
                                                 EIS-TIER SECURITY                                         343


                 interface and pass it to the login context, which forwards it directly
   re l dn aH kc a b
   to the underlying login modules. A login module uses the callback handler both
   to gather input (such as a password or smart card PIN number) from users or to
   supply information (such as status information) to users. By allowing the appli-
   cation to specify the callback handler, an underlying login module can remain
   independent of the different ways applications interact with users.
   For example, the implementation of a callback handler for a GUI application
   might display a window to solicit user input. Or, the implementation of a call-
   back handler for a command line tool might simply prompt the user for input
   directly from the command line.
   The login module passes an array of appropriate callbacks to the callback han-
   dler’s el dn ah method (for example, a                   for the user name and a
                                                      k ca bl la C em aN
                         for the password), and the callback handler performs the
   kc a bl la C dr ow ss a P
   requested user interaction and sets appropriate values in the callbacks. For exam-
   ple, to process a                , the
                        k ca bl la C em aN                   may prompt for a name,
                                                   r el dn a Hk ca bl l aC
   retrieve the value from the user, and call the          method of the
                                                     em aN t es                             ll aC e ma N
   kc a bto store the name.

   Specifying the Application Client’s Callback
   Handler
   Use the following procedure in            lo ot y ol pe d   to specify a callback handler for an
   application client.
        1. Select the application client JAR.
        2. Select the General tab.
        3. From the CallbackHandler Class menu, select the                       class
                                                                             re ld n aH kc ab l la C
           that will be used as an interface to gather user authentication data.


EIS-Tier Security
   In the EIS tier, an application component requests a connection to an EIS
   resource. As part of this connection, the EIS may require a sign-on to the
   resource. The application component provider has two choices for the design of
   the EIS sign-on:
        • With the container-managed sign-on approach, the application component
          lets the container take the responsibility of configuring and managing the
344                                       SECURITY



             EIS sign-on. The container determines the user name and password for
             establishing a connection to an EIS instance.
           • With the component-managed sign-on approach, the application compo-
             nent code manages EIS sign-on by including code that performs the sign-
             on process to an EIS.
      The component provider can use           l o ot yo l pe d   to choose the type of sign-on.

      Configuring Sign-On
      Use the following procedure in         l oo ty ol p ed   to configure the type of sign-on.
           1.   Select the component.
           2.   Select the Resource Refs tab.
           3.   Click Add.
           4.    In the Authentication combo box, select either Container for container-
                managed sign-on or Application for component-managed sign-on.

      Container-Managed Sign-On
      With container-managed sign-on, an application component does not have to
      pass any security information for signing on to the resource to the                  c en n oC te g
      ) (n o itmethod. The security information is supplied by the container, as shown
      in the following example.

           t ne no p mo c no i ta ci l pp a na ni d o ht em s s en is uB //
                      ; )( tx e tn oC l ai ti nI we n = x tc ti n i tx et n oC

                   y ro tc af no it c en no c a n ia t bo o t p uk oo l I DN J m ro fr ep //
                                    = fx c yr o tc aF n oi tc en n oC .i c c. ec ru o se r. xa v aj
           ( pu ko o l. xt ct i ni )y r ot ca Fn o it ce n no C. ic c .e cr u os er .x a va j(
                              ; )” yr o tc aF xC e ma rf n ia M/ si e /v ne / pm oc :a v aj “

               y t ir uc es eh T . no it ce n no c a n ia tb o o t y ro tc af ek ov nI //
           d oh t em n oi t ce nn o Ct eg e h t ni de ss ap to n s i no it a mr of ni //
             ; ) ( no it ce n no Ct e g . fx c = x c n oi tc en n oC .i c c. ec ru o se r. xa v aj
                                                                                              . ..

      Component-Managed Sign-On
      With component-managed sign-on, an application component is responsible for
      passing the security information that is needed for signing on to the resource to
                                           EIS-TIER SECURITY                                     345


the                   method. Security information could be a user name and
   ) (n oi tc e nn oC t eg
password, for example, as shown in the following example.

       tn en o pm oc no it ac i lp pa n a n i d oh te M / /
    ;) (t xe t no Cl a it in I w en = x t ct in i t xe tn o C

            y r ot ca f n oi tc e nn oc a ni at b o ot p u ko ol I D NJ m r of re p / /
                              = f xc y ro t ca Fn o it ce nn o C. ic c. e cr uo s er .x av a j
    ( p uk oo l .x tc ti n i) yr o tc aF no i tc en n oC .i cc . ec ru os e r. xa v aj (
                      ;) ” yr ot c aF xC em a rf ni a M/ si e/ v ne /p mo c :a va j “

            n oi tc en n oc a ni at bo ot y ro t ca f e ko vn I / /
    . . // = se it re p or p l pm Ic ep S no it ce n no C. s ie ym .m o c

               ce pS no i tc en no C w en a te g / /
          ;) ” .. .“ (e m aN re sU t es .s e it re po r p
          ;) ” .. .“ (d r ow ss aP t es .s e it re po r p
    = xc n o it ce nn o C. ic c. e cr uo s er .x av a j
      ; ) se i tr ep or p (n oi tc e nn oC t eg .f xc
                                                    ...

Configuring Resource Adapter Security
In addition to configuring the sign-on, you must also configure the resource
adapter security. To add security to a resource adapter, complete the following
steps:
    1. Select the resource adapter RAR (Resource Adapter Archive).
    2. Select the Security tab. In the Authentication Mechanisms pane, select the
        authentication mechanisms that this resource adapter supports:
        • Password: A user and password is required to connect to an EIS.
        • Kerberos Version 5.0: The resource adapter supports the Kerberos
           authentication mechanism. See RFC-1510, The Kerberos Network
           Authentication Service (V5), for details. This specification can be
           found at                                            .
                       t x t. 01 5 1c fr /c f r/ gr o. f te i. w ww // :p t th
       You can select no mechanism, one mechanism, or multiple mechanisms.
       If you do not select a mechanism, no security authentication will be sup-
       ported.
    3. Select Reauthentication Supported if the resource adapter supports per-
       forming reauthentication on an existing physical connection. Reauthenti-
       cation will be performed when an application server calls the
346                                      SECURITY



                                  method with a security context that is different from
               )( no i tc en n oC te g
               the one that was used to establish the connection.
            4. In the Security Permissions pane, click the Add button to add a security
               permission that your resource adapter needs to access system resources in
               your operational environment. Specify only permissions that are not
               included in the default set, which are listed in Table 2 of Section 11.2 in
               the J2EE™ Connector Architecture Specification 1.0.
            5. For each security permission, click the rightmost column labeled with a
               folded paper icon to enter a description for the permission.
        To delete a security permission, select the permission in the table and click
        Delete.


      Propagating Security Identity
        When you deploy an enterprise bean or Web component, you can specify the
        security identity that will be propagated (illustrated in Figure 15–1) to enterprise
        beans invoked from within that component.




        Figure 15–1 Security Identity Propagation

        You can choose one of the following propagation styles:
            • The caller identity of the intermediate component is propagated to the tar-
              get enterprise bean. This technique is used when the target container trusts
              the intermediate container.
                                           PROPAGATING SECURITY IDENTITY                   347


      • A specific identity is propagated to the target enterprise bean. This tech-
        nique is used when the target container expects access via a specific iden-
        tity.

Configuring a Component’s Propagated Security
Identity
You use               to select the type of security identity that is propagated
             l o ot yo l pe d
from an enterprise bean or Web component.
To configure an enterprise bean or Web component to propagate the caller iden-
tity with which the component is running:
      1. Select the component.
      2. Select the Security tab.
      3. In the Security Identity pane, select the Use Caller ID radio button.
To configure a component to propagate a security identity other than that with
which the component is running:
      1. Select the component.
      2. Select the Security tab.
      3. In the Security Identity pane, select the Run As Specified Role option.
      4. Use the drop-down menu to select the role with which to run.
      5. After you select the role, you can select a user from that role. To do this,
         select Deployment Settings.
      6. From Run As Specified User, select the user name that the client will use
         to invoke the enterprise bean’s methods.
      7. Click OK.

Configuring Client Authentication
If an application component in an application client container accesses a pro-
tected method on a bean, use client authentication.
In   lo o ty ol pe d   , use the following procedure to configure client authentication:
      1. Select the target enterprise bean.
      2. Select the Security tab.
      3. Select Deployment Settings to display the Security Deployment Settings
         dialog box.
348                                  SECURITY



            4. Select the SSL Required checkbox to enable SSL.
            5. In the Client Authentication pane, select Certificate as the method by
               which the server expects the client to authenticate itself to the server.
            6. Click OK.

        Trust Between Containers
        When an enterprise bean is designed so that either the original caller identity or a
        designated identity is used to call a target bean, the target bean will receive the
        propagated identity only; it will not receive any authentication data.
        There is no way for the target container to authenticate the propagated security
        identity. However, since the security identity is used in authorization checks (for
        example, method permissions or with the                              method), it is
                                                       ) (e lo Rn I re ll a Cs i
        vitally important that the security identity be authentic. Since there is no authen-
        tication data available to authenticate the propagated identity, the target must
        trust that the calling container has propagated an authenticated security identity.
        By default, the J2EE SDK server is configured to trust identities that are propa-
        gated from different containers. Therefore, there are no special steps that you
        need to take to set up a trust relationship.


      J2EE Users, Realms, and Groups
        A J2EE user is similar to an operating system user. Typically, both types of users
        represent people. However, these two types of users are not the same. The J2EE
        authentication service has no knowledge of the user name and password you pro-
        vide when you log on to the operating system. The J2EE authentication service
        is not connected to the security mechanism of the operating system. The two
        security services manage users that belong to different realms.
        A realm is a collection of users that are controlled by the same authentication
        policy. The J2EE authentication service governs users in two realms: certificate
        and default.
        Certificates are used with the HTTPS protocol to authenticate Web browser cli-
        ents. To verify the identity of a user in the certificate realm, the authentication
        service verifies an X.509 certificate. For step-by-step instructions, see Setting
        Up a Server Certificate, page (350). The common name field of the X.509 certif-
        icate is used as the principal name.
                                      J2EE USERS, REALMS, AND GROUPS                  349


In most cases, the J2EE authentication service verifies user identity by checking
the default realm. This realm is used for the authentication of all clients except
for Web browser clients that use the HTTPS protocol and certificates.
A J2EE user of the default realm can belong to a J2EE group. (A user in the cer-
tificate realm cannot.) A J2EE group is a category of users classified by common
traits, such as job title or customer profile. For example, most customers of an e-
commerce application might belong to the                group, but the big spenders
                                               RE M OT SU C
would belong to the  D ER R EF ER Pgroup. Categorizing users into groups makes it
easier to control the access of large numbers of users. The section EJB-Tier
Security, page (341) explains how to control user access to enterprise beans.

Managing J2EE Users and Groups
This section shows how to use    lo ot y ol pe d   to do the following:
    • Display all users in the default realm
    • Add a user to the default realm
    • Add a user to the certificate realm
    • Remove a user
    • Add a group to the default realm (you cannot add a group to the certificate
      realm)
    • Remove a group from the default realm
Use the following procedure to display all users in the default or certificate
realm.
    1. Select the server to which you want to add users or groups, or both.
    2. Select Tools→Server Configuration to display the Configuration Installa-
       tion screen.
    3. Under J2EE Server in the tree view, select Users.
    4. Select the realm (Default or Certificate).
Use the following procedure to add a user to the default realm.
    1. Click Add User.
    2. Enter a user name and a password in the appropriate fields.
    3. In the Group Membership pane, select the group (from Available groups)
       to which the user you are adding will belong. To select multiple groups,
       repeat this step.
    4. Click Add to move your selection(s) to Groups.
350                                    SECURITY



            5. Click OK when done.
         Use the following procedure to add a new group to the default realm.
            1.   Click Edit Groups.
            2.   From the Groups window, click Add.
            3.   Select the line you just added and enter the name of the group to add.
            4.   Click OK when done.
         Use the following procedure to remove a group from the default realm.
            1.   Click Edit Groups.
            2.   From the Groups window, select the group to remove.
            3.   Click Delete.
            4.   Click Yes when prompted.
            5.   Click OK when done.
        Use the following procedure to add a new user to the certificate realm.
            1.   Select the Certificate realm.
            2.   Click Add User.
            3.   Select the directory where the certificate is located.
            4.   Select the certificate file name.
            5.   Click OK when done.


      Setting Up a Server Certificate
        Certificates are used with the HTTPS protocol to authenticate Web clients. The
        HTTPS service of the J2EE server will not run unless a server certificate has
        been installed. Use the following procedure to set up a J2EE server certificate.
            1. Generate a key pair and a self-signed certificate.
               The             utility enables you to create the certificate. The
                     l o ot ye k                                                  lo ot y ek
               utility that ships with the J2EE SDK has the same syntax as the one that
               ships with the J2SE software. However, the J2EE SDK version program-
               matically adds a Java Cryptographic Extension provider that has imple-
               mentations of RSA algorithms. This provider enables you to import RSA-
               signed certificates.
                                        SETTING UP A SERVER CERTIFICATE                            351


  To generate the certificate, run the         utility as follows, substituting
                                                l oo ty ek
                           with the alias of your certificate and
  > sa il a e ta c if it re c <                                                   er ot s ye k <
             with the name of your keystore file:
                 > em an el i f

   > sa il a e ta ci f it re c < sa il a AS R g la ye k ye kn e g l o ot ye k
                                       > em an e li f er o ts ye k < er ot s ye k

2. The           utility prompts you for the following information:
        l oo t ye k
   a. Keystore password: Enter a password. (You may want to use
      “           ” to be consistent with the default password of the J2EE
       ti eg na h c
      SDK keystore.)
   b. First and last name: Enter the fully qualified name of your server. This
      fully-qualified name includes the host name and the domain name.
   c. Organizational unit: Enter the appropriate value.
   d. Organization: Enter the appropriate value.
   e. City or locality: Enter the appropriate value.
   f. State or province: Enter the unabbreviated name.
   g. Two-letter country code: For the USA, the two-letter country code is
      US.
   h. Key password for alias: Do not enter a password. Press the Return key.
3. Import the certificate.
   If your certificate will be signed by a CA other than Verisign, you must
   import the CA certificate. Otherwise, you may skip this step. (Even if
   your certificate will be signed by Verisign Test CA, you must import it.)
  To import the certificate, perform these tasks:
   a. Request the CA certificate from your CA. Store the certificate in a file.
   b. To install the CA certificate in the Java 2 Platform, Standard Edition,
      run the         utility as follows. (You must have the required permis-
               lo ot ye k
      sions to modify the                                              file.)
                                  s t re ca c /y ti ru c es /b i l/ er j/ E MO H_ A VA J$

      s t re ca c ts ur t tr op mi l oo t ye k           > sa il a t re c a c < s a il a
             > e m an el if tr ec a c < el i f

4. If you want to have your certificate digitally signed by a CA, do the fol-
   lowing:
   a. Generate a Certificate Signing Request (CSR).
                                                        > e l if t r ec d en g is <
                       e li f    > s ai la tr ec < s ai la t ro p mi lo o ty ek
c. Import the signed certificate that you received in email into the server:
   send the signed certificate via e-mail. Store this certificate in a file.
                /m oc .n g is ir e v. di la t ig id / /: pt th
   Verisign CA, go to                                          . Verisign will
b. Send the contents of the       > e ma n el if r s c <
                                               for signing. If you are using
                                                      > e ma n el if rs c < e l if
  > s a il a t re c < s a il a   AS Rh ti w 5D M g la gi s qe rt r ec lo o ty ek
                                                     SECURITY                         352
                                             16
                                      Resource
                                    Connections
                                                                    Dale Green



  BOTH enterprise beans and Web components can access a wide variety of
  resources, including databases, mail sessions, Java™ Message Service objects,
  and URLs. The J2EE™ platform provides mechanisms that allow you to access
  all of these resources in a similar manner. This chapter describes how to get con-
  nections to several types of resources. Although the code samples in this chapter
  are from enterprise beans, they will also work in Web components.

  In This Chapter
            JNDI Names and Resource References 353
                deploytool Tips for Resource References 354
            Database Connections for Enterprise Beans 356
                Coded Connections 357
                Connection Pooling 359
            Mail Session Connections 359
                Running the ConfirmerEJB Example 361
            URL Connections 362
                Running the HTMLReaderEJB Example 363


JNDI Names and Resource References
  First, let’s define some terms.
                                                                                       353
354                                       RESOURCE CONNECTIONS



      JNDI is the acronym for the Java Naming and Directory Interface API. J2EE
      components locate objects by invoking the JNDI      method.     p uk o ol
      A JNDI name is a people-friendly name for an object. These names are bound to
      their objects by the naming and directory service that is provided by the J2EE
      server. Because J2EE components access this service through the JNDI API, we
      usually refer to an object’s people-friendly name as its JNDI name. The JNDI
      name of the Cloudscape database is                      . When it starts up, the
                                                      e pa cs d uo lC /c b dj
      J2EE server reads information from a configuration file and automatically adds
      JNDI database names such as                     to the name space.
                                            e pa cs d uo lC /c b dj
      A connection factory is an object that produces connection objects that enable a
      J2EE component to access a resource. The connection factory for a database is a
      j                       object, which creates a
      e cr uo S at aD .l q s. xa v a                                          object.
                                                                  n oi tc e nn oC . lq s. av a j
      A resource reference is an element in a deployment descriptor that identifies the
      component’s coded name for the resource. More specifically, the coded name
      references a connection factory for the resource. In the example in the following
      section, the resource reference name is                           .
                                                       BD t nu oc c As gn iv a S/ cb dj
      The JNDI name of a resource and the name of the resource reference are not the
      same. This approach to naming requires that you map the two names before
      deployment, but it also decouples components from resources. Because of this
      decoupling, if at a later time the component needs to access a different resource,
      you don’t have to change the name in the code. This flexibility also makes it eas-
      ier for you to assemble J2EE applications from preexisting components.

      deploytool Tips for Resource References
      The instructions that follow refer to the entity bean described in the section The
      SavingsAccountEJB Example, page (84). The
       B JE t nu oc cA s gn iv a S                                            code is in
      the                                                          directory. A sample
                     t nu oc ca s gn iv a s/ bj e/ c rs /s e lp ma xe / la ir o tu te e2 j
                                 file is in the j
      sr ae / se lp ma x e/ la ir o tu te e 2                                  directory.
                                                               ra e. p pA tn uo c cA sg ni v aS

      Specifying a Resource Reference
           1.   In             , select
                   l oo ty o lp ed                           from the tree.
                                           BJ Et n uo cc As g ni va S
           2.   Select the Resource Refs tab.
           3.   Click Add.
           4.   In the Coded Name field, enter                             .
                                                       BD t nu oc cA s gn iv a S/ cb dj
                The                        code refers to the database as follows:
                    na eB t nu oc c As gn iv a S

           ;" BD t nu oc c As gn iv a S/ cb d j/ vn e/ p mo c: a va j" = em aN b d gn ir t S et av i rp
                                         JNDI NAMES AND RESOURCE REFERENCES                        355


      The                  prefix is the name of the JNDI context for the com-
                                   v ne / pm oc :a v aj
      ponent. The
           B Dt nu oc c As gn iv a S/ cb d j  string is the JNDI name for the
      resource reference. The JNDI names for JDBC                   objects are
                                                                   e cr uo Sa t aD
      stored in the                       subcontext.
                     c bd j/ vn e /p mo c :a va j
    5. In the Type combo box, select                            .A
                                              e cr uo Sa t aD .l q s. xa va j    e cr uo S at aD
       object is a factory for database connections.
    6. In the Authentication combo box, select Container.
    7. If you want other enterprise beans to share the connections acquired from
       the              , select the Sharable checkbox.
          ec ru o Sa ta D
If the preceding steps are followed, the Resource Refs tab will appear as shown
in Figure 16–1.




Figure 16–1 Resource Refs Tabbed Pane of        BJ Et nu o cc As g ni va S

Mapping a Resource Reference to a JNDI Name
    1. Select the J2EE application from the tree.
356                                       RESOURCE CONNECTIONS



           2. Select the JNDI Names tab.
           3. In the References table, select the row containing the resource reference.
              For the
               BJ E tn uo cc A sg ni v aS        example, the resource reference is
                                        , the name you entered in the Coded Name field
                      B Dt n uo cc As g ni va S /c bd j
              of the Resource Refs tab.
           4. In the row you just selected, enter the JNDI name. For the              c As g ni va S
                         example, you would enter
               BJ E tn uo c                                           in the JNDI Name
                                                            ep a cs du o lC /c bd j
              field.
              The JNDI Names tab for                         is shown in Figure 16–2.
                                              pp A tn uo c cA sg ni v aS




        Figure 16–2 JNDI Names Tab of        p pA tn u oc cA s gn iv aS


      Database Connections for Enterprise Beans
        The persistence type of an enterprise bean determines whether or not you code
        the connection routine. You must code the connection for enterprise beans that
        access a database and do not have container-managed persistence. Such beans
                                            DATABASE CONNECTIONS FOR ENTERPRISE BEANS                        357


include entity beans with bean-managed persistence and session beans. For
entity beans with container-managed persistence,        generates the con-
                                                             l oo ty ol p ed
nection routines for you.

Coded Connections
How to Connect
The code examples in this section are from the                       n ae Bt n uo cc A sg ni va S   class,
which connects to the database via the following steps.
     1. Specify the database name.

     ; "B Dt n uo cc A sg ni va S /c bd j /v ne /p m oc :a v aj " = e ma Nb d g ni rt S e ta vi r p

     2. Obtain the    ec ru o Sa ta D   associated with the logical name.

              ; ) (t xe tn o Cl ai t in I we n = c i t xe tn o Cl ai ti n I
     ;) e ma Nb d (p uk oo l .c i ) ec ru oS a ta D( = sd e c ru oS at a D

     3. Get the   n oi tc e nn oC   from the   e cr uo S at aD   .

     = n oc n o it ce nn o C    ;) (n o it ce n no Ct eg . sd

When to Connect
When coding an enterprise bean, you must decide how long it will retain the
connection. Generally you have two choices: either hold the connection for the
lifetime of the bean, or hold it only during each database call. Your choice deter-
mines the method (or methods) in which your bean connects to a database.

Long-Term Connections
You can design an enterprise bean that holds a database connection for its entire
lifetime. Because the bean connects and disconnects just once, its code is slightly
easier to write. But there’s a trade-off—other components cannot acquire the
connection. Session and entity beans issue the lifelong connections in different
methods.
Session Beans
The EJB™ container invokes the                   method at the beginning of a ses-
                                                e t ae rC bj e
sion bean’s life cycle and invokes the               method at the end. To retain a
                                           e v om eR b je
connection for the lifetime of a session bean, you connect to the database in                       bj e
        and disconnect in
et ae r C                               . If the session bean is stateful, you must
                                 e v om eR bj e
358                                       RESOURCE CONNECTIONS



      also connect in                 and disconnect in
                          et a vi tc A bj e                            . A stateful ses-
                                                                     e ta vi ss a Pb je
      sion bean requires these additional calls because the EJB container may passi-
      vate the bean during its lifetime. During passivation, a stateful session bean is
      saved in secondary storage, but a database connection cannot be saved in this
      manner. Because a stateless session bean cannot be passivated, it does not
      require the additional calls in             and
                                              e ta v it cA bj e       . For more infor-
                                                                    e t av is s aP bj e
      mation on activation and passivation, see The Life Cycle of a Stateful Session
      Bean, page (64). For an example of a stateful session bean with a long-term con-
      nection, see the                          code in the
                                av aj . na eB re l le T                          m ax e /l ai r ot ut ee 2 j
                          directory.
      r el le t /b je /s e lp
      Entity Beans with Container-Managed Persistence
      After instantiating an entity bean and moving it to the pooled stage, the EJB con-
      tainer invokes the
                      t x et no Cy t it nE t es  method. Conversely, the EJB container
      invokes the                             method when the entity bean leaves the
                           tx e tn oC yt i tn Et e sn u
      pooled stage and becomes eligible for garbage collection. To retain a database
      connection for its entire life span, an entity bean connects in the                 n oC y ti tn E te s
      t x etmethod and disconnects in the                            method. To see a dia-
                                                     t xe t no Cy ti t nE te sn u
      gram of the life cycle, see Figure 3–5. For an example of an entity bean with a
      long-term connection, see the
      av aj . na eB tn u oc cA s gn iv aS                                  code in the
                                                           directory.
                         tn uo cc a sg ni v as /b je / se lp m ax e/ la i ro tu te e 2j

      Short-term Connections
      Briefly held connections allow many components to share the same connection.
      Because the EJB container manages a pool of database connections, enterprise
      beans can quickly obtain and release the connections. For example, a business
      method might connect to a database, insert a row, and then disconnect.
      In a session bean, a business method that connects to a database should be trans-
      actional. The transaction will help maintain data integrity.

      deploytool Tips for Specifying Database Users and Passwords
      The instructions in this section do not apply to entity beans with container-man-
      aged persistence. For those entity beans, see the instructions in Specifying the
      Database JNDI Name, User Name, and Password, page (150).
      To connect to the Cloudscape database bundled with this release, you do not
      specify a database user name and password; authentication is performed by a
      separate service. For more information about authentication, see Chapter 15.
      However, some types of databases do require a user name and password during
      connection. For these databases, if the               call has no parameters,
                                                          n oi tc e nn oC t eg
                                               MAIL SESSION CONNECTIONS                                       359


  you must specify the database user name and password with                          lo ot y ol pe d   . To
  specify these values, perform these steps:
       1. Select the enterprise bean in the tree view.
       2. Select the Resource Refs tab.
       3. Select the appropriate row in the table labeled, Resource Factories Refer-
          enced in Code, and enter the database user name and password in the fields
          at the bottom.
  If you wish to obtain the database user name and password programmatically,
  you do not need to specify them with            . In this case, you include the
                                                  l oo t yo lp ed
  database user name and password in the arguments of the                            n oi tc e nn oC t eg
  method:

       ;) dr ow s sa Pb d , re sU b d( no i tc en no C te g. ec r uo Sa t ad = n o c

  Connection Pooling
  The EJB container maintains the pool of database connections. This pool is
  transparent to the enterprise beans. When an enterprise bean requests a connec-
  tion, the container fetches one from the pool and assigns it to the bean. Because
  the time-consuming connection has already been made, the bean quickly gets a
  connection. The bean may release the connection after each database call, since
  it can rapidly get another connection. Because such a bean holds the connection
  for a short time, the same connection can be shared sequentially by many beans.


Mail Session Connections
  If you’ve ever ordered a product from a Web site, you’ve probably received an e-
  mail confirming your order. The                   class demonstrates how to send
                                           na eB r em ri fn o C
  e-mail from an enterprise bean.
  The source code for this example is in the                                ma xe / la ir o tu te e2 j
                             directory. To compile the code, go to the
  r e mr if no c /b je / cr s/ se l p
                           directory and type
    s el pm ax e /l ai r ot ut ee 2 j                    . A sample
                                        r em r if no c t na                                        no C
              file is in the j
                 ra e. p pA re mr i f                   directory.
                                           s ra e/ s el pm ax e /l ai r ot ut ee 2
  In the               method of the
           e ci to N dn es                              class, the
                                                na e Br em ri f no C       method    pu ko o l
  returns a          object, which represents a mail session. Like a database con-
             n oi ss e S
  nection, a mail session is a resource. As with any resource, you must link the
  coded name (                   ) with a JNDI name. Using the
                   no i ss eS li a Me hT                                  object as
                                                                           no is s eS
  an argument, the ec i to Nd ne smethod creates an empty             object. After
                                                                                e g as se M
                                                                                          }
                                                                                     }
                      ; )) (e g as se Mt e g. e( n oi tp ec x EB JE we n wo r ht
                                                       { ) e n oi t pe cx E( h ct ac }
                                                       ; )g sm ( dn es . tr op sn a rT
                                           ; )p ma t Se mi t( e ta Dt n eS te s. g sm
                                ; )r el ia m , "r e li aM X " (r ed a eH te s. g sm
                                              ; )t x eT eg as s em (t x eT te s. g sm
                   ;" . " + ) pm at Se m it (t a mr of .r e tt am r oF et ad
                               + " no re dr o r uo y d ev ie c er e W"
+ ' n\ ' + " .r ed r o r uo y r of u oy kn ah T " = tx eT eg a ss em gn i rt S
                                         ; ) (e ta D w en = pm at S em it e t aD
                         ; )T R OH S. ta m ro Fe t aD , GN O L. ta m ro Fe ta D
                                (e cn at s nI em i Te ta Dt e g. ta m ro Fe ta D
                                           = re t ta mr oF e ta d t am ro Fe t aD
      ;) "n a eB re mr i fn oC mo rf e g as se M t se T" ( tc ej b uS te s. g sm
               ; )) es l af , t ne ip ic e r( es r ap .s se r dd At e nr et nI
                 ,O T. e py Tt n ei pi ce R .e ga s se M( st n ei pi c eR te s. g sm
                                                            ;) (m o rF te s. g sm
                      ; )n oi s se s( eg a ss eM e mi M we n = g s m eg as s eM
                              ; )" no is s eS li a Me hT /v n e/ pm o c: av aj "
                                         ( pu ko o l. la it i ni ) n oi ss eS (
                                                         = n oi ss e s no is s eS
                      ; )( tx e tn oC la i ti nI we n = l ai ti n i tx et n oC
                                                                                 { y rt
                             { )t ne ip i ce r g ni rt S( e ci to N dn es d i ov c il b up
code for the            method follows.                               ec i to Nd n es
      method of the                                           t r op sn ar T
                             class to send the message on its way. The source             d n es
              e ci t oN dn es
calling several     methods on the        eg as se M
                                             object,              invokes thete s
                                        RESOURCE CONNECTIONS                                       360
                                          MAIL SESSION CONNECTIONS                                       361


Running the ConfirmerEJB Example
Deploying the Application
   1. In              , open the
        l o ot yo l pe d                 re mr i fn oC / sr ae /s e lp ma x e/ la ir o tu te e 2j
               file (File→Open).
                 ra e .p pA
   2. In the Resource Refs tab of the bean, specify the resource reference for the
      mail session with the values shown in Table 16–1.


Table 16–1 Resource Refs for the        B JE r em ri fn o C   Example

 Field Name            Value

 emaN dedoC            noisseSliaMehT

 epyT                  noisseS.liam.xavaj

 noitacitnehtuA        noitacilppA

 morF                  )sserdda liame ruoy(

 tsoH                  )tsoh revres liam(

 emaN resU             )eman resu swodniW ro XINU ruoy(



   3. Deploy the                        application (Tools→Deploy). In the
                       p p At nu oc c As gn i va S
      Introduction dialog box, make sure that you select the Return Client JAR
      checkbox.

Running the Client
   1. In a terminal window, go to the                                    direc-
                                                   s r ae /s e lp ma xe / la ir o tu te e2 j
      tory.
   2. Set the           environment variable to
                 HT A PC PP A                                               .
                                                               ra j. t ne il C pp Ar em r if no C
   3. Type the following command on a single line, replacing                        > tn ei p ic er <
      with the e-mail address of the person who will receive the message.

         r a e. pp A re mr if n oC t ne i lc t ne il cn u r      tn ei l Cr em ri f no C e ma n
                              > tn ei pi c er < h tu at xe t

   4. At the login prompts, enter        ts eu g     for the user name and     32 1 ts eu g    for the
      password.
362                                          RESOURCE CONNECTIONS



        Troubleshooting
        If the application cannot connect to the mail server it will generate this excep-
        tion:

             t so h P TM S o t tc e nn oc to n dl u oC : n oi tp ec x Eg ni g as se M. l ia m. xa v aj

        To fix this problem, make sure that the mail server is running and that you’ve
        entered the correct name for the mail server host in the Resource Refs tab of the
                     .
        l oo ty ol p ed


      URL Connections
        A Uniform Resource Locator (URL) specifies the location of a resource on the
        Web. The                class shows how to connect to a URL from within an
                    n ae B re da eR L MT H
        enterprise bean.
        The source code for this example is in the                              m ax e /l ai r ot ut ee 2 j
                                     directory. To compile the code, go to the
                                                  r e da er l mt h/ bj e /c rs /s e lp
        re da er l mt h t n a   directory and type              . A sample
                                                      se lp m ax e/ la i ro tu te e 2j              L MT H
                    file is in the j
          sr ae / se lp ma x e/ la i ro tu te e 2              directory.
                                                                  r ae . pp Ar ed a eR
        The                 method of the
             s t ne tn o Ct eg                               class returns a
                                                   n ae Br e da eR LM T H             that     g ni rt S
        contains the contents of an HTML file. This method looks up the                  LR U .t en .a v aj
        object associated with a coded name (            ), opens a connection to it, and
                                               LR Uy M/ l ru
        then reads its contents from an              . Before deploying the application,
                                                   m ae rt St u pn I
        you must map the coded name (               ) to a JNDI name (a URL string).
                                                    L RU yM / lr u
        Here is the source code for the             method.
                                                    st ne t no Ct eg

             no i tp ec xE e sn op s eR PT TH s wo rh t )( st n et no Ct e g r ef f uB gn i rt S c il b up
                                                                                                         {

                                      ;t x et no c t xe tn oC
                                                  ; l ru L RU
                               ; r ef fu b r ef fu B gn ir tS
                                            ; en il gn ir tS
                                    ; ed o Ce sn op s er t ni
                 ; no i tc en no c n oi t ce nn oC L RU pt tH
                                   ;t up n i ma er t St up nI
                      ; tu pn Ia t ad m a er tS tu p nI at aD

                                                                                               { y rt
                                                    ; )( t xe tn o Cl ai ti n I we n = t xe t no c
                 ; ) "L RU y M/ lr u/ v ne /p m oc :a va j "( pu k oo l. tx e tn oc ) LR U( = lr u
                                                         h tu at x et tn e il Cr e da eR LM T H
                                 e m an    ra e .p pA r ed ae RL M TH t ne i lc t ne il cn u r
                                          3. Type the following command on a single line:
       r aj .t n ei lC p pA re da e RL MT H
       .                                  2. Set the                        HT A PC PP A
                                                              environment variable to
                                             tory.
      direc-   s r ae /s e lp ma xe / la ir o tu te e2 j
                                          1. In a terminal window, go to the
                                                                             Running the Client
         box.
         tion dialog box, make sure that you select the Return Client JAR check-
      2. Deploy the                                             pp Ar ed a eR LM T H
                                     application (Tools→Deploy). In the Introduc-
                   file (File→Open).                                                   ra e .p pA
       re da e RL MT H /s ra e/ s el pm a xe /l ai r ot ut e e2 j
                          , open the                                           l oo ty o lp ed 1. In
                                                                Deploying the Application
                                   Running the HTMLReaderEJB Example
                                                                                                    }
                                                                            ; re f fu b n ru te r
                                                                                            }
                           ;) ) (e ga s se Mt eg . xe (n o it pe cx E BJ E we n w or h t
                                                           { )x e n oi tp ec x E( h c ta c }
                                                                                         }
                                                       ; ) ’n \' (d n ep pa .r e ff ub
                                                       ; ) en il (d n ep pa .r e ff ub
                   { )l lu n = ! )) ( en iL da e r. tu p nI at ad = en il ( ( el i hw
                              ; )t up n i( ma er t St up n Ia ta D w en = t u pn Ia t ad
                                   ;) ( ma er tS t up nI t eg .n oi t ce nn oc = tu p ni
                                               ; ) (r ef f uB gn ir t S we n = r ef f ub
                                                                                       { yr t
                                                                                         }
                                     ;) )e do C es no p se r( fO e ul av .g n ir tS
       + " :e d oc es no p se r P TT H" ( no it p ec xE es n op se RP T TH we n w or h t
                   { )K O_ P TT H. n oi tc en n oC LR U pt tH = ! e do Ce s no ps e r( f i
                                                                                              }
                              ;) ) (e ga s se Mt eg . xe (n o it pe cx E BJ E we n w or h t
                                                              { )x e n oi tp ec x E( h c ta c }
                         ; )( ed o Ce sn o ps eR te g .n oi t ce nn oc = ed oC e sn op s er
           ;) ( no it c en no Cn e po .l r u) no it c en no C LR Up tt H ( = no i tc en n oc
363                                           URL CONNECTIONS
364                            RESOURCE CONNECTIONS



      4. At the login prompts, enter        for the user name and
                                     t se u g                                 for the
                                                                    3 2 1t se u g
         password.
      5. The client displays the contents of the             file that resides in the
                                                 l mt h .x ed n i
                        directory of your J2EE SDK installation.
         l mt h_ c il bu p
                         17
          J2EE™ Connector
               Architecture
                                          Dale Green and Beth Stearns



T   HE other chapters in this book are intended for business application develop-
ers, but this chapter is for advanced users such as system integrators and tools
developers. The examples in this chapter demonstrate the J2EE™ Connector
architecture by accessing relational databases. However, this technology is not a
substitute for the JDBC™ API. Business application developers should continue
to use the JDBC API to access relational databases.
The J2EE Connector architecture enables J2EE components such as enterprise
beans to interact with enterprise information systems (EISs). EIS software
includes various types of systems: enterprise resource planning (ERP), main-
frame transaction processing, and non-relational databases, among others. The
J2EE Connector architecture simplifies the integration of diverse EISs. Each EIS
requires just one implementation of the J2EE Connector architecture. Because an
implementation adheres to the J2EE Connector Specification, it is portable
across all compliant J2EE servers.

In This Chapter
          About Resource Adapters 366
             Resource Adapter Contracts 366
             Administering Resource Adapters 368



                                                                                    365
366                                  J2EE™ CONNECTOR ARCHITECTURE


                  The Black Box Resource Adapters 369
                      Transaction Levels 369
                      Properties 370
                      Configuring JDBC™ Drivers 371
                  Resource Adapter Tutorial 372
                      Setting Up 372
                      Deploying the Resource Adapter 372
                      Testing the Resource Adapter 373
                  Common Client Interface 375
                      Overview of the CCI 375
                      Programming with the CCI 377
                      Writing a CCI Client 386
                      CCI Tutorial 386


      About Resource Adapters
        A resource adapter is a J2EE component that implements the J2EE Connector
        architecture for a specific EIS. It is through the resource adapter that a J2EE
        application communicates with an EIS (see Figure 17–1).
        Stored in a Resource Adapter Archive (RAR) file, a resource adapter may be
        deployed on any J2EE server, much like the EAR file of a J2EE application. A
        RAR file may be contained in an EAR file or it may exist as a separate file.
        A resource adapter is analogous to a JDBC driver. Both provide a standard API
        through which an application can access a resource that is outside the J2EE
        server. For a resource adapter, the outside resource is an EIS; for a JDBC driver,
        it is a DBMS. Resource adapters and JDBC drivers are rarely created by applica-
        tion developers. In most cases, both types of software are built by vendors who
        sell products such as tools, servers, or integration software.

        Resource Adapter Contracts
        Figure 17–1 shows the two types of contracts implemented by a resource
        adapter. The application contract defines the API through which a J2EE compo-
        nent such as an enterprise bean accesses the EIS. This API is the only view that
        the component has of the EIS. The resource adapter itself and its system con-
        tracts are transparent to the J2EE component.
        The system contracts link the resource adapter to important services—connec-
        tion, transaction, and security—that are managed by the J2EE server.
                                   ABOUT RESOURCE ADAPTERS                        367


The connection management contract supports connection pooling, a technique
that enhances application performance and scalability. Connection pooling is
transparent to the application, which simply obtains a connection to the EIS.
Because of the transaction management contract, a call to the EIS may be
enclosed in an XA transaction. XA transactions are global—they may contain
calls to multiple EISs, databases, and enterprise bean business methods.
Although often appropriate, XA transactions are not mandatory. Instead, an
application may use local transactions, which are managed by the individual
EIS, or it may use no transactions at all.
To protect the information in an EIS, the security management contract provides
these mechanisms: authentication, authorization, and secure communication
between the J2EE server and the EIS.




Figure 17–1 Accessing an EIS Through a Resource Adapter
368                                      J2EE™ CONNECTOR ARCHITECTURE



      Administering Resource Adapters
      Installing a resource adapter is a two-step process:
          1. Deploy the RAR file containing the resource adapter onto a server.
             The following command, for example, deploys a sample black box
             resource adapter onto the local host. (For Windows, in the following com-
             mands omit the backslash character, change               to             ,
                                                                      E MO H _E E2 J $   % EM O H_ EE 2J %
             and enter the entire command on a single line.)

                                      \ r ot ce n no Cy o lp ed l oo ty ol p ed
          \ ra r .x t xo b kc al b ic c/ ro t ce nn oc / bi l/ E MO H_ EE 2 J$
                                                                 ts oh la c ol

          2. Add a connection factory for the resource adapter.
             Suppose that you wanted to add a connection factory for the resource
             adapter in the                       file. The JNDI name of the connec-
                                        r ar .x t x ob k ca lb ic c
             tion factory will be                        . To override the default value
                                xT xo B kc al B ic Cy M/ s ie
             of the property named                    , you specify the URL of a data-
                                   LR U no it ce n nn oC
             base. (A property is a name-value pair used to configure a connection fac-
             tory.) To add the connection factory, you might enter the following
                         command:
             ni md ae e 2j

                                           \ y r ot ca Fr o tc en n oC dd a ni md ae e 2j
                                                        \ xT xo B kc al B ic Cy M/ s ie
                                                         \ r ar . xt x o bk ca lb i cc
                                                                            \ s po r p
          BD TC C A: 12 5 1: ts oh y m@ :n i ht :e lc a ro :c bd j =L RU n oi tc en n oC

      For the full syntax of the                and
                                              l oo t yo lp e d  commands, see
                                                                      n im da ee 2 j
      Appendix B. These commands also list and remove resource adapters and con-
      nection factories.
      To list the resource adapters that have been deployed, use the following com-
      mand:

          l oo ty ol p ed    ts o hl ac o l sr ot c en no C ts il

      To list the connection factories that have been added, use the following com-
      mand:

          ni md ae e 2j     yr o tc aF ro t ce nn o Ct si l

      To uninstall the resource adapter deployed in step 1, use the following command:
                                                THE BLACK BOX RESOURCE ADAPTERS                             369


       l o ot yo lp e d    t s oh la c ol r ar . xt x o bk ca lb i cc r o tc en no C yo lp ed n u

  To remove the connection factory added in step 2, use the following command:

       n im da ee 2 j     x T xo Bk ca l Bi cC y M/ si e y ro tc a Fr ot ce n no Ce vo m er


The Black Box Resource Adapters
  The J2EE SDK includes several black box resource adapters for performing end-
  to-end and compatibility testing. The underlying EIS of these adapters is a rela-
  tional DBMS. The client API is the JDBC 2.0 API and the                        at aD . lq s. x av aj
          interface. Underneath, the black box adapters use JDBC drivers to
  ec ru o S
  communicate with relational databases. For more information, see Configuring
  JDBC™ Drivers, page (371).

     Note: Although the black box adapters use JDBC, resource adapters are not meant
     to replace JDBC for accessing relational databases. The black box adapters are for
     testing purposes only. Because they use JDBC, they can be plugged into existing
     tests that also use JDBC.



  Transaction Levels
  The black box resource adapters reside in the                    r ot ce n no c/ b il /E MO H _E E2 J $
  (UNIX) or                                  (Windows) subdirectory. Table 17–1
                r o tc en n oc \b il \ %E MO H _E E2 J%
  lists the black box RAR files and the different transaction levels that they sup-
  port.


  Table 17–1 Black Box Transaction Levels

   File                          Transaction Level

   rar.xton xobkcalb             NOITCASNART_ON

   rar.xt xobkcalb               NOITCASNART_LACOL

   rar.ax xobkcalb               NOITCASNART_AX

   rar.xt xobkcalbicc            NOITCASNART_LACOL

   rar.ax xobkcalbicc            NOITCASNART_AX
370                                      J2EE™ CONNECTOR ARCHITECTURE



      For the                  level, the underlying JDBC driver must support the XA
              N OI T CA SN AR T _A X
      requirements as defined by the JDBC 2.0 API.

      Properties
      A resource adapter may contain properties, that is, name-value pairs containing
      information specific to the resource adapter and its underlying EIS. These prop-
      erties are defined in the deployment descriptor of each black box RAR file.
      Because the EIS of a black box adapter is a relational database, the properties
      contain information required for connecting to a database. Table 17–2 lists the
      properties of the black box adapter files. Table 17–3 shows the default values for
      the black box properties.


      Table 17–2 Black Box Properties

       File                       Property Name         Description

       rar.xton xobkcalb          LRUnoitcennoC         URL of database

       rar.xt xobkcalb            LRUnoitcennoC         URL of database

       rar.ax xobkcalb            emaNecruoSataDAX      JNDI name of    ecruoSataDAX

       rar.xt xobkcalbicc         LRUnoitcennoC         URL of database

       rar.ax xobkcalbicc         emaNecruoSataDAX      JNDI name of    ecruoSataDAX



      Table 17–3 Default Values for Black Box Properties

       Property Name            Description

       LRUnoitcennoC            eurt=etaerc;BDepacsduolC:imr:epacsduolc:cbdj

       emaNecruoSataDAX         ax_epacsduolCAX/cbdj



      To override a default property value, you set the value when adding a connection
      factory with the             command. See the section Administering Resource
                         ni md ae e 2j
      Adapters, page (368).
                                            THE BLACK BOX RESOURCE ADAPTERS                             371


Configuring JDBC™ Drivers
If you are running the black box adapters against a Cloudscape database, you
may skip this section. If you are using a database other than Cloudscape, you
should perform the steps that follow.

The Non-XA Black Box Adapters
   1. Set the JDBC driver class. Use the              tool with the
                                                        n im da e e2 j                     bd Jd d a
                option and specify the driver class name. The syntax for this
       re v ir Dc
      option is as follows:

   n im da ee 2 j     > e ma n s sa l c < r ev i rD cb dJ d da

   2. Edit the                                   (UNIX) or
                                   hs . gi fn o cr es u/ n ib                     (Win-
                                                                 t ab .g i fn oc re s u\ ni b
      dows) file, setting the
                     H TA P SS AL C _E E2 J              variable to the location of the
      JDBC driver classes.
   3. Restart the J2EE server.

The XA Black Box Adapters
   1. Set the
       e cr uo sa t aD AX   property. With the            tool and the
                                                            ni md ae e 2j                   dJ dd a
                        option, specify the JNDI name and class name for the
             ec ru o sa ta D AX cb
                     property. Optionally, you may specify the XA user name
                ec r uo sa t aD AX
       and password and you may override the default property value. The syntax
       follows:

   > em a n ss al c < > e m an i dn j < ec r uo sa ta D AX cb dJ d da n im da ee 2 j
                                   ]> d ro ws sa p a x< > e ma n r es u ax < [
                                         ] +) > e u la v < => e ma n < ( s po rp [

      The preceding command results in two data sources. One is a                     e cr uo S at aD
      object with the specified JNDI name from which the J2EE application
      gets a             instance. The other is an
              n o it ce nn o C                                     object whose
                                                                 e cr uo sa t aD AX
      JNDI name is the
                     > em an id nj <     parameter appended with two under-
      scores and     (                   ). Behind the scenes, the
                    a x_ _> e ma n id n j < ax                                        e cr uo S at aD
      uses the                to create connections.
                                  ec ru oS a ta DA X
   2. Restart the J2EE server.
372                                         J2EE™ CONNECTOR ARCHITECTURE



      Resource Adapter Tutorial
        This tutorial shows how to deploy the black box resource adapter stored in the
                           file. To test the resource adapter, you will modify the
                                                                 r ar .x t x ob kc a lb             m ax e
                                                                         file so that it
        a va j. n ae Bt n uo cc As g ni va S /t nu oc c as gn i va s/ bj e /c rs /s e lp
        accesses the Cloudscape database through the resource adapter. The                  c As g ni va S
                          file is also used in another example; see Running the Sav-
        av aj . na eB tn u oc
        ingsAccountEJB Example, page (97)

        Setting Up
             1. Start the J2EE server.

                  e e 2j     e so b re v

             2. Follow the instructions in the section, Setting Up the Database, page (97).

        Deploying the Resource Adapter
             1. Deploy a black box resource adapter that is packaged in the                   x o bk ca lb
                       file.
                 r ar .x t
                UNIX

                                               \ r ot ce n no Cy ol p ed l oo ty ol p ed
                  ts oh l ac ol ra r. xt xo bk c al b/ ro t ce nn oc / bi l/ E MO H_ EE 2 J$

                Windows (Enter the following and all subsequent Windows commands on
                a single line.)

                                                      r ot ce n no Cy ol p ed l oo ty ol p ed
                  t so hl a co l r ar .x t x ob kc a lb \r ot c en no c\ b il \% E MO H_ EE 2 J%

             2. Add a connection factory for the resource adapter. The JNDI name for the
                connection factory is                    .
                                            xT x oB kc al B yM /s i e
                UNIX

                  \ y r ot ca Fr o tc en no C dd a ni md ae e 2j
                  r ar . xt x ob k ca lb x T xo Bk c al By M/ s ie

                Windows
      e. Click OK.
         able Files field to the Contents field.
      d. Drag and drop the     ss a lc .n a eB tn uo c cA sg n iv aS
                                                      file from the Avail-
                                 ss a lc .n a eB tn uo c cA sg ni v aS /b j e/ dl iu b /s el p
                                                    file.
       ma xe / la ir o tu te e2 j
      c. In the Available Files field, locate the
      b. On the General tab of the  R AJ t nu oc cA s gn iv a S
                                                  , click Edit.
                                          file.ra e. pp A tn uo cc A sg ni v aS /s ra e /s el p
       ma xe / la ir o tu te e2 j     open the          lo ot y ol pe d
                                                        ,                    GUI      the    a. In
                                                                       r a e. pp At n uo cc A sg ni
                                                                   file.
       va S   file in the existing     ss al c .n ae Bt n uo cc A sg ni va S  5. Replace the new
                                                              tn u oc ca sg n iv as t n a
                                                                 b. Type                       .
                                                     . se l pm ax e /l ai ro t ut ee 2 j
                                                                 a. Go to
                       directory.    t nu oc ca s gn iv a s   4. Compile the source code in the
                         ; " SI Ey M /v ne /p m oc :a v aj " = e ma Nb d g ni rt S e ta vi r p
         assigned to the         variable as follows:                 em a Nb d
      3. Edit the                                  a v aj .n a eB tn uo c cA sg ni v aS
                                                  source code, changing the value
                             t nu o cc as g ni va s/ b je /c r s/ se lp m ax e/ la i ro tu t ee 2j
                                                                 directory.
      2. Locate the                             av aj .n a eB tn u oc cA sg n iv aS
                                                   source code, which resides in the
         Chapter 2.
      1. If you are new to the J2EE SDK, you should first read the instructions in
                                                    Testing the Resource Adapter
                         x T xo Bk c al By M/ s ie : e ma N ID N J yr ot c aF n o it ce nn o C
                                                 : se i ro tc af no it ce n no c d el la ts n I
                                                  r ar . xt x ob k ca lb : e ma N r ot ce nn o C
                                                              :) s (r ot ce n no c d el la ts n I
                                            utility displays these lines:      lo o ty ol pe d   The
                                          t so h la co l s ro tc e nn oC ts i l    l o ot yo lp e d
                                 3. Verify that the resource adapter has been deployed.
                                                ra r. x t xo bk c al b xT x oB kc a lB yM /s i e
                                                   yr o tc aF ro t ce nn oC d da n im da ee 2 j
373                             RESOURCE ADAPTER TUTORIAL
374                                     J2EE™ CONNECTOR ARCHITECTURE



          6. Change the resource factory reference.
             a. Select the Resource Refs tab of             B J Et nu o cc As gn i va S   .
             b. Select the item whose Coded Name entry is                 B Dt n uo cc As g ni va S /c bd j   .
             c. Click Delete.
             d. Click Add.
             e. Enter the values specified in Table 17–4.


      Table 17–4 Resource References Values

       Field                 Value

       Coded Name            SIEyM

       Type                  ecruoSataD.lqs.xavaj

       Authentication        reniatnoC

       JNDI Name             xTxoBkcalByM/sie



               The                        JNDI name matches the name of the connection
                   x Tx oB k ca lB yM / si e
               factory that you added in step 2 of Deploying the Resource
               Adapter, page (372). The          value of the Coded Name field corre-
                                                                         S IE yM
               sponds to this line in the                          source code:
                                               av aj . na eB tn u oc cA sg n iv aS

                ; "S IE y M/ vn e/ p mo c: a va j" = em aN bd gn ir t S et av i rp

               Although it is included in the source code, the                    subcon-
                                                                           / v ne /p m oc :a va j
               text is implicit in the Coded Name field of the Resource Refs tab.
          7. Save the                       application (File→Save).
                         pp A tn uo cc A sg ni va S
          8. Deploy the                       application.
                            p pA tn uo c cA sg n iv aS
             a. Select Tools→Deploy.
             b. In the Introduction dialog box, select Return Client Jar.
                                       COMMON CLIENT INTERFACE                        375


           c. In the JNDI Names dialog box, verify that the JNDI names in Table 17–
              5 have been specified.


  Table 17–5 JNDI Names

   Component or Reference Name                 JNDI Name

   BJEtnuoccAsgnivaS                           tnuoccAsgnivaSyM

   SIEyM                                       xTxoBkcalByM/sie

   tnuoccAsgnivaSelpmiS/bje                    tnuoccAsgnivaSyM



      9. To run the application, follow the directions in the section Running the
         Client, page (98).


Common Client Interface
  This section describes how components use the Connector architecture Common
  Client Interface (CCI) API and a resource adapter to access data from an EIS.

  Overview of the CCI
  Defined by the J2EE Connector Architecture specification, the CCI defines a set
  of interfaces and classes whose methods allow a client to perform typical data
  access operations. Our example             session bean includes methods that
                                    B JE e ef fo C
376                                        J2EE™ CONNECTOR ARCHITECTURE



      illustrate how to use the CCI, in particular, the following CCI interfaces and
      classes:
          •                            : Provides an application component with a
              yr ot ca F no it c en no C                                                          c en n oC
                    instance to an EIS.
                                  n oi t
          •                : Represents the connection to the underlying EIS.
              no it c en no C
          •                       : Provides a means for an application component to pass
              c ep S no it c en no C
              connection-request-specific properties to the                           when
                                                                         yr ot ca F no it c en no C
              making a connection request.
          •                  : Provides a means for an application component to execute
              n oi tc a re tn I
              EIS functions, such as database stored procedures.
          •                         : Holds properties pertaining to an application compo-
              ce pS n oi tc a re tn I
              nent’s interaction with an EIS.
          •           : The superclass for the different kinds of record instances. Record
              d ro ce R
              instances may be                         ,                  , or
                                           dr o ce Rd e xe dn I d ro ce R de pp aM           te St l us eR
              instances, which all inherit from the            interface.
                                                         d ro ce R
          •                     : Provides an application component with a
              yr o tc aF d ro ce R                                                                 dr oc e R
              instance.
          •                     : Represents an ordered collection of
                                dr o ce Rd e xe dn I                              instances
                                                                                      d ro ce R
              based on the
              t si L. l it u. av a j             interface.
      A client or application component that uses the CCI to interact with an underly-
      ing EIS does so in a prescribed manner. The component must establish a connec-
      tion to the EIS’s resource manager, and it does so using the                    .
                                                                                y ro t ca Fn oi t ce nn o C
      The                object represents the actual connection to the EIS and is used
           n oi t ce nn o C
      for subsequent interactions with the EIS.
      The component performs its interactions with the EIS, such as accessing data
      from a specific table, using an                  object. The application component
                                                                  n o it ca r et nI
      defines the                  object using an
                    n o it ca re t nI        ce pS n oi tc ar e tn I     object. When the
      application component reads data from the EIS (such as from database tables) or
      writes to those tables, it does so using a particular type of         instance, either
                                                                              dr o ce R
      a                 ,                  , or
      d ro ce R de xe d nI dr o ce Rd ep p aM                instance. Just as the
                                                                         t eS tl us e R            c en n oC
      no i tc en no Ccreates                 instances, a
                               y r ot ca Fn o it       y ro tc a Fd ro ce R creates               dr oc e R
      instances.
      Our example shows how a session bean uses a resource adapter to add and read
      records in a relational database. The example shows how to invoke stored proce-
      dures, which are business logic functions stored in a database and specific to an
      enterprise’s operation. Stored procedures consist of SQL code to perform opera-
      tions related to the business needs of an organization. They are kept in the data-
                                                 COMMON CLIENT INTERFACE                                   377


base and can be invoked when needed, just as you might invoke a Java™
method. In addition to showing how to use the CCI to invoke stored procedures,
we’ll also explain how to pass parameters to stored procedures and how to map
the parameter data types from SQL to those of the Java programming language.

Programming with the CCI
The code for the following example is in the                   i cc /r o tc en n oc /c rs / se lp m ax e
directory.
To illustrate how to use a CCI resource adapter, we’ve written a session bean and
a client of that bean. These pieces of code illustrate how clients invoke the differ-
ent CCI methods that resource adapters built on CCI might make available. Our
example uses the two sample CCI-specific resource adapters:
                        and c
ra r. x t_ xo b kc al bi c c                        .
                                      ra r. ax _ xo bk c al bi c
The               session bean is much like any other session bean. It has a home
                    ee f fo C
interface (
      e m oH ee ff o C       ), a remote interface (      ), and an implementation
                                                            ee ff o C
class (                ). To keep things simple, we’ve called the client
             B JE ee f fo C                                                             il Ce e ff oC
tne .
Let’s start with the session bean interfaces and classes. The home interface,           fo C
         , is like any other session bean home interface. It extends
e mo He e f                                                                    and          em o HB JE
defines a           method to return a reference to the
              e ta e rc                                        remote interface.
                                                                    ee f fo C
The          remote interface defines the bean’s two methods that may be called
      ee f fo C
by a client.

      )y ti tn a uq t n i ,e ma n g ni r tS (e ef f oC tr es n i di o v ci lb u p
                                               ;n o it pe cx E et om e R sw or h t
      ;n oi tp e cx Ee t om eR s w or ht )( tn uo C ee ff oC t eg t n i ci lb u p

Now let’s examine the          session bean implementation class to see how
                                B JE e ef fo C
it uses the CCI. To begin with, notice that                    imports the
                                                                        BJ Ee e ff oC
                    CCI interfaces and classes, along with the
                            e cr uo s er .x av a j
                                     and the sample
no it p ec xE ec r uo se R. e cr uo s er .x av a j                classes.
                                                                         xo bk ca l bi cc

                         ; *. ic c. e cr uo se r .x av a j tr op m i
      ; no it pe c xE ec r uo se R. e cr uo se r .x av a j tr op m i
        ;* .x ob k ca lb i cc .r ot c en no c. n us .m o c tr op m i
                    n oi t ce nn oC es ab at a D a g ni ni at b O

Prior to obtaining a database connection, the session bean does some set up work
in its                      method. (See the following code example.) Specifi-
        t x et no C no is se S te s
                                { )x e n oi tp e cx Ee cr u os eR ( h ct ac }
                              ; )c ep s( n oi tc e nn oC te g .f c = n oc                   2
          ; ) dr ow ss a p ,r e su (c ep S no it c en no Ci c C we n
                                           = ce p s ce pS n oi tc e nn oC                   1
                                                                        { yrt
                                               ; l lu n = n oc n o it ce nn o C
                           { ) (n oi tc e nn oC I CC te g n oi tc e nn oC e t av ir p
uses the CCI to establish a database connection.
method internally to establish a connection to the database. The following code
bean cannot invoke this method directly. Rather, the session bean uses this
        e ef fo C
to the underlying resource manager or database. A client of the           session
                             n oi t ce nn o CI CC te g
           uses its private method                      to establish a connection     BJ Ee ef f oC
   black box resource adapter and obtain a reference to it.
3. Use the    yr o tc aF no i tc en n oC
                    method to locate the                               pu ko ol
                                                                for the CCI
   word values.
2. Use the JNDI                        p uk o ol .t x et no Cl a it in I
                                           method to find the user and pass-
1. Establish a JNDI                  .       tx et n oC la it i nI
                                                                                    }
                                                                                }
                                             ;) (e c ar Tk ca t St ni r p. xe
                                     { )x e n oi t pe cx Eg n im aN ( h ct ac }
                                  ;) "S IE I CC /v n e/ pm oc : av aj " (
                        p uk oo l .c i )y r ot ca F no it ce n no C( = fc                   3
                              ; ) "d ro ws s ap /v n e/ pm oc : av aj " (
                                p uk oo l. c i )g n ir tS ( = d ro w ss ap
  ;) " re su / vn e/ pm o c: av a j" (p uk o ol .c i ) gn ir t S( = re su                   2
                        ; )( tx e tn oC la i ti nI we n = c i tx e tn oC