435
Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform FJ-310

FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

  • Upload
    vannhi

  • View
    220

  • Download
    2

Embed Size (px)

Citation preview

Page 1: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Developing Applications for theJ2EE™ Platform

FJ-310

Page 2: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.

This product or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or document maybe reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.

Third-party software, including font technology, is copyrighted and licensed from Sun suppliers.

Sun, Sun Microsystems, the Sun logo, Enterprise JavaBeans, EJB, J2EE, Java, Java Naming and Directory Interface, JavaServer Pages, JSP, JavaServer, JVM, and Solaris are trademarks orregistered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.

IBM and the IBM Logo are registered trademarks of IBM Corp. in the United States and other countries, and are used under license by Sun Microsystems, Inc.

U.S. Government approval might be required when exporting the product.

RESTRICTED RIGHTS: Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-14(g)(2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227-7015(b)(6/95) and DFAR 227.7202-3(a).

DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS, AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTYOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS AREHELD TO BE LEGALLY INVALID.

Page 3: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, Etats-Unis. Tous droits réservés.

Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la copie, la distribution, et la décompilation. Aucune partie de ceproduit ou document ne peut être reproduite sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de licence, s’il y en a.

Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un copyright et licencié par des fournisseurs de Sun.

Sun, Sun Microsystems, le logo Sun, Enterprise JavaBeans, EJB, J2EE, Java, Java Naming and Directory Interface, JavaServer Pages, JSP, JavaServer, JVM, et Solaris sont des marques defabrique ou des marques déposées de Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays.

IBM et le logo IBM sont des marques déposées d'IBM Corporation aux Etat-Unis et dans d'autres pays et elles sont utilisées sous licence par Sun Microsystems, Inc.

L’accord du gouvernement américain est requis avant l’exportation du produit.

LA DOCUMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENTEXCLUES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE, AL’APTITUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.

Page 4: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Developing Applications for the J2EE™ Platform i2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Course Contents

About This Course ......................................................................................... Preface-iCourse Goals .................................................................................................................................Preface-iiCourse Map ..................................................................................................................................Preface-iiiTopics Not Covered ....................................................................................................................Preface-ivHow Prepared Are You? ............................................................................................................Preface-viIntroductions ..............................................................................................................................Preface-viiIcons ........................................................................................................................................... Preface-viiiTypographical Conventions ...................................................................................................... Preface-ix

Placing the J2EE™ Model in Context ..................................................................... 1-1Objectives ................................................................................................................................................. 1-2Needs of Enterprise Applications ......................................................................................................... 1-3Java™ Technology Platforms ................................................................................................................ 1-4Enterprise Application Infrastructure Technologies ......................................................................... 1-5J2EE Technology Suite ............................................................................................................................ 1-6J2EE Specifications and the Java Community ProcessSM .................................................................. 1-7Component, API, and Service Layer .................................................................................................... 1-8J2EE Component Containers ................................................................................................................. 1-9Advantages of Using Server-Provided Services ............................................................................... 1-10J2EE Platform APIs and Services ........................................................................................................ 1-11J2EE Service Infrastructure .................................................................................................................. 1-12J2EE Platform Tiers and Architecture ................................................................................................ 1-13N-Tier Architectural Model ................................................................................................................. 1-14J2EE Tiered Architecture ...................................................................................................................... 1-15J2EE Application Architecture ............................................................................................................ 1-16J2EE Web-Centric Architecture ........................................................................................................... 1-17

Page 5: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform iiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE EJB™ Component-Centric Architecture ................................................................................... 1-18B2B Application Architecture ............................................................................................................. 1-19J2EE Web Service Architecture ........................................................................................................... 1-20J2EE Patterns .......................................................................................................................................... 1-21J2EE Pattern Tiers .................................................................................................................................. 1-22Using J2EE Patterns .............................................................................................................................. 1-23J2EE BluePrints ...................................................................................................................................... 1-24Summary ................................................................................................................................................ 1-25

J2EE Component Model and Development Steps ................................................ 2-1Objectives ................................................................................................................................................. 2-2Principles of Component-Based Development ................................................................................... 2-3J2EE Components .................................................................................................................................... 2-4J2EE Component Characteristics .......................................................................................................... 2-5Component State and Properties .......................................................................................................... 2-6Encapsulated Components .................................................................................................................... 2-7Interaction of J2EE Application Components Through Interfaces .................................................. 2-8Distributable and Local Component Interactions .............................................................................. 2-9Distributed Components and RMI ..................................................................................................... 2-10Calling Semantics for Local and Distributable Components ......................................................... 2-12Costs and Benefits of a Distributed Component Model .................................................................. 2-13Location Transparency ......................................................................................................................... 2-14Naming Services in the Component Model ...................................................................................... 2-15Use of the Java Naming and Directory Interface™ (JNDI) API in the J2EE Component

Model ................................................................................................................................................... 2-16The Context Interface and the InitialContext Object ............................................................... 2-17Configuring the InitialContext Object ......................................................................................... 2-19Using JNDI API as a Resource Locator .............................................................................................. 2-20Narrowing and Remote Objects .......................................................................................................... 2-21Asynchronous Communication Model ............................................................................................. 2-22

Page 6: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform iiiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Asynchronous Component-to-Component Interaction .................................................................. 2-23Asynchronous Messaging .................................................................................................................... 2-24Benefits and Costs of Asynchronous Interactions ............................................................................ 2-25Developing J2EE Applications ............................................................................................................ 2-26J2EE Roles ............................................................................................................................................... 2-27Steps for Developing a J2EE Application .......................................................................................... 2-29J2EE Application Development Process ............................................................................................ 2-30Comparison of Development Options ............................................................................................... 2-31Source Code Control Systems ............................................................................................................. 2-32Configuring and Packaging J2EE Applications ................................................................................ 2-33Web Application Elements .................................................................................................................. 2-35Web Archive File Creation .................................................................................................................. 2-36Java Archive Files .................................................................................................................................. 2-37EJB Component JAR File Contents ..................................................................................................... 2-38Resource Archive Files ......................................................................................................................... 2-39Enterprise Archive Files ....................................................................................................................... 2-40Deployment Descriptors ...................................................................................................................... 2-41Vendor-Specific Deployment Information ........................................................................................ 2-42Summary ................................................................................................................................................ 2-44

EJB™ Component Model ........................................................................................ 3-1Objectives ................................................................................................................................................. 3-2Role of EJB Components in a J2EE Application ................................................................................. 3-3EJB Component Types ............................................................................................................................ 3-4EJB Timer Service .................................................................................................................................... 3-5EJB Tiers ................................................................................................................................................... 3-6EJB Application Tiers ............................................................................................................................. 3-7EJB Life Cycle ........................................................................................................................................... 3-8EJB Method Types ................................................................................................................................... 3-9Important EJB Component Interfaces ................................................................................................ 3-10

Page 7: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform ivCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Analysis of the EJB Component Model ............................................................................................. 3-11Role of the EJB Container ..................................................................................................................... 3-12Home Objects as Factories ................................................................................................................... 3-14EJB Objects and Proxies ........................................................................................................................ 3-15Local and Distributed Client Views ................................................................................................... 3-16Elements of a Distributable EJB Component .................................................................................... 3-18Client View of a Distributable EJB Component ................................................................................ 3-19EJB Terminology ................................................................................................................................... 3-20Summary ................................................................................................................................................ 3-25

Developing Session Beans ..................................................................................... 4-1Objectives ................................................................................................................................................. 4-2EJB Component Types ............................................................................................................................ 4-3Class Diagram of the Session Facade Design Pattern ........................................................................ 4-4Session EJB Component Elements ........................................................................................................ 4-5Session Bean Home and Component Interfaces ................................................................................. 4-6Bean Class ................................................................................................................................................ 4-9Session EJB Component Methods ....................................................................................................... 4-10Session EJB Component Bean Class ................................................................................................... 4-11Client View of a Session Bean ............................................................................................................. 4-12Comparison of Stateless and Stateful Behavior ................................................................................ 4-13Use of Session Beans for Stateless and Stateful Business Logic ..................................................... 4-14Cardinality and Performance Characteristics of Stateless and Stateful Session Bean

Components ........................................................................................................................................ 4-15Stateless Session Bean Operational Characteristics ......................................................................... 4-16Stateless Session Bean Cardinality ..................................................................................................... 4-17Stateful Session Bean Operational Characteristics ........................................................................... 4-18Stateful Session Bean Cardinality ....................................................................................................... 4-19Stateless Session Bean Method Sequence .......................................................................................... 4-20Life Cycle of a Stateless Session Bean Instance ................................................................................. 4-21

Page 8: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform vCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Stateful Session Bean Method Sequence ............................................................................................ 4-22Life Cycle of a Stateful Session Bean Instance .................................................................................. 4-23Developer Responsibilities .................................................................................................................. 4-24Session EJB Component Deployment Descriptor ............................................................................ 4-25Session EJB Component Environment Entry .................................................................................... 4-26Creator Methods ................................................................................................................................... 4-27The SessionContext Object ............................................................................................................... 4-28Business Methods ................................................................................................................................. 4-30Passivating Stateful Session Bean Instances ...................................................................................... 4-31Activating Stateful Session Bean Instances ....................................................................................... 4-32Removing a Session Bean .................................................................................................................... 4-33Coding a Session EJB Component Client .......................................................................................... 4-34The HelloSession Session Bean ........................................................................................................ 4-35Summary ................................................................................................................................................ 4-36

Basics of Entity Beans ............................................................................................ 5-1Objectives ................................................................................................................................................. 5-2Representation of Data Using Entity EJB Components ..................................................................... 5-3Object-Oriented Data Model ................................................................................................................. 5-5Container-Managed Data Synchronization ........................................................................................ 5-6Normalized Data Mapping ................................................................................................................... 5-7Use of an Entity EJB Component Across a Set of Database Tables ................................................. 5-8Container-Managed Relationships ....................................................................................................... 5-9Concept of Primary Key ....................................................................................................................... 5-10Entity EJB Component Primary Key Association ............................................................................ 5-11Persistence Management Options ...................................................................................................... 5-12Bean-Managed Persistence .................................................................................................................. 5-13Container-Managed Persistence ......................................................................................................... 5-14CMP Entity EJB Component Persistence Configuration ................................................................. 5-15EJB QL Deployment Descriptor Entry ............................................................................................... 5-16

Page 9: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform viCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

CMP Benefits ......................................................................................................................................... 5-17Container Optimizations for CMP ..................................................................................................... 5-18Appropriateness of CMP ..................................................................................................................... 5-19Entity EJB Component Elements ........................................................................................................ 5-20Entity Bean Home and Component Interface Overview ................................................................ 5-21Entity EJB Component Home Interface ............................................................................................. 5-22Entity EJB Component Interface ......................................................................................................... 5-23Entity EJB Component Implementation Class .................................................................................. 5-24Entity EJB Component Primary Key Class ........................................................................................ 5-26Primary Key Class Deployment Descriptor Entry ........................................................................... 5-27Client View of an Entity EJB Component .......................................................................................... 5-28Cardinality of Clients and EJB Objects .............................................................................................. 5-30Entity EJB Component Cardinality .................................................................................................... 5-31Entity Bean Life Cycle With Method Calls ........................................................................................ 5-32Summary ................................................................................................................................................ 5-33

Developing CMP Entity Beans ................................................................................ 6-1Objectives ................................................................................................................................................. 6-2Implementing CMP Entity EJB Components ...................................................................................... 6-3Creating CMP Entity EJB Deployment Descriptors ........................................................................... 6-4Creating an Entity Bean ......................................................................................................................... 6-6Creator Method Sequence ...................................................................................................................... 6-7CMP Entity EJB ejbCreate and ejbPostCreate Method Implementation ................................. 6-8Finder Methods ....................................................................................................................................... 6-9Single-Object Finder Method .............................................................................................................. 6-10Multi-Object Finder Method ............................................................................................................... 6-11Finder Method Declaration and Deployment Descriptor Entry .................................................... 6-12Home Methods ...................................................................................................................................... 6-13Select Methods ....................................................................................................................................... 6-14Remove Methods .................................................................................................................................. 6-15EJB Query Language ............................................................................................................................ 6-16

Page 10: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform viiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB QL Examples .................................................................................................................................. 6-19Steps for Creating a Finder Method ................................................................................................... 6-21In-Class Activity to Create a CMP Entity Bean ................................................................................ 6-22Source Code Examples ......................................................................................................................... 6-23CMP Mapping to Database Elements With the IDE ........................................................................ 6-24In-Class Activity to Add a Finder Method ........................................................................................ 6-25Summary ................................................................................................................................................ 6-26

Assembling EJB Components Into an Application ............................................... 7-1Objectives ................................................................................................................................................. 7-2Exploiting Reusable Components ........................................................................................................ 7-3Packaging Options .................................................................................................................................. 7-4Assigning Components to Modules ..................................................................................................... 7-5Components and Modules in IDE Tools ............................................................................................. 7-7Namespace Management Problems in Complex Applications ........................................................ 7-8Local Namespaces ................................................................................................................................... 7-9Resolving Resource and EJB Component References ...................................................................... 7-10References in the Deployment Descriptors ....................................................................................... 7-11Reference Naming Conventions ......................................................................................................... 7-13Resolving References at Deployment Time ...................................................................................... 7-14Configuration Strategies ...................................................................................................................... 7-15EJB Component Environment ............................................................................................................. 7-17Capabilities of the EJB Component Environment ............................................................................ 7-18Issues With Standalone Clients ........................................................................................................... 7-19Authentication by the Application Client Container ....................................................................... 7-21Client Container Namespace ............................................................................................................... 7-22Summary ................................................................................................................................................ 7-23

Page 11: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform viiiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Developing Message-Driven Beans ....................................................................... 8-1Objectives ................................................................................................................................................. 8-2Using Enterprise Messaging .................................................................................................................. 8-3Enterprise Messaging System ............................................................................................................... 8-4Guaranteed Delivery .............................................................................................................................. 8-5Example of Messaging ........................................................................................................................... 8-6Messaging Models .................................................................................................................................. 8-7Point-to-Point and Publish and Subscribe Messaging Models ........................................................ 8-8Synchronous and Asynchronous Messaging ...................................................................................... 8-9JMS API .................................................................................................................................................. 8-10Abstraction of the Underlying Implementation ............................................................................... 8-11Message Structure ................................................................................................................................. 8-13Connection Factories ............................................................................................................................ 8-14Prerequisites for Sending a Message to a Queue ............................................................................. 8-15Process of Sending a Message to a Queue ......................................................................................... 8-16Sending a Message to a Queue ........................................................................................................... 8-17Role of Message-Driven Beans ............................................................................................................ 8-18Invalid JMS Message Consumers ....................................................................................................... 8-19Message-Driven Beans as Message Consumers ............................................................................... 8-20Client Relationship With Message-Driven Bean .............................................................................. 8-21Message-Driven Beans and J2EE Connector Architecture .............................................................. 8-22Basics of Message-Driven Beans ......................................................................................................... 8-23Instance Pooling and Statelessness ..................................................................................................... 8-24Message-Driven Bean Life Cycle ........................................................................................................ 8-26Method Sequence for Message-Driven Beans ................................................................................... 8-29Implementing Message-Driven Beans ............................................................................................... 8-30Interfaces Implemented by Message-Driven Beans ......................................................................... 8-31The ejbCreate Method ....................................................................................................................... 8-32The setMessageDrivenContext Method ........................................................................................ 8-33The onMessage Method ....................................................................................................................... 8-34

Page 12: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform ixCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The ejbRemove Method ....................................................................................................................... 8-35Message-Driven Bean Deployment Descriptor ................................................................................ 8-36Message-Driven Bean Examples ......................................................................................................... 8-37Client-Message Producer ..................................................................................................................... 8-38Message-Driven Bean Implementation Class ................................................................................... 8-39Message-Driven Bean Deployment Descriptor ................................................................................ 8-41Summary ................................................................................................................................................ 8-42

Web Component Model ........................................................................................... 9-1Objectives ................................................................................................................................................. 9-2Role of Web Components in a J2EE Application ............................................................................... 9-3HTTP Request-Response Model ........................................................................................................... 9-4The GET and POST Requests ................................................................................................................... 9-5Form Data ................................................................................................................................................. 9-6Content Type and the Response Header ............................................................................................. 9-7Comparison of Servlets and JSP™ Components ................................................................................ 9-8Life Cycle of a Web Component ........................................................................................................... 9-9The service Method ........................................................................................................................... 9-10Servlet and JSP Component Examples .............................................................................................. 9-11Servlet Example ..................................................................................................................................... 9-12JSP Component Example ..................................................................................................................... 9-13Servlet and JSP Component Collaboration ....................................................................................... 9-14Run-Time Behavior of Servlets and JSP Components ..................................................................... 9-15Web Context Root and Alias Mapping .............................................................................................. 9-16Session Management ............................................................................................................................ 9-17Web Component Thread Model ......................................................................................................... 9-18Implications for the Developer ........................................................................................................... 9-19Summary ................................................................................................................................................ 9-20

Page 13: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform xCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Developing Servlets ............................................................................................... 10-1Objectives ............................................................................................................................................... 10-2Basics of the Servlet API ....................................................................................................................... 10-3Structure of the Servlet API ................................................................................................................. 10-4Benefits of the Protocol-Specific API .................................................................................................. 10-5Benefits of the HttpServletClass ..................................................................................................... 10-6The service Method ........................................................................................................................... 10-7Request Handling Methods ................................................................................................................. 10-8Basic Servlet ........................................................................................................................................... 10-9Using the Request and Response APIs ............................................................................................ 10-10Request Object ..................................................................................................................................... 10-11Response Object .................................................................................................................................. 10-12Example of Handling Form Data and Producing Output ............................................................ 10-13Forwarding Control and Passing Data ............................................................................................ 10-14The RequestDispatcher Interface .................................................................................................. 10-15The RequestDispatcher Target and the Context Root ............................................................... 10-16The forward and include Methods ................................................................................................ 10-17Transfer of Data in the Request Object ............................................................................................ 10-18Using the Session Management API ................................................................................................ 10-19J2EE Platform Web-Tier Session Management Model .................................................................. 10-20Session and Authentication ............................................................................................................... 10-21Session Binding ................................................................................................................................... 10-22Session Timeout .................................................................................................................................. 10-23New and Timed-Out Sessions ........................................................................................................... 10-24Retrieving a Session Object ................................................................................................................ 10-25Logout and Invalidation .................................................................................................................... 10-26Calling EJB Components From Servlets .......................................................................................... 10-27Initializing a Reference to a Home Object ....................................................................................... 10-28Calling Business Methods .................................................................................................................. 10-29Summary .............................................................................................................................................. 10-30

Page 14: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Developing With JavaServer Pages™ Technology ............................................ 11-1Objectives ............................................................................................................................................... 11-2JSP Technology as a Presentation Mechanism .................................................................................. 11-3Presentation Using JSP Pages Compared to Servlets ...................................................................... 11-5JSP Page Deployment Mechanism ...................................................................................................... 11-7JSP Page Translation Procedure .......................................................................................................... 11-8Java Code Embedded in JSP Pages ..................................................................................................... 11-9Authoring JSP Pages ........................................................................................................................... 11-10JSP Page Components ........................................................................................................................ 11-11Syntactic Forms of JSP Tags ............................................................................................................... 11-12JSP Technology Directives ................................................................................................................. 11-13JSP Directives ....................................................................................................................................... 11-14The page Directive .............................................................................................................................. 11-15JSP page Directives ............................................................................................................................. 11-17The include Directive ....................................................................................................................... 11-18Declarations, Expressions, and Scriptlets ........................................................................................ 11-20Declaration Scripting Elements ......................................................................................................... 11-22Expression Scripting Elements .......................................................................................................... 11-23Scriptlet Scripting Elements .............................................................................................................. 11-24Thread-Safety Implications ................................................................................................................ 11-26Processing Data From Servlets .......................................................................................................... 11-27The jsp:useBean Action ................................................................................................................... 11-28The jsp:useBean Scopes ................................................................................................................... 11-33Request-Scope Beans and Collecting Data From Servlets ............................................................. 11-34The jsp:getProperty Action .......................................................................................................... 11-37Custom Tag Libraries ......................................................................................................................... 11-38The taglib Directive ......................................................................................................................... 11-39The tag-library Descriptor and Java Classes .............................................................................. 11-41Summary .............................................................................................................................................. 11-43

Page 15: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform xiiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Using Web-Tier Design Patterns .......................................................................... 12-1Objectives ............................................................................................................................................... 12-2Problems With Web-Tier Development ............................................................................................ 12-3Worker Beans and Custom Tags ......................................................................................................... 12-4Model 1 and Model 2 Architectures ................................................................................................... 12-5Traditional MVC Architecture ............................................................................................................ 12-6Model 2 Architecture as MVC ............................................................................................................. 12-7MVC in the J2EE Platform ................................................................................................................... 12-8Using Web-Tier Design Patterns ........................................................................................................ 12-9Service-to-Worker and Dispatcher View Patterns ......................................................................... 12-10Web-Tier Design Framework Construction .................................................................................... 12-11Some Available Web-Tier Frameworks ........................................................................................... 12-12Business Delegate Pattern .................................................................................................................. 12-13Summary .............................................................................................................................................. 12-14

Implementing a Transaction Policy ...................................................................... 13-1Objectives ............................................................................................................................................... 13-2Transaction Semantics .......................................................................................................................... 13-3Atomicity ................................................................................................................................................ 13-4Locking and Isolation ........................................................................................................................... 13-5Transaction Models ............................................................................................................................... 13-6Comparison of Programmatic and Declarative Transactions ........................................................ 13-7Using JTA to Scope Transactions Programmatically ....................................................................... 13-8Getting a Reference to the UserTransaction Interface ................................................................. 13-9Using the begin, commit, and rollback Methods ....................................................................... 13-10Effect of Programmatic Scoping on Reusability ............................................................................. 13-11Implementing a Container-Managed Transaction Policy ............................................................. 13-12How the Container Interacts With the Transaction Management Infrastructure ..................... 13-13How to Control the Container’s Behavior Using Transaction Attributes .................................. 13-14Predicting the Effect of Transaction Scope on Application Performance ................................... 13-15

Page 16: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform xiiiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Transaction Scope and Entity Bean Synchronization .................................................................... 13-16Transaction Scope and Database Concurrency .............................................................................. 13-17Effect of Exceptions on Transaction State ........................................................................................ 13-19Summary .............................................................................................................................................. 13-20

Implementing a Security Policy ............................................................................ 14-1Objectives ............................................................................................................................................... 14-2Exploiting Container-Managed Security ........................................................................................... 14-3Security Concepts .................................................................................................................................. 14-4End-to-End Security Model ................................................................................................................. 14-5Container-Managed Security .............................................................................................................. 14-6Container-Managed Authentication .................................................................................................. 14-7Authentication in the Web Tier ........................................................................................................... 14-8Web-Tier Authentication Challenge Methods .................................................................................. 14-9Basic Authentication Dialog Box ...................................................................................................... 14-10Authentication From the Web Tier to the EJB Tier ........................................................................ 14-11Authentication of Non-Web Clients ................................................................................................. 14-12Interaction With the Security Infrastructure ................................................................................... 14-14User Roles and Responsibilities ........................................................................................................ 14-15Role-Based J2EE Security Model ....................................................................................................... 14-16End-to-End Roles ................................................................................................................................ 14-17Creating a Role-Based Security Policy ............................................................................................. 14-18Role-Based Authorization in the Web Tier ..................................................................................... 14-19Role-Based Authorization in the EJB Tier ....................................................................................... 14-20Using the Security API ....................................................................................................................... 14-21Web-Tier Security API ........................................................................................................................ 14-22EJB-Tier Security API ......................................................................................................................... 14-23Configuring Authentication in the Web Tier .................................................................................. 14-24Selecting the Authentication Type ................................................................................................... 14-25Creating an HTML Login Page for Form-Based Authentication ................................................. 14-26Summary .............................................................................................................................................. 14-27

Page 17: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Preface

About This Course

Page 18: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Preface, slide ii of xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Course Goals

Upon completion of this course, you should be able to:

• Describe the application model for the J2EE™ platformand the context for the model

• Develop and test an application based on EJB™technology

• Develop a web-based user interface to an applicationbased on EJB technology

• Configure the J2EE platform services layer

Page 19: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform About This Course, iii of xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Course MapJ2EE Application Model and Its Context

Placing the J2EE™Model in Context

Developing and Testing an EJB Application

EJB Component Developing SessionBeans

Developing a Web-Based User Interface to an EJB Application

Using J2EEDevelopment Tools

Model

Developing CMP Entity

Basics of EntityBeans

Web Component Developing ServletsModel

Developing With Using Web-TierDesign PatternsJavaServer Pages™

Assembling EJBComponents Into an

Application

Developing

Configuring the J2EE Platform Services Layer

Implementing a Implementing aSecurity PolicyTransaction Policy

Message-DrivenBeans

Technology

Beans

J2EE Component Modeland Development Steps

Page 20: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Preface, slide iv of xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Topics Not Covered

• Basic Java™ programming language concepts –Covered in course SL-275: Java™ ProgrammingLanguage

• Object-oriented design and analysis concepts and UML– Covered in course OO-226: Object-Oriented Analysisand Design Using UML

• Distributed programming concepts and multi-tierarchitectures – Covered in course SL-301: DistributedProgramming With Java™ Technology

Page 21: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Preface, slide v of xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Topics Not Covered

• Advanced EJB component development, design, andimplementation – Covered in course SL-351: AdvancedBusiness Component Development With EnterpriseJavaBeans™ Technology

• Patterns for the J2EE platform – Covered in courseSL-500: J2EE™ Patterns

Page 22: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Preface, slide vi of xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

How Prepared Are You?

To be sure you are prepared to take this course, can youanswer yes to the following questions?

• Are you experienced with the Java programminglanguage?

• Are you familiar with distributed programming(multi-tier architecture)?

• Are you familiar with relational databaseprogramming?

• Are you familiar with component technology?

Page 23: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Preface, slide vii of xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Introductions

• Name• Company affiliation• Title, function, and job responsibility• Experience related to topics presented in this course• Reasons for enrolling in this course• Expectations for this course

Page 24: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Preface, slide viii of xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Icons

Additional resources

Note

Page 25: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Preface, slide ix of xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Typographical Conventions

• Courier is used for the names of commands, files,directories, programming code, programmingconstructs, and on-screen computer output.

• Courier bold is used for characters and numbersthat you type, and for each line of programming codethat is referenced in a textual description.

• Courier italics is used for variables andcommand-line placeholders that are replaced with areal name or value.

Page 26: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Preface, slide x of xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Typographical Conventions

• Courier italics bold is used to representvariables whose values are to be entered by the studentas part of an activity.

• Palatino italics is used for book titles, new words orterms, or words that are emphasized.

Page 27: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Preface, slide xi of xiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Additional Conventions

Java programming language examples use the followingadditional conventions:

• Courier is used for the class names, methods, andkeywords.

• Methods are not followed by parentheses unless aformal or actual parameter list is shown.

• Line breaks occur where there are separations,conjunctions, or white space in the code.

• If a command on the Solaris™ Operating System isdifferent from the Microsoft Windows platform, bothcommands are shown.

Page 28: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 1

Placing the J2EE™ Model in Context

Page 29: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 2 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Describe the needs of enterprise applications and howthe J2EE platform addresses these needs

• Describe the Java 2 Platform, Enterprise Edition 1.4Specification (J2EE platform 1.4) APIs and supportingservices

• Describe the J2EE platform tiers and architectures• Describe how to simplify J2EE application

development using architecture patterns

Page 30: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 3 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Needs of Enterprise Applications

The J2EE platform:

• Is an architecture for implementing enterprise-classapplications

• Uses Java and Internet technology• Has a primary goal of simplifying the development of

enterprise-class applications through an applicationmodel that is:• Vendor-neutral• Component-based

Page 31: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 4 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Java™ Technology Platforms

MicroEdition

StandardEdition

Java technology-enableddevices

Java technology-enableddesktop

EnterpriseEdition

Workgroupserver

High-endserver

Page 32: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 5 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Enterprise Application InfrastructureTechnologies

Naming service technologiesService location assistance

Messaging, connector, and related technologies

Communication with other enterprise and legacy applications

Networking and distributed object technologies

Client-tier communications

Transaction technologiesData integrity

Persistence technologiesData preservation

Multithreading technologiesMulti-user support

Security domain technologiesUser authentication

Enterprise Infrastructure Requirement

Technology or DomainSingle-UserBusiness

Application

Multi-UserEnterprise Application

+ =

Page 33: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 6 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Technology Suite

Servlets

and JSP Pages

EJB

Components

Email

JMS API

Web Services

ebXML

JAX-RPC

Connectors

JMXSpecification

DeclarativeSecurity

DeclarativeTransaction

Management

J2SE

JNDI API, RMI,COBRA, SQL, JTA

Page 34: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 7 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Specifications and the JavaCommunity ProcessSM

J2EE Platform 1.4

EJB Component

Servlet

Java Comunity Process Specfications and APIs Developers

Page 35: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 8 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Component, API, and Service Layer

Component

Layer

API

Layer

Service

Layer

Vendor-neutral

Defined by the J2EE

specification (vendor-neutral)

Vendor-specific

Databases and other

back-end services

Page 36: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 9 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Component Containers

Database

AppletContainer

Web Container

ApplicationClient

Container

EJB Container

Page 37: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 10 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Advantages of Using Server-ProvidedServices

Build From the Ground Up

Use Application Component Server

Business servicesPersistenceTransaction managementMulti-threadingSecurity managementNetworkingService publishing

Developer’s Checklist

TM

TM

Business services

Developer’s Checklist

PersistenceTransaction managementMulti-threadingSecurity managementNetworkingService publishing

Services Provided by Server

Page 38: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 11 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Platform APIs and Services

J2EE service categories:

• Deployment-based services• API-based services• Inherent services• Vendor-specific functionality

Page 39: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 12 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Service Infrastructure

HTTPSSL

HTTP Secure Sockets Layer (SSL)

Database

AppletContainer

Web Container

ApplicationClient

Container

J2SE

J2SE

J2SE

JMS

Connectors

JTA/JT

S

JDB

C

JavaMail

JAF

CO

RB

A

RM

I

JAX

-RP

C

JAX

R

JAX

P

J2SE

JMS

Connectors

JTA/JT

S

JDB

C

JavaMail

JAF

CO

RB

A

RM

I

JAX

-RP

C

JAX

R

JAX

P

EJB Container

JMS

JND

I

JDB

C

RMI/IIOP

Page 40: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 13 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Platform Tiers and Architecture

• The J2EE specification outlines an architectural modelbased on tiers which developers are encouraged to use

• The historical motivation for tiering:• Division of labor around specialized servers• Formal definitions of application responsibilities

based on the division of labor

Page 41: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 14 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

N-Tier Architectural Model

The N-tier architectural model:

• Progammatically separates application functionalityacross three or more tiers

• Has tier components and tier infrastructure that isuniquely suited to a particular task

• Has programmatic interfaces that define the tierboundaries

ClientTier

PresentationTier

BusinessTier

IntegrationTier

EIS/Data(Resource)

Tier

Page 42: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 15 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Tiered Architecture

DBMS

<%%>

<%%>

<%%>

UI

DBMS

SQLRMI/IIOP

Web Container EJB Container

Views

HTML FormWeb Browser

Controller

HTTP

Client Presentation

J2EE Application Boundary

Business Resource

BusinessServices

Entities

ClientTier

PresentationTier

BusinessTier

IntegrationTier

EIS/Data(Resource)

Tier

Page 43: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 16 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Application Architecture

• Web-centric architecture• Combined web and EJB component-based architecture,

sometimes called EJB component-centric architecture• Business-to-business (B2B) application architecture• Web service application architecture

Page 44: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 17 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Web-Centric Architecture

DBMS

<%%>

<%%>UI

DBMS

SQL

Web Container

Views

HTML Form

HTML

Client Presentation and Business Resource

Web BrowserController

<%%>

Model

BusinessServices

Entities

Page 45: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 18 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE EJB™ Component-CentricArchitecture

DBMS

<%%>

<%%>

<%%>

UI

DBMS

SQLRMI / IIOP

Web Container EJB Container

Views

HTML FormWeb Browser

Controller

HTTP

Client Presentation Business Resource

BusinessServices

Entities

Page 46: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 19 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

B2B Application Architecture

J2EE Server

J2EE Server

EIS Resources

WebContainer

EJBContainer

WebContainer

EJBContainer

Page 47: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 20 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Web Service Architecture

WSDLFile

Web Service Registry

Service Registry Entry

DescriptionInterfaceLocation

StatelessSession

Bean

J2EE Application Server

EJB Container

Port

«maps to»

Web Service Requester

Web Service Client

ServiceEndpointInterface

Page 48: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 21 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Patterns

• Patterns provide a standard solution for wellunderstood programming problems.

• J2EE pattern catalog:• Help a developer create scalable, robust,

high-performance, J2EE technology applications• Presuppose the use of the Java programming

language and the J2EE technology platform• Are, in many places, closely related to the GoF

patterns

Page 49: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 22 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Pattern Tiers

Integration Tier

Business Tier

Presentation Tier

J2EE Patterns

Architectural Principles Design Principles

Behavioral

Structural

Creational

GoF Patterns

Page 50: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 23 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Using J2EE Patterns

ServiceLocator

Controller

View

Session Facade

Session Entity DAO

Model

JSPPage

JNDIAPI

ViewHelper

Page 51: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 24 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE BluePrints

• Developed by the Java software group• Provide a set of guidelines and a sample application• Used as a reference when designing and developing a

J2EE application or J2EE application components• Known as the Java 2 Platform, Enterprise Edition

BluePrints• Available in print form and online

Page 52: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 1, slide 25 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• The requirements of an enterprise application• How J2EE technology helps an application developer

create robust and functional enterprise-scaleapplications

• The role of the container and services in the J2EEframework

• The most common J2EE application architectures• How patterns can be applied when developing a J2EE

application

Page 53: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 2

J2EE Component Model andDevelopment Steps

Page 54: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 2 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Describe the principles of a component-baseddevelopment model

• Describe the asynchronous communication model• Describe the process used and roles involved when

developing and executing a J2EE application• Compare the different methods and tools available for

developing a J2EE application and related components• Describe how to configure and package J2EE

applications

Page 55: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 3 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Principles of Component-BasedDevelopment

• The EJB specification was designed from the outset tosupport integration of components from differentvendors.

• EJB components can be authored without knowing theenvironment in which they will be used.

• Applications based on EJB components are looselycoupled:• Loosely coupled systems are easier to test and

maintain.• Components of a loosely coupled system are easier

to reuse.

Page 56: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 4 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Components

Database

AppletContainer

Web Container

ApplicationClient

Container

EJB ContainerApplet

AppClient

Servlets EJBComponents

JSPPages

Page 57: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 5 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Component Characteristics

• State and properties• Encapsulation by a container• Strict separation of interface from implementation• Support for local and distributable component

interactions• Location transparency• Component references obtained using a naming

system

Page 58: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 6 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Component State and Properties

• State is associated data that has to be maintained acrossa series of method calls• A component might or might not be stateful• Stateless components might have performance

advantages over stateful components• A property is a component feature that can be either

read and written or read or written by its clients• A property might be represented internally by an

instance variable• Properties are modeled as accessor and mutator

method pairs

Page 59: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 7 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Encapsulated Components

• Encapsulation is an important concept inobject-oriented programming

• J2EE encapsulates components in containers that:• Provide life-cycle management• Isolate components from other components• Isolate components from the runtime environment

Page 60: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 8 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Interaction of J2EE ApplicationComponents Through Interfaces

Interface1 Interface2

Implementation2Implementation1

Page 61: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 9 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Distributable and Local ComponentInteractions

The developer specifies whether an interaction is to be local ordistributable.

• Local – The application server makes componentsavailable to each other in the same JVM™.

• Distributable – The application server provides an RMIinfrastructure by which components communicate.

Both strategies have associated costs and benefits.

Page 62: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 10 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Distributed Components and RMI

Interface2 Interface2

Component1

Component2

Stub Skeleton

Page 63: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 11 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Distributed Components and RMI

The RMI infrastructure must be able to manage the followingdesign issues:

• Marshalling and unmarshalling of arguments andreturn values

• Passing distributed exceptions• Passing security context and transaction context

Page 64: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 12 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Calling Semantics for Local andDistributable Components

Local and distributable component interactions followdifferent calling conventions.

Arguments that are themselves distributable components arean exception to these rules. These arguments are passed byreference.

Local Components Distributable Components

Passingarguments

Arguments are passed inshared memory.

Arguments are passed byvalue.

Modifying thecaller’sinstance

The target component canmodify the caller’s instance.

The target component cannotmodify the caller’s instance.

Page 65: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 13 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Costs and Benefits of a DistributedComponent Model

The following benefits derive from location transparency:

• Increased fault tolerance• Improved load sharing between hosts

The following costs derive from RMI overheads:

• Data marshalling overheads• Network latency• More complex exception handling

Page 66: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 14 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Location Transparency

Location transparency is a design goal of the distributedcomponent model in the J2EE platform:

• The calling component is not concerned with thephysical location of the target component.

• A component can be deployed in more than one host,which has these benefits:• Load balancing• Fault tolerance

• The application server vendor is responsible forrealizing these benefits.

• The developer is responsible for developingspecification-compliant components.

Page 67: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 15 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Naming Services in the Component Model

Interface2

Interface2

Component1

Component2

NamingService

2

1

3

Publish

Lookup

Page 68: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 16 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Use of the Java Naming and DirectoryInterface™ (JNDI) API in the J2EE

Component Model

In the J2EE platform environment, the JNDI API:

• Implements a general lookup service for:• J2EE components• External resources• Component environment

• Abstracts the underlying naming protocols andimplementation:• CORBA naming service• LDAP• Vendor-specific protocols

Page 69: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 17 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The Context Interface and theInitialContextObject

The Context interface is the basis for all naming operations.

• The InitialContext object is a specificimplementation of the Context interface.

• AnInitialContext object represents the entry pointto the naming service.

• The namespace can be hierarchical.• A lookup operation on a Context object results either

in an object or in a subcontext.

Page 70: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 18 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The Context Interface and theInitialContextObject

A subcontext also implements the Context interface. Thefollowing two code snippets have the same effect:

Context c = new InitialContext();Object o = c.lookup(“aaa/bbb”);

Or

Context c = new InitialContext();Context subcontext = (Context) c.lookup(“aaa”);Object o = subcontext.lookup(“bbb”);

Page 71: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 19 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Configuring the InitialContextObject

Configuration of the InitialContext object differs within aJ2EE component and in a standalone application:

• Within a J2EE component, the container providesconfiguration to the InitialContext object:Context c = new InitialContext();

• In a standalone application, the InitialContextobject must be configured:Hashtable env = new Hashtable();env.put (“java.naming.factory.Initial”,“com.sun.jndi.cosnaming.CNCtxFactory”);

env.put(“java.naming.provider.url”, “iiop://hostname:3700”);Context c = new InitialContext(env);

Page 72: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 20 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Using JNDI API as a Resource Locator

In addition to components, JNDI API calls can locate:

• Connections to relational databases• Connections to messaging services• Message destinations• Component environment variables• Connections to legacy systems that are supported by

resource adapters

Page 73: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 21 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Narrowing and Remote Objects

JNDI lookup results differ for non-remote and remote objects:

• For non-remote objects, the result of a lookup is cast tothe appropriate type:Context c = new InitialContext();DataSource ds = (DataSource)c.lookup(“jdbc/bank”);

• For remote objects, the result of a lookup must benarrowed to the appropriate type:Context c = new InitialContext();Object o = c.lookup(“ejb/BankMgr”);BankMgrHome home = (BankMgrHome)

javax.rmi.PortableRemoteObject.narrow(o, BankMgrHome.class);

Page 74: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 22 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Asynchronous Communication Model

Synchronous Asynchronous

Semantics Request-response Request-notification

Blocking Client blocks until operationcompletes

Client does not block

Response Client gets a direct response Client gets a deferred response

Page 75: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 23 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Asynchronous Component-to-ComponentInteraction

2

3

4

1

Place Order

Notify OrderStatus

Legacy BatchOrdering System

Update OrderStatus

Check OrderStatus

Page 76: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 24 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Asynchronous Messaging

The application server must provide a messaging service tosupport asynchronous component interaction.

• With the J2EE platform 1.4, the server must provideinfrastructure for web services XML messaging.

• Components use the JMS API to send messages to othercomponents or to external resources.

• Message-driven beans act as consumers of messages.

Page 77: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 25 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Benefits and Costs of AsynchronousInteractions

Asynchronous component interaction results in both benefitsand costs, compared to synchronous component interaction.

• Benefits:• Reduced coupling between components, which

results in reduced long-term costs of softwaremanagement

• Accommodation of operations that take an extendedtime to complete

• Costs:• Requires a more complex infrastructure• Is usually less efficient in network resource usage

Page 78: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 26 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Developing J2EE Applications

• Performed by a group of people• Involves separate roles and responsibilities

Page 79: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 27 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Roles

Roles related to application development:

• Application component provider• Application assembler• Deployer

Other defined roles:

• System administrator• Tool provider• Product provider

Page 80: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 28 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Roles

Important role distinctions:

• Distinction between tool provider and productprovider

• Distinction between component provider, applicationassembler, and deployer

Page 81: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 29 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Steps for Developing a J2EE Application

• Designing• Coding• Creating deployment descriptors• Packaging• Assembly• Deployment

Page 82: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 30 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Application Development Process

<ejb-

TM

TM

TM

ApplicationComponent Provider

ApplicationAssembler

Assemble- Client Module- EJB Component Module- Web Module- Resource Module

ApplicationComponents

TM

Deployer DeploymentTool

Applications

ApplicationServer

WAR

RAR JAR EAR

Page 83: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 31 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Comparison of Development Options

• Packaging tools• Makefiles• Apache ANT• IDE features:

• Serve as an editor• Manage components graphically• Compile• Debug• Edit deployment descriptors graphically• Deploy to one or more application servers

Page 84: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 32 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Source Code Control Systems

TMTM TM

Editing EJB2Editing EJB1

EJB1EJB2EJB3

Source Control System

Checked Out:EJB1EJB2

Viewing EJB1(not editing)

Page 85: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 33 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Configuring and Packaging J2EEApplications

• Developers package individual components intoarchive files. These archive files contain:• Relevant class files• XML deployment descriptors

• These archive files are packaged into a super archive toform a complete application.

• The contents and structure of these archive files aremandated by the J2EE specification.

• Any compliant application server should be able toaccept any compliant application.

Page 86: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 34 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Configuring and Packaging J2EEApplications

There are four basic types of archive files used in a J2EEdevelopment project:

• WAR files• JAR files• RAR files• EAR files

Page 87: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 35 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Web Application Elements

Web Container

Web Application

Servlet

<XML>

</XML>

<%

%>

<HTML>

</HTML>

Deployment DescriptorStatic Content

Dynamic Content

Controllers

Tag Libraries

Auxiliary Classes

Page 88: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 36 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Web Archive File Creation

/

Static Content

web.xml

Dynamic Content myWebApp.war

WEB-INF/

classes/

lib/

jar cvf myWebApp.war

Page 89: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 37 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Java Archive Files

Java Archive files:

• Provide a standard mechanism for packaging anddistributing Java class files and related resources

• Normally given names that end in .jar

• Are defined by the J2EE specification as the packagingformat for EJB components and J2EE clients

Page 90: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 38 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Component JAR File Contents

DeploymentDescriptor

HelperClassesInterfaces

BeanImplementation

Class

XML

Page 91: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 39 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Resource Archive Files

A resource adapter:

• Is a software component that has hooks into acontainer’s transaction management, security, andresource pooling subsystems

• Can request extended access to the system, beyondwhat would be allowed to an enterprise bean

• Can make native calls, create or open network socketsthat listen, create and delete threads, and read andwrite files

• Is packaged into RAR files that have names that end in.rar

Page 92: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 40 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Enterprise Archive Files

Helper ClassesJAR File

RARFile

XML

DeploymentDescriptor

EJBComponent

JAR

WARFile

EJBComponent

JAR

Page 93: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 41 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Deployment Descriptors

Deployment descriptors:

• Are XML formatted files• Provide a declarative way to describe the interactions

between components and between a component and itscontainer

• Have their format, naming convention, and otherattributes defined in the relevant componentspecification

Page 94: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 42 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Vendor-Specific Deployment Information

Sun™ ONE Application Server deployment descriptor:

1 <?xml version="1.0" encoding="UTF-8"?>2 <sun-ejb-jar>3 <enterprise-beans>4 <ejb>5 <ejb-name>BankMgr</ejb-name>6 <jndi-name>ejb/BankMgr</jndi-name>7 <pass-by-reference>false</pass-by-reference>8 <principal> <name></name> </principal>9 <ior-security-config>10 <transport-config>11 <integrity>NONE</integrity>12 <confidentiality>NONE</confidentiality>13 <establish-trust-in-target>NONE14 </establish-trust-in-target>15 <establish-trust-in-client>SUPPORTED16 </establish-trust-in-client>17 </transport-config>

Page 95: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 43 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Vendor-Specific Deployment Information

18 <as-context>19 <auth-method>USERNAME_PASSWORD</auth-method>20 <realm>default</realm>21 <required>false</required>22 </as-context>23 <sas-context>24 <caller-propagation>SUPPORTED</caller-propagation>25 </sas-context>26 </ior-security-config>27 <bean-pool>28 <steady-pool-size>32</steady-pool-size>29 <resize-quantity>16</resize-quantity>30 <max-pool-size>640</max-pool-size>31 <pool-idle-timeout-in-seconds>60032 </pool-idle-timeout-in-seconds>33 <max-wait-time-in-millis>0</max-wait-time-in-millis>34 </bean-pool>35 </ejb>36 </enterprise-beans>37 </sun-ejb-jar>

Page 96: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 2, slide 44 of 44Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• The principles of component-based development• The characteristics of asynchronous communication• The roles and development steps involved to create a

J2EE technology application• How J2EE components are packaged and assembled• The tools and techniques available for creating a J2EE

technology application

Page 97: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 3

EJB™ Component Model

Page 98: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 2 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Describe the role of EJB components in a J2EEapplication

• Describe the EJB component model• Identify the proper terminology to use when

discussing EJB components and their elements

Page 99: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 3 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Role of EJB Components in a J2EEApplication

EJB components:

• Are managed by the EJB container• Provide business and data access functions• Are scalable, transactional, and multi-user secure

Page 100: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 4 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Component Types

Enterprise JavaBeansTechnology

Session Entity Message-Driven

Stateless

Stateful

Bean-Managed

Persistence (BMP)

Container-Managed

Persistence (CMP)

Page 101: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 5 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Timer Service

• Is new as of the J2EE platform 1.4• Is a container-managed service• Provides a callback service for modeling

workflow-type business processes that depend onnotifications that certain time-related events haveoccurred

• Can be configured to occur:• At a specific time• After a specific elapsed duration• At specific recurring intervals

Page 102: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 6 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Tiers

Modern practice favors the division of EJB components intotiers:

• The services tier, which consists mostly of sessionbeans and message-driven beans

• The EIS-facing or object-relational mapping tier, whichconsists mostly of entity beans and their supportingclasses

Page 103: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 7 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Application Tiers

Session Bean

Entity Beans

Database

AutomaticTeller

BranchTeller

TransactionLog

Customer

Account

ATMCustomer

Ledger

Client

Client

Client

Client

Session Bean

Page 104: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 8 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Life Cycle

• An EJB component has a life cycle that is controlled bythe EJB container based on the functionality requestedby the client and the operational requirements of thesystem.

• Each type of EJB component has specific life-cycleoperations and characteristics.

• Understanding the life cycle of the various EJBcomponent types might allow a component developerto optimize the operation of the bean.

Page 105: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 9 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Method Types

There are two basic categories of methods that are common toboth session and entity EJB components:

• Life-cycle or callback methods• Business or data access methods

Page 106: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 10 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Important EJB Component Interfaces

The EJB component model provides some basic functionalityusing a few base interfaces common to all EJB componenttypes. These interfaces include:

• The EJBContext interface• The EnterpriseBean interface• The Handle interface

Page 107: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 11 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Analysis of the EJB Component Model

The EJB component model has the following characteristics:

• A container encapsulates each component.• The container provides proxies that allow clients

limited and controlled access to the EJB component.• The proxies implement interfaces that are provided by

the EJB component developer.• Clients make method calls on these interfaces.

Page 108: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 12 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Role of the EJB Container

Container

Life-Cycle Management

Resource ManagementC

lient

Sup

port

Page 109: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 13 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Role of the EJB Container

The EJB container provides the following functionality:

• Encapsulates access to external resources such asdatabases and legacy systems

• Manages the life cycles of instances of the EJBcomponent’s implementation class

• Isolates the class that provides the implementationfrom its clients

• Provides timer services, and can invoke methods atcertain times, which allows the EJB component toperform scheduled tasks

• Monitors, for message-driven beans, a message queueon behalf of the EJB component

Page 110: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 14 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Home Objects as Factories

create() HomeObject

New

Page 111: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 15 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Objects and Proxies

BusinessMethods

HomeObject

New

EJBObject

Page 112: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 16 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Local and Distributed Client Views

The home interface and component interface serve thefollowing three purposes:

• They provide an access point for clients• They specify to the server how to construct the home

object and EJB object• They serve as a framework for the behavior of the EJB

component

Page 113: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 17 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Local and Distributed Client Views

You can provide an EJB component with in any combinationof the following three types of home and componentinterfaces:

• Local interfaces• Distributed interfaces• Web services interfaces

Page 114: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 18 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Elements of a Distributable EJBComponent

A distributable, remotely accessible EJB component has thefollowing elements:

• Remote home interface• Remote component interface• Implementation class

Page 115: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 19 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Client View of a Distributable EJBComponent

// BankMgrHome is the home interface for EJB ‘BankMgr’// BankMgr is the component interface

BankMgrHome home = //.. get home object

// Request home object to create an instance of BankMgrBankMgr bankMgr = home.create();

// Call business methods on the instanceCustomerData cd = bankMgr.getCustomerData(“fred”);

// Tell container that instance is no longer requiredbankMgr.remove();

Page 116: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 20 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Terminology

The following table lists the various names used for the EJBcomponent elements for version 1.1 of the EJB specification.

Term Description

Remote client view Includes both the home and remote interface

Home interface Extends the EJBHome interface and provides a homeobject

Remote interface Extends the EJBObject interface and provides an EJBobject

Page 117: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 21 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Terminology

The following table lists the various names used for the EJBcomponent elements for version 2.0 of the EJB specification.

Term Description

Remote client view Includes both the remote home interface and the remoteinterface

Local client view Includes both the local home interface and the localinterface

Home interface Generic term for the factory interface for an EJBcomponent regardless of it being local or remote

Local homeinterface

Extends EJBLocalHome and provides a local home objectRemote home interface

Remote homeinterface

Extends EJBHome interface and provides a remote homeobject

Page 118: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 22 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Terminology

Term Description

Remote interface Extends the EJBObject interface and provides an EJBobject

Local interface Extends the EJBLocalObject interface and provides alocal object

Page 119: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 23 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Terminology

The following table lists the various names used for the EJBcomponent elements for version 2.1 of the EJB specification.

Term Description

Remote client view Includes both the remote home interface and the remotecomponent interface

Local client view Includes both the local home interface and the localcomponent interface

Home interface Generic term for the factory interface for an EJBcomponent regardless of it being local or remote

Local homeinterface

Extends the EJBLocalHome interface and provides a localhome object

Remote homeinterface

Extends the EJBHome interface and provides a remotehome object

Page 120: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 24 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Terminology

Term Description

Component interface Generic term for the business method interface regardlessof it being local or remote

Local componentinterface

Extends the EJBLocalObject interface and provides alocal EJB object

Remotecomponentinterface

Extends the EJBObject interface and provides a remoteEJB object

Page 121: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 3, slide 25 of 25Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• The role of EJB components in a J2EE application• The three main EJB component types• The two major EJB tiers that are typically found in the

EJB layer of a J2EE application• The two general classifications of methods found on an

EJB component• The characteristics of the EJB component model• The terminology used to describe the elements of an

EJB component

Page 122: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 4

Developing Session Beans

Page 123: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 2 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Describe the role of session beans• Describe the function and operational characteristics of

stateless and stateful session EJB components• Describe the life cycle of session EJB components• Implement a session bean

Page 124: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 3 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Component Types

Enterprise JavaBeans

Technology

Session Entity Message-Driven

Stateless

Stateful

Bean-Managed

Persistence (BMP)

Container-Managed

Persistence (CMP)

Page 125: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 4 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Class Diagram of the Session FacadeDesign Pattern

Client

<<EJBSession>>

SessionFacade

<<EntityEJB>>

BusinessEntity

BusinessObject

DataAccessObject

<<SessionEJB>>

BusinessSession

Accesses

Accesses Accesses

1..*

Page 126: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 5 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session EJB Component Elements

Java Virtual Machine

BankingBean

BankingHome

Home interface

Banking

Component interface

Bus methods

Creator method(s)

Life-cycle methods

(Local, Remote, or Both)

(Local, Remote, or Both)

DeploymentDescriptor

Component Properties

Component References

Environment Entries

Page 127: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 6 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session Bean Home and ComponentInterfaces

• Home and component interfaces define thefunctionality exposed by a session EJB component.

• Home and component interfaces define therequirements for the server generated and EJBHomeand EJBObject implementations.

• Client uses interfaces to interact with the EJBcomponent instance.

• Remote client uses a stub to interact with remoteimplementations of the home and componentinterfaces.

Page 128: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 7 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session Bean Home and ComponentInterfaces

A session EJB component’s home interface has the followingcharacteristics:

• The home interface is implemented on the server sideby a home object.

• The local and remote home interfaces extendjavax.EJBLocalHome and javax.ejb.EJBHomerespectively.

1 import javax.ejb.*;2 public interface HelloSessionHome extends javax.ejb.EJBHome {3 public HelloSession create()4 throws javax.ejb.CreateException, java.rmi.RemoteException;5 }

Page 129: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 8 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session Bean Home and ComponentInterfaces

A session EJB component’s interface has the followingcharacteristics:

• Provides access to the component’s business methods.• The home interface is implemented on the server side

by an EJB object or component object.• The local and remote home interfaces extend

javax.EJBLocalObject and javax.ejb.EJBObjectrespectively.

1 import javax.ejb.*;2 public interface HelloSession extends javax.ejb.EJBObject {3 public java.lang.String hello() throws java.rmi.RemoteException;4 }

Page 130: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 9 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Bean Class

A session EJB component’s class has the followingcharacteristics:

• Implements javax.ejb.SessionBean• Often referred to as the bean class, implementation

instance, or EJB class• Contains code that implements the functionality

provided by the component’s business and life-cyclemethods

Page 131: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 10 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session EJB Component Methods

Called by client Called by container

Method Type

Factory

Infrastructure

Business

Infrastructure

Infrastructure

Factory

Bean ClassComponent Interface

HomeInterface

ejbCreate

setSessionContext

<businessMethods>

ejbPassivate

ejbActivate

ejbRemove

<businessMethods>

remove

create

remove

Page 132: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 11 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session EJB Component Bean Class

1 import javax.ejb.*;2 public class HelloSessionBean implementsjavax.ejb.SessionBean {3 public void setSessionContext (SessionContext aContext){}4 public void ejbActivate() {}5 public void ejbPassivate() {}6 public void ejbRemove() {}7 public void ejbCreate() {}8 public java.lang.String hello() { return "Hello World!";}9 }

Page 133: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 12 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Client View of a Session Bean

BankingHome home = look up home object

Create bean

Call business methods

Remove bean

Lookup home

banking.remove();

banking.withdrawal(accountNum, amount);

banking.deposit(accountNum, amount);

Banking banking = home.create();

Page 134: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 13 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Comparison of Stateless and StatefulBehavior

Each type of session bean, stateless or stateful, is used for aspecific type of business function:

• In a stateless client-service interaction, noclient-specific information is maintained beyond theduration of a single method invocation.

• Stateful services require that information obtainedduring one method invocation be available duringsubsequent method calls:• Shopping Carts• Multi-page data entry• Online banking

Page 135: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 14 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Use of Session Beans for Stateless andStateful Business Logic

The component developer configures a session bean’sstatefulness using a property contained in a session bean’sdeployment descriptor.

Configuring the type property of session EJB component:

1 <enterprise-beans>2 <session>3 ...4 <session-type>Stateless</session-type>5 ...6 </session>7 </enterprise-beans>

Page 136: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 15 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Cardinality and PerformanceCharacteristics of Stateless and Stateful

Session Bean Components

• The container is responsible for creating an appropriatenumber of EJB objects, home objects, and instances ofthe bean class to satisfy clients.

• These cardinalities are different for stateless andstateful session beans.

Page 137: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 16 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Stateless Session Bean OperationalCharacteristics

With stateless session beans:

• The bean does not retain client-specific information.• A client might not get the same session bean instance.• Any number of client requests can be handled by the

same session bean instance. This has profoundperformance advantages.

Page 138: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 17 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Stateless Session Bean Cardinality

EJB object

Pool of EJBinstances

Home objectClient

Client

Client

Banking

BankingBean

BankingBean

BankingHome

Page 139: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 18 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Stateful Session Bean OperationalCharacteristics

With stateful session beans:

• The bean belongs to a particular client for an entireconversation.

• The client connection exists until the client removes thebean or the session times out.

• The container maintains a separate EJB object and EJBinstance for each client.

Page 140: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 19 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Stateful Session Bean Cardinality

EJB home

EJB instancesEJB objects

Client

Client

Client

Banking

Banking

Banking

BankingBean

BankingBean

BankingBean

BankingHome

Page 141: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 20 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Stateless Session Bean Method Sequence

: Client

: BankingHome

: Banking

: BankingBean

create

new

new

setSessionContext(sc)

ejbCreate

withdrawal

withdrawal

prepare

remove

Page 142: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 21 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Life Cycle of a Stateless Session BeanInstance

Does notexist

Method-readypool

1. newInstance()

2. setSessionContext(sc)

3. ejbCreate()

ejbRemove()

ejbTimeout(arg)method

method()

ejbCreate()

Action initiated by client

Action initiated by container

Page 143: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 22 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Stateful Session Bean Method Sequence

create(...)

: Client : BankingHome

: Banking

: BankingBeannew

new

setSessionContext(sc)

ejbCreate(...)

withdrawal

withdrawal

prepare

ejbActivate

ejbPassivate

ejbRemoveremove

Page 144: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 23 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Life Cycle of a Stateful Session BeanInstance

Does notexist

Methodready

Methodready in TX

Passive

Chosen asleast recently used (LRU)

Victim

ejbPassivate()

ejbActivate()

afterCompletion(false)1. beforeCompletion()2. afterCompletion(true)

1. newInstance()2. setSessionContext(sc)3. ejbCreateNAME(args)

afterBegin()

ejbRemove()

remove()or timeout

������

�����������

� ��� �� ������� � �� �������� ������

�� ������

� ��� ������

createNAME(args)

create()newInstance

Action initiated by clientAction initiated by container

ERROR

Timeout

Instance throws systemexception from any method

Only applicable if

component implements

SessionSynchronization interface

Page 145: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 24 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Developer Responsibilities

A session EJB component developer must provide:

• Bean class• Corresponding home interface (local, remote, or both)• Corresponding component interface (local, remote, or

both)• Deployment descriptor

Page 146: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 25 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session EJB Component DeploymentDescriptor

1 <?xml version="1.0" encoding="UTF-8"?>2 <ejb-jar>3 <enterprise-beans>4 <session>5 <display-name>HelloSession</display-name>6 <ejb-name>HelloSession</ejb-name>7 <home>HelloSessionHome</home>8 <remote>HelloSession</remote>9 <ejb-class>HelloSessionBean</ejb-class>10 <session-type>Stateless</session-type>11 <transaction-type>Container</transaction-type>12 </session>13 </enterprise-beans>14 </ejb-jar>

Page 147: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 26 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session EJB Component EnvironmentEntry

1 <?xml version="1.0" encoding="UTF-8"?>2 <ejb-jar>3 <enterprise-beans>4 <session>5 ...6 <env-entry>7 <description>8 Largest single deposit or withdrawal9 </description>10 <env-entry-name>transactionLimit</env-entry-name>11 <env-entry-type>java.lang.Double</env-entry-type>12 <env-entry-value>300.0</env-entry-value>13 </env-entry>14 </session>15 </enterprise-beans>16 </ejb-jar>

Page 148: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 27 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Creator Methods

• Method signatures on create and correspondingejbCreate methods must match.

• Stateless session EJB components only have oneparameterless creator method.

EJB object

Home object

Client

BankingBean

EJB instance

Banking

ejbCreatecreateBankingHome

2

3

4

1

Page 149: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 28 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The SessionContextObject

Use the SessionContext object to access home and EJBobjects, obtain current transaction status, and obtain securityinformation.

1 import javax.ejb.*;23 public class BankingBean implements javax.ejb.SessionBean {45 private javax.ejb.SessionContext context;67 public void setSessionContext (javax.ejb.SessionContext aContext){8 context=aContext;9 }10 ...11 }

Page 150: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 29 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The SessionContextObject

setSessionContext

Home object

BankingBean

EJB instance

BankingHome

myContextSessionContext

2

1

: BankingHome

: Banking

: BankingBeannew

new

setSessionContext(sc)

ejbCreate

Page 151: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 30 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Business Methods

Business methods declared on the component interface mustthrow application exceptions. If the component interface isremote, they must also throw RemoteException.

deposit

deposit

EJB object

Home objectClient

BankingBean

EJB instance

Banking

BankingHome

21

Page 152: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 31 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Passivating Stateful Session BeanInstances

create ejbCreate

Client

Client

Client

Banking

Banking

Banking

BankingBean

BankingBean

BankingHome

2

4

5

3

1

6

Page 153: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 32 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Activating Stateful Session Bean Instances

Client

Client

Client

Banking

Banking

Banking

BankingBean

BankingBean

BankingBean

BankingHome

depositdeposit 4

2

3

1

Page 154: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 33 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Removing a Session Bean

A component developer codes the session EJB component’sremove method to free resources held by the bean class.

remove(handle)

ejbRemove

remove

or

EJB object

Home object

BankingBean

EJB instance

Banking

BankingHome

Client

Page 155: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 34 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Coding a Session EJB Component Client

1 InitialContext ic = new InitialContext();2 Object lookup = ic.lookup (“ejb/Hello”);3 HelloHome home = (HelloHome)4 PortableRemoteObject.narrow (lookup, HelloHome.class);5 Hello hello = home.create();6 hello.hello();7 helloBean.remove ();

Page 156: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 35 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The HelloSessionSession Bean

Client

HelloSessionBean

ejbCreate

hello

create

hello

HelloSessionHome

HelloSession

Page 157: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 4, slide 36 of 36Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• Session beans are service components that encapsulatecomplex business logic that is processed by the server.

• Session beans typically provide the primary point ofclient access to the business logic that resides in the EJBtier.

• A session bean component has several elements.• A session EJB component has creator methods, remove

methods, life cycle methods, and business methods.• The type of session EJB component, stateful or stateless,

determines the component’s life-cycle characteristics,and the timing of the component method invocations.

Page 158: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 5

Basics of Entity Beans

Page 159: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 2 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Describe the role of entity beans in a J2EE application• Describe the persistence management options available

when implementing entity EJB components• Describe the elements of an entity EJB component• Describe the life cycle and operational characteristics of

a CMP entity EJB component

Page 160: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 3 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Representation of Data Using Entity EJBComponents

Enterprise JavaBeansTechnology

Session Entity Message-Driven

Stateless

Stateful

Bean-Managed

Persistence (BMP)

Container-Managed

Persistence (CMP)

Page 161: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 4 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Representation of Data Using Entity EJBComponents

Entity beans:

• Are transactional and persistent objects• Represent business entities that are stored persistently,

usually in a relational database

Relational Database

Flat File

Legacy Application

Object Database

Directory Server

EntityEJB

ComponentDataStore

Page 162: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 5 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Object-Oriented Data Model

Entity EJB components:

• Provide an object-oriented view of the database• Decouple database structure from business logic,

which is implemented by session beans• Might contain application logic, which should be

intrinsic to the entity

CustomerEntityEJB

Component

Customer

Page 163: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 6 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Container-Managed Data Synchronization

EntityEJB

Component

ServiceLayer

DataStore

Set Attribute

Page 164: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 7 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Normalized Data Mapping

CustomerCustomer

AccountAccount

AddressAddress

Page 165: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 8 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Use of an Entity EJB Component Across aSet of Database Tables

CustomerEntityEJB

Component

Customer

Account

Address

Page 166: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 9 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Container-Managed Relationships

Customer

CustomerEntityEJB

Component Account

Address

Account

Entity

EJB

Component

Address

Entity

EJB

Component

Page 167: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 10 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Concept of Primary Key

• A primary key uniquely describes each logical elementin a data store.

• An entity EJB component distinguishes itself and thedata it represents from other entities using a primarykey class where the class fields are typically mapped tothe primary key in the underlying database table.

• Some types of data have a natural primary key.• Some types of data might require a unique sequence

number to identify the entity bean.

Page 168: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 11 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Entity EJB Component Primary KeyAssociation

<<customer>>

Primary Key 102

Customer Table

Database

<<customer>>

Primary Key 105

<<customer>>

Primary Key 976

102

105

976

.

.

.

.

.

.

Page 169: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 12 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Persistence Management Options

An entity EJB component developer can choose between twostyles of persistence management when implementing anentity EJB component:

• Bean-managed persistence (BMP)• Container-managed persistence (CMP)

These two forms of persistence are distinguished by themechanism used to implement the underlying data accesscode.

Page 170: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 13 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Bean-Managed Persistence

• The entity bean developer is responsible forimplementing all of the data access code required tointeract with the back-end data store.

• The container invokes synchronization methods on theentity bean at the appropriate times, usually attransaction boundaries.

• The data access code might be encapsulated in a DAO.

Page 171: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 14 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Container-Managed Persistence

• The container automatically stores and retrievespersistent fields from the database using databasemapping information furnished by the componentdeveloper.

• The code required to access the data store is specified inthe component’s deployment descriptor using ageneric query language called EJB QL.

Page 172: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 15 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

CMP Entity EJB Component PersistenceConfiguration

1 <?xml version="1.0" encoding="UTF-8"?>2 <ejb-jar>3 <enterprise-beans>4 <entity>5 <display-name>BankCustomer</display-name>6 ...7 <persistence-type>Container</persistence-type>8 ...9 <cmp-field><field-name>custId</field-name></cmp-field>10 <cmp-field><field-name>lastName</field-name></cmp-field>11 <cmp-field><field-name>firstName</field-name></cmp-field>12 ...13 </entity>14 </enterprise-beans>15 </ejb-jar>

Page 173: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 16 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB QL Deployment Descriptor Entry

1 <query>2 <query-method>3 <method-name>findCustomerByLastName</method-name>4 <method-params>5 <method-param>java.lang.String</method-param>6 </method-params>7 </query-method>8 <ejb-ql>9 SELECT object (o) FROM BankCustomer o WHERE o.lastName=?110 </ejb-ql>11 </query>

Page 174: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 17 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

CMP Benefits

CMP offers three major benefits:

• Convenience• Rich feature set• Database independence

Page 175: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 18 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Container Optimizations for CMP

• A CMP implementation is theoretically more efficientthan even the most carefully implemented BMPscheme.

• The EJB container has control of the instance poolingscheme and the transaction context.

• The container can make calls in such a way thatdatabase overheads are minimized.

• The container can implement both eager and lazyloading and storing schemes.

Page 176: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 19 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Appropriateness of CMP

• Most CMP implementations use SQL as the underlyingquery mechanism.

• It is problematic at present to use CMP for any storagesystem except a relational database.

• A place for BMP still exists for data stores that are notrelational databases.

Page 177: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 20 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Entity EJB Component Elements

bankingPrimary Key ClassCustPriKey.java

Component InterfaceRemote: Customer.javaLocal: CustomerLocal. java

Home InterfaceRemote: CustomerHome.javaLocal: CustomerLocalHome.java

Implementation ClassCustomerBean.java

Page 178: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 21 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Entity Bean Home and ComponentInterface Overview

• These interfaces serve a similar purpose to that alreadydescribed for session EJB components.

• It is much more likely that an entity bean will expose itsfunctionality using a local interface in addition to orinstead of a remote interface.

• The create and remove methods have a differentfunction:• The createmethod adds a new data element to the

underlying data store.• The removemethod deletes a data element from the

underlying data store.

Page 179: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 22 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Entity EJB Component Home Interface

• Entity component’s home interface defines a methodnamed findByPrimaryKey, which uses the associatedprimary key to locate an entity.

• Local and remote home interfaces extendjavax.EJBLocalHome and javax.ejb.EJBHome,respectively.

1 import javax.ejb.*;23 public interface MinimumCMPHome extends javax.ejb.EJBHome {45 public MinimumCMP findByPrimaryKey(Integer aKey)6 throws FinderException, java.rmi.RemoteException;7 }

Page 180: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 23 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Entity EJB Component Interface

• Entity EJB component interface provides access to thebusiness methods of an entity EJB component.

• Local and remote component interfaces extendjavax.EJBLocalObject and javax.ejb.EJBObject,respectively.

1 import javax.ejb.*;23 public interface MinimumCMP extends javax.ejb.EJBObject {}

Page 181: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 24 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Entity EJB Component ImplementationClass

1 import javax.ejb.*;2 public abstract class MinimumCMPBean3 implements javax.ejb.EntityBean {4 private javax.ejb.EntityContext context;56 public void setEntityContext(javax.ejb.EntityContext aContext) {7 context = aContext;8 }9 public void ejbActivate() {}10 public void ejbPassivate() {}11 public void ejbRemove() {}12 public void unsetEntityContext() {}13 public void ejbLoad() {}14 public void ejbStore() {}15 public Integer ejbCreate() throws javax.ejb.CreateException {}16 public void ejbPostCreate() throws javax.ejb.CreateException {}17 public abstract Integer getCustId();18 public abstract void setCustId(Integer custId);19 }

Page 182: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 25 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Entity EJB Component ImplementationClass

At deployment time, the application server generates aconcrete subclass of your bean class:

• This subclass provides implementations of all of theabstract methods in your bean class, specifically:• The get and set methods• The database synchronization logic• The ejbSelect methods

• Finder methods might be implemented in this subclassor on the generated home object.

Page 183: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 26 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Entity EJB Component Primary Key Class

• The primary key class must map to a column ormultiple columns in the underlying database.

• When a client updates or deletes an entity, the primarykey indicates which row is updated or deleted in theunderlying data.

• When a client creates an entity bean, the primary keythat the entity bean or container generates is used tocreate a new row in the database.

• The class must provide suitable implementations of thehashCode and equals methods.

Page 184: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 27 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Primary Key Class Deployment DescriptorEntry

1 <?xml version="1.0" encoding="UTF-8"?>2 <ejb-jar>3 <enterprise-beans>4 <entity>5 ...6 <prim-key-class>java.lang.Integer</prim-key-class>7 ...8 <primkey-field>custId</primkey-field>9 ...10 </entity>11 </enterprise-beans>12 </ejb-jar>

Page 185: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 28 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Client View of an Entity EJB Component

• Similar to that of a session EJB component.• Client obtains an EJB object by invoking one of the

bean’s creator or finder methods.• The container manages the allocation of EJB objects and

associated bean instances based on usage and resourceavailability.

• With CMP, the container synchronizes the state of eachentity bean with the persistent storage or database.

Page 186: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 29 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Client View of an Entity EJB Component

• Provides a strategy closer to a true object-orientedmodel in which objects are responsible for managingtheir own state

• Resolves issues that might arise when two or moreclients try to get access to the same pieces of data at thesame time

• Relieves the author of the client object with the burdenof setting transaction boundaries as thepersistence-management operation calls areintermingled with business method calls

Page 187: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 30 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Cardinality of Clients and EJB Objects

• Conceptually, there is an entity bean for everycorresponding row of data in the database.

• Entity beans, like all EJB components, are pooled.• All entity beans in the pool are identical, and they do

not have a specific identity assigned to them.• When an entity bean is initialized with data, it is

removed from the pool and given a specific identity.

Page 188: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 31 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Entity EJB Component Cardinality

CustomerLocalHome

CustomerBean

CustomerBean

CustomerBean

Customer 102

Customer 102

Customer 224

Customer 903

CustomerLocal

CustomerLocal

CustomerLocal Customer903

Identity

Customer224

Identity

Customer102

Identity

Pooled InstancesAll identicalNo EJB objectidentity assigned

Ready InstancesSpecific EJB objectIdentity assigned

Page 189: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 32 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Entity Bean Life Cycle With Method CallsInstance throwssystem exceptionfrom any method

Does notexist

Pooled

1� newInstance()2. setEntityContext(ec) 1. unsetEntityContext()

ejbRemove()ejbPassivate()ejbCreateXXX(args)()

ejbPostCreateXXX(args)()

ejbLoad()

ejbActivate()

ejbSelectXXX(args)*Business Method

ejbFindXXX(args)

ejbSelectXXX(args)ejbHomeXXX(args)

Ready

ejbTimeout(args)

*For CMP Entity EJB Components Only

ejbStore()

Page 190: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 5, slide 33 of 33Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• The role of entity EJB components• The object-oriented data view provided by entity beans• The purpose of a primary key• The two types of persistence mechanisms• The elements of an entity EJB component• The cardinality and life cycle of entity EJB components

Page 191: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 6

Developing CMP Entity Beans

Page 192: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 2 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Implement CMP entity beans• Write finder methods with the use of query language

for EJB technology (EJB QL)

Page 193: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 3 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Implementing CMP Entity EJB Components

A CMP entity EJB component developer must supply:

• Bean class• Corresponding home interface (local, remote, or both)• Corresponding component interface (local, remote, or

both)• Primary key class• Deployment descriptor for the entity EJB component

Page 194: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 4 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Creating CMP Entity EJB DeploymentDescriptors

1 <?xml version="1.0" encoding="UTF-8"?>2 <ejb-jar>3 <enterprise-beans>4 <entity>5 ...6 <ejb-class>BankCustomerBean</ejb-class>7 <persistence-type>Container</persistence-type>8 <prim-key-class>java.lang.Integer</prim-key-class>9 <reentrant>False</reentrant>10 <abstract-schema-name>BankCustomer</abstract-schema-name>11 <cmp-field><field-name>custId</field-name></cmp-field>12 <cmp-field><field-name>lastName</field-name></cmp-field>13 <cmp-field><field-name>firstName</field-name></cmp-field>14 <primkey-field>custId</primkey-field>15 </entity>16 </enterprise-beans>17 </ejb-jar>

Page 195: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 5 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Creating CMP Entity EJB DeploymentDescriptors

The deployment descriptor for a CMP entity EJB componentdefines the characteristics of the component, which include:

• Abstract schema• Persistence type• Primary key class• List of persistence fields• Primary key field

Page 196: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 6 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Creating an Entity Bean

ejbCreate(109,001,100.00)create(109,001,100.00)

create(int acctNum, int customerID, double balance)

Account109,001,100.00

AcctLocalHome

Acct # 109

EJBClient

Page 197: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 7 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Creator Method Sequence

Clientcreate(...) Home

Object

EJB Object(With Primary Key)

PoolManager

EJB BeanImplementation

1

allocate instance2

ejbCreate(...)3

ejbPostCreate(...)5

new4

return EJB

object6

Page 198: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 8 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

CMP Entity EJB ejbCreateandejbPostCreateMethod Implementation

1 public Integer ejbCreate(String pLastName,2 String pFirstName,3 Address pAddress)4 throws javax.ejb.CreateException {5 setLastName(pLastName);6 setFirstName(pFirstName);7 return null;8 }91011 public void ejbPostCreate(String pLastName,12 String pFirstName,13 Address pAddress)14 throws javax.ejb.CreateException {15 setAddress(pAddress);16 }

Page 199: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 9 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Finder Methods

Entity beans use finder methods to find one or more specificentities:

• Each entity bean is required to expose afindByPrimaryKey method in its home interface.

• The naming convention for custom finders in the homeinterface is findXXX.

• For CMP, the associated EJB QL is specified in thecomponent’s deployment descriptor.

• Single-entity finder methods only return one entitybean reference.

• Multi-entity finder methods return a Collection ofentity beans. Use these with care on large tables.

Page 200: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 10 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Single-Object Finder Method

ejbFindByPrimaryKeyfindByPrimaryKey*

Account Table

*findByPrimaryKey(int acctNum)

AcctLocalHome

Acct # 102

EJBClient

Page 201: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 11 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Multi-Object Finder MethodejbFindByCustomerIDfindByCustomerID*

Account Table

*findByCustomerID(int acctNum)

AcctLocalHome

Acct # 102

Acct # 110

Acct # 122

EJBClient

Page 202: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 12 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Finder Method Declaration and DeploymentDescriptor Entry

1 public Collection findCustomerByLastName (String pLastName)2 throws java.rmi.RemoteException, javax.ejb.FinderException;34 <query>5 <query-method>6 <method-name>findCustomerByLastName</method-name>7 <method-params>8 <method-param>java.lang.String</method-param>9 </method-params>10 </query-method>11 <ejb-ql>12 SELECT object (o) FROM BankCustomer o WHERE o.lastName=?113 </ejb-ql>14 </query>

Page 203: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 13 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Home Methods

• Are for business logic that is not specific to an entitybean instance

• Are called by way of the home interface• Have a corresponding ejbHome method in the entity

bean class• Have arguments that are used by the entity bean in

computations that do not depend on a specific entitybean instance

Home method arguments and return types on the remotehome interface must be legal types for RMI-IIOP.

Page 204: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 14 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Select Methods

• Query-based helper methods• Called by the bean class itself and not accessible to

clients• Implemented in the deployment descriptor with

EJB QL• Defined in the implementation class as abstract• Similar to finder methods, but do not require a call

through the home object1 public abstract LocalMinimumCMP2 ejbSelectCustByName(String pName)3 throws javax.ejb.FinderException;

Page 205: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 15 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Remove Methods

Client

remove()

Home

Object

EJB Object

(With Primary Key)

Pool

Manager

EJB Bean

Implementation

1

release instance4

allocate instance2

remove(pk)2

allocateinstance

2

ejbRemove()3

ejbRemove()

3

Page 206: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 16 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Query Language

EJB QL is a vendor-neutral, database-independent abstractionof a query language:

• EJB QL is similar in syntax to SQL.• EJB QL contains no schema-specific identifiers.• Identifiers refer to properties of entity beans.• The range of operators and data types is much smaller

than that offered by SQL.

Page 207: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 17 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Query Language

EJB QL queries are of the following form:

SELECT something FROM somewhere WHERE condition

• Something denotes the type of the thing to beretrieved, and introduces an identifier by which it canbe referenced.

• Somewhere denotes the objects from which you areselecting.

• Condition denotes the condition that you areimposing to select only specific objects.

Page 208: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 18 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Query Language

SELECT OBJECT (c) FROM customer c WHERE c.id = “A1”

• SELECT OBJECT(c)

The query returns references to EJB components andthe identifier c is used later to identify potentialmatches.

• FROM customer c

This section of the code indicates that c ranges overCustomer instances.

• WHERE c.id = ‘Al’

This section of the code indicates that the selectionshould include all of the customers for which thespecific test for c.id is true.

Page 209: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 19 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB QL Examples

The following examples relate to an entity bean calledCustomer, which is in a one-to-many association with an EJBcomponent called Account.

• The Customer bean has id, name, and addressproperties.

• The Account bean has a balance property.• For an EJB QL query to work across associations, the

association must be defined in the implementationclass as a Collection-valued abstract method. Forexample, the link between the Customer entity beanand the Account instance is declared in Customer asfollows:

public abstract Collection getAccounts();

Page 210: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 20 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB QL Examples

SELECT OBJECT (c) FROM customer c WHERE c.address =?1

Find all customers whose address is given by thefirst argument to the finder method.

SELECT OBJECT (c) FROM customer c IN (c.accounts) a WHERE a.balance < 0

Find all customers who have at least one overdrawnbank account.

SELECT OBJECT (c) FROM customer c IN (c.accounts) a WHERE a.balance > ?1

Find all customers who have at least one bankaccount with a balance that is greater than the firstargument to the finder method.

Page 211: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 21 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Steps for Creating a Finder Method

To create a finder method, you must do two things:

1. Declare the method in the home interface class:public java.util.Collection findCustomerByLastName(java.lang.StringpLastName) throws java.rmi.RemoteException, javax.ejb.FinderException;

2. Add EJB QL to the deployment descriptor toimplement the method:

1 <query>2 <query-method>3 <method-name>findCustomerByLastName</method-name>4 <method-params>5 <method-param>java.lang.String</method-param>6 </method-params>7 </query-method>8 <ejb-ql>SELECT object (o) FROM BankCustomer o WHERE o.lastName=?19 </ejb-ql>10 </query>

Page 212: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 22 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

In-Class Activity to Create a CMP EntityBean

The instructor will lead an in-class activity for creating a CMPentity bean. Use the supplied checklist to verify therequirements for the various classes. The bank customerentity bean illustrates the following features:

• EJB Name: BankCustomer• Three persistent fields:

• custId, which is the primary key• lastName

• firstName

• One business method named getPrintName

• One create method that sets the persistent fields

Page 213: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 23 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Source Code Examples

The source code examples in your student guide directlycorrespond to the in-class activity.

Review the code created during the in-class activity againstyour checklist.

Page 214: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 24 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

CMP Mapping to Database Elements Withthe IDE

The IDE provides a mechanism for mapping persistent fieldsto database elements:

• The deployer is responsible for mapping persistentfields to a database.

• To map the persistent fields of a CMP entity bean withthe IDE:• Use the EJB module template to create a module. Add

one or more EJB components to the module.• Map the persistent fields of a CMP entity bean

within the module to an existing database schema.

Instructor demonstration

Page 215: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 25 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

In-Class Activity to Add a Finder Method

The instructor will lead an in-class activity for creating afinder method on the BankCustomer CMP entity bean. Thefinder method illustrates the following features:

• Method name: findCustomerByLastName• Method accepts a single String parameter for the last

name• Method returns java.util.Collection

The EJB QL should return a collection of customers that havea last name that matches the input parameter.

Page 216: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 6, slide 26 of 26Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• The responsibilities of a CMP entity EJB componentdeveloper

• The function of a CMP entity EJB component’smethods

• How to use EJB QL to configure a CMP entity EJBcomponent to access a data store

Page 217: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 7

Assembling EJB Components Into anApplication

Page 218: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 2 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Exploit reusable components• Package components appropriately• Use the java:comp/env namespace• Resolve resource and EJB component references• Use the EJB component’s environment• Use application client containers

Page 219: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 3 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Exploiting Reusable Components

To get the full benefit of the reuse mechanism in the J2EEmodel, developers and assemblers must follow certain designpractices:

• Package components appropriately• Use the java:comp/env namespace for lookups• Avoid hard-coded configuration in components• Use client containers for standalone clients

Page 220: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 4 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Packaging Options

Customer

Customer

BankMgr

BankMgr

JAR1

JAR1

EAR1

EAR1

JAR2

Page 221: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 5 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Assigning Components to Modules

When you package and allocate EJB components to JARmodules, keep the following points in mind:

• Entity beans to be used in container-managedrelationships must be packaged together.

• EJB components that form a tightly-coupled assemblyshould be packaged together.

• EJB components that could be reused independentlyshould be packaged separately.

Page 222: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 6 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Assigning Components to Modules

Different roles address deployment descriptors for EJBcomponents at different stages:

• The EJB component developer usually creates adeployment descriptor file for the JAR module thatcontains the EJB component code.

• The assembler and deployer can edit the developer’sdeployment descriptor file.

Page 223: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 7 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Components and Modules in IDE Tools

IDE tools that are designed for the J2EE platform providefeatures for the management of components and have thefollowing characteristics:

• Must respect the J2EE specification’s packaging rules• Maintain an internal representation of the structure of

each component• Render their internal representation into JAR files and

EAR files at deployment time

Page 224: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 8 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Namespace Management Problems inComplex Applications

Problem:

An application server’s central naming service isaccessible by JNDI API calls and shared by allapplications. Potential for name conflicts is great.

Solution:

In the J2EE model, the developer works with indirectnames, not JNDI names. These indirect names aremapped to JNDI names at deployment.

Page 225: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 9 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Local Namespaces

EJB components each have their own local namespace, whileweb components share a local namespace with othercomponents in the same WAR module.

lookup("java:comp/env/XXX")

Naming Service

Local Namespace

lookup("YYY")

Container

Page 226: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 10 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Resolving Resource and EJB ComponentReferences

• Component provider:• Develops each J2EE application component so that

lookups for other components and resources are intheir local namespaces

• Exposes coded names in the deployment descriptors• Deployer:

• Registers an application’s components andresources in the naming service

• Resolves references in the deployment descriptors tothe registered names

Page 227: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 11 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

References in the Deployment Descriptors

Exposing remote references in the deployment descriptor:

• In the BankMgr EJB component:Context c = new InitialContext();Object o = c.lookup(“java:comp/env/ejb/TheCustomer”);CustomerHome c = (CustomerHome)

PortableRemoteObject.narrow (o, CustomerHome.class);

• In the deployment descriptor:<session><ejb-name>BankMgr</ejb-name><ejb-ref><ejb-ref-name>ejb/TheCustomer</ejb-ref-name><ejb-ref-type>Entity</ejb-ref-type><home>bank.CustomerHome</home><remote>bank.Customer</remote>

</ejb-ref></session>

Page 228: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 12 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

References in the Deployment Descriptors

Exposing local references in the deployment descriptor:

• In the BankMgr EJB component:Context c = new InitialContext();Object o = c.lookup(“java:comp/env/ejb/TheCustomer”);CustomerHome c = (CustomerHome) o; // No narrow

• In the deployment descriptor:<session><ejb-name>BankMgr</ejb-name><ejb-local-ref><ejb-ref-name>ejb/TheCustomer</ejb-ref-name><ejb-ref-type>Entity</ejb-ref-type><local-home>bank.CustomerLocalHome</local-home><local>bank.CustomerLocal</local>

</ejb-local-ref></session>

Page 229: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 13 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Reference Naming Conventions

The following examples illustrate a naming convention that isgenerally followed for resolving references and JNDI names.

Prefix Type of Object Referenced

ejb/something EJB components

jdbc/something Databases

jms/something Messaging services

Page 230: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 14 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Resolving References at Deployment Time

lookup("java:comp/env/ejb/TheCustomer)

Local Namespace

ejb/Customer -> Customer

BankMgr

CustomerNaming Service

ejb/Customer -> Customer

Page 231: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 15 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Configuration Strategies

Problem:

When J2EE components are reused, they will likely needreconfiguration. Configuration data:

• Cannot be embedded in source code• Must be in a uniform format, external to the component

Page 232: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 16 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Configuration Strategies

Solution:

In the J2EE model, configuration data for web and EJBcomponents is supplied through a standardized technique:

• The developer writes components to pick upconfiguration data by a JNDI API lookup call.

• The assembler or deployer provides the configurationvalues in the deployment descriptor.

Page 233: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 17 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB Component Environment

<XML>

</XML>

Local Namespace

DeploymentDescriptor

BankMgr

Overdraftlimit-> 500

lookup("java:comp/env/Overdraftlimit")

Page 234: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 18 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Capabilities of the EJB ComponentEnvironment

The EJB component environment:

• Can store objects of the following classes: String,Character, Integer, Boolean, Double, Byte, Short,Long, or Float

• Is specific to a particular EJB componentValues cannot be shared between components,unless they are replicated.

• Is read-only• Uses values that are set at deployment time and cannot

normally be changed after deployment

Page 235: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 19 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Issues With Standalone Clients

Problem:

Standalone clients are not part of the application server’srun-time environment, which has two importantconsequences:

• A user’s identity will not necessarily be trusted by theapplication server.

• Standalone clients have no local namespace, so theymust use real JNDI names to locate EJB components.This constrains namespace management on theserver.

Page 236: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 20 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Issues With Standalone Clients

Solution:

Use an application client container.

• The client container is generated by the server when theapplication is deployed.

• The client accesses the server’s security infrastructureand naming service through the client container.

Page 237: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 21 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Authentication by the Application ClientContainer

BankMgrJava ApplicationClient

Security

Interface

Application Client

Container

Application

Server

Security

Infrastructure

Security

Credentials

Page 238: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 22 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Client Container Namespace

The application client container provides the standaloneclient with a local java:comp/env namespace:

• The client uses this namespace to look up references toEJB components.

• The client developer exposes the EJB componentreferences in the deployment descriptor.

• At deployment, the references are mapped to real JNDInames.

• This mapping mechanism decouples the server’snamespace from the client.

Page 239: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 7, slide 23 of 23Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• Exploiting reusable components• Packaging components• Using the java:comp/env namespace• Resolving resource and EJB component references• Using the EJB component's environment• Using application client containers

Page 240: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 8

Developing Message-Driven Beans

Page 241: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 2 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Benefit from the use of enterprise messaging• Describe the use of the JMS API• Describe the role of message-driven beans• Describe the object cardinality, life cycle, and pooling

of message-driven beans• Implement message-driven beans

Page 242: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 3 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Using Enterprise Messaging

Messaging systems:

• Enable asynchronous and loosely coupledcommunication between disparate applications

• Promote peer-to-peer relationships betweenapplication components

• Maintain a high degree of anonymity between messageproducers and message consumers

• Should be scalable, reliable, and easy to integrate intoheterogeneous networks

The J2EE specification includes the JMS API to implementmessaging between application components.

Page 243: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 4 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Enterprise Messaging System

Application Server

Application 1

Application 2

Client Process D

Client Process E

Client Process A

Client Process B

Client Process F

MessageService

Client Process C

Page 244: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 5 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Guaranteed Delivery

There are four aspects to messaging reliability:

• Offer some guarantee of successful delivery• Allow message sending and receiving to be

transactional:• Transactional production• Transactional consumption

• Deliver a message exactly one time to each recipient• Provide a reliable fault-tolerance

Page 245: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 6 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Example of Messaging

Client

Deposit.....Deposit

Deposit

Withdrawl.....

WithdrawlDeposit.....

Withdrawl....

~~~~~~~~

Client

Client JMSQueue

LoggingApplication

(QueueConsumer)

Logs

BankingApplication

Page 246: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 7 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Messaging Models

• Point-to-point – Messages are sent to a queue and thereis only one consumer for each message.

• Publish and Subscribe – Messages are event driven:• Message consumers subscribe to topics.• Message producers associate a message with a

specific topic.• A message router routes messages to subscribers of

a topic.

Page 247: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 8 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Point-to-Point and Publish and SubscribeMessaging Models

Point-To-Point Messaging

Publish and Subscribe Messaging

ClientBart

ClientBob

ClientEd

MessageRouter

ClientBart

MessageQueue

ClientEd

MessageQueue

ClientBob

MessageQueue

1

3 C

2B

A

Page 248: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 9 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Synchronous and AsynchronousMessaging

Synchronous

ClientBart

- Processing- Processing

- Ready to send

ClientBob

- Blocked

- Ready to receive

- Receiving- Sending

- Processing- Processing

Asynchronous

ClientBob

ClientBart

Message

Router

Register

Send

Page 249: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 10 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

JMS API

• Java Message Service makes standardized messagingavailable to Java applications.

• The JMS API is a set of interfaces that the developer canassume have been implemented by the messagingvendor.

• JMS implements a core suite of common operationsthat are provided by most enterprise messagingsystems.

• The JMS API provides an interface for accessingmessaging systems from a variety of vendors, such asIBM® WebSphere MQ Series, and TIBCO Rendezvous.

Page 250: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 11 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Abstraction of the UnderlyingImplementation

Java Clients JMS InterfaceImplementingTechnologies

Sun OneMessageQueue

Software

TIBCORendezvous

IBMWebsphere

MQ

Page 251: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 12 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Abstraction of the UnderlyingImplementation

• An important element of a messaging system is themessage.

• Messages are lightweight elements that consist of aheader and a message body:• The message header stores information used for

message routing and identification.• The message body contains the application data

component.• JMS technology defines a flexible message format that

can be used to work with a wide variety of existingmessage types.

Page 252: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 13 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message Structure

Message

Header

Message

Body

Text

Primitives

Name-value pairs

Serializable object

Byte stream

Message identification

Routing information

Header extensions or properties

Page 253: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 14 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Connection Factories

• Connection factories provide clients with a connectionobject that represents a connection to a messagingserver.

• The JMS API provides two types of factories:• Queue factories, which implement the

javax.jms.QueueConnectionFactory interface• Topic factories, which implement the

javax.jms.TopicConnectionFactory interface• Clients use the connection object to post and receive

messages.

Page 254: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 15 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Prerequisites for Sending a Message to aQueue

1. Obtain an InitialContext object and look up theconnection factory.

2. Look up the queue (or topic).3. Use the ConnectionFactory object to create a

QueueConnection object.4. Use the connection to create a QueueSession object.5. Use the session object to create a message producer,

such as a QueueSender object.6. Use the session object to create a message.7. Use the message producer to send the message to the

destination.

Page 255: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 16 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Process of Sending a Message to a Queue

Destination

JNDI API

ConnectionFactory

Session

Message

Connection

MessageProducer

1. Lookup

2. Lookup

3. New

4. New

5. New6. New

7. Send

Page 256: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 17 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Sending a Message to a Queue

1 Context ctx = new InitialContext();2 QueueConnectionFactory factory = (QueueConnectionFactory)ctx.lookup("jms/QueueConnectionFactory");3 Queue q = (Queue)ctx.lookup("jms/Queue");4 QueueConnection qc = factory.createQueueConnection();5 QueueSession qSess = qc.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);6 QueueSender qSend = qSess.createSender(q);7 TestMessage tm = qSess.createTextMessage(“Hello World”);8 qSend.send(tm);

Page 257: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 18 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Role of Message-Driven Beans

Message-driven beans fill the role of message consumer in theJ2EE platform.

• Invalid JMS message consumers• Message-driven beans as message consumers• Message-driven beans and J2EE Connector

Architecture

Page 258: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 19 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Invalid JMS Message Consumers

The following can be message producers, but cannot bemessage consumers in the J2EE platform:

• Session beans• Entity beans

Page 259: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 20 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message-Driven Beans as MessageConsumers

A message-driven bean:

• Is an asynchronous message consumer of messages• Has neither a home nor a component interface• Is associated with a queue or topic destination• Provides the onMessagemethod as a means to process

messages that arrive at destination X

• Is a MessageListener on a destination X to whichclients send messages

Page 260: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 21 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Client Relationship With Message-DrivenBean

Client

Destination

Container

Message-Driven Bean

Message-driven bean instances

Page 261: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 22 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message-Driven Beans and J2EEConnector Architecture

• Message-driven beans support the ability to consumeevents other than JMS messages.

• Through the use of the J2EE Connector Architecture,message-driven beans are able to receive informationfrom a variety of sources, such as legacy applications,which do not produce JMS messages.

• Message-driven beans indicate the type of messagethey listen for by the type of message listener interfacethey implement.

Page 262: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 23 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Basics of Message-Driven Beans

• Instance pooling and statelessness• Message-driven bean life cycle

Page 263: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 24 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Instance Pooling and Statelessness

• Message-driven beans carry no client state and are,therefore, considered stateless.

• The container considers all instances to be identical.• An incoming message can be handled by any free

instance.• The container will normally hold a pool of method-ready

instances and allocate an instance to each incomingmessage.

Page 264: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 25 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Instance Pooling and Statelessness

• There is no association between the identity of themessage producer and the instance that handles themessage.

• The container will prevent the onMessage methodfrom being entered on multiple threads.

• There must be sufficient instances in the pool to handleconcurrency.

Page 265: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 26 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message-Driven Bean Life Cycle

1.newInstance()2.setMessageDrivenContext(mdc)3.ejbCreate()

ejbCreate()

ejbRemove()

ejbTimeout(arg)������� ������ �����

������� ������ ����� Action resulting from client message arrival

Action initiated by container

Does notexist

Method-readypool

Page 266: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 27 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message-Driven Bean Life Cycle

The following steps provide a simplified version of theinteractions between the client, the messaging service, thecontainer, and the implementation instance:

1. The container initiates the message-driven bean’s lifecycle by creating a new instance of the bean, which isusually done when the bean is deployed or thecontainer is started.

2. The container calls the bean instance’ssetMessageDrivenContext method.

3. The container calls the bean instance’s ejbCreatemethod.

Page 267: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 28 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message-Driven Bean Life Cycle

4. The client (producer) sends a JMS message to themessaging service destination.

5. The container invokes the bean instance’s onMessagemethod to read and process the message from thedestination.

Page 268: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 29 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Method Sequence for Message-DrivenBeans

X

Client or Producer Container

Instanceor

Consumer

setMessageDrivenContext

(MessageDrivenContext)

ejbCreate()

send JMS message

new

ejbRemove

onMessage(msg)

Page 269: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 30 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Implementing Message-Driven Beans

• The bean developer is responsible for coding theimplementation class.

• The deployer is responsible for associating themessage-driven bean with a destination or end point inthe bean’s deployment descriptor.

Page 270: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 31 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Interfaces Implemented byMessage-Driven Beans

• The javax.ejb.MessageDrivenBean interface• The particular listener interface for the type of message:

• If the bean supports JMS API message types, thebean must implement thejavax.jms.MessageListener interface.

• If the bean supports JAXM message types, the beanmust implement either:• The javax.xml.messaging.OneWayListener

interface• The javax.xml.messaging.ReqRespListener

interface

Page 271: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 32 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The ejbCreateMethod

• Takes no parameters• Initializes resources needed by the incoming messages• Must have the following signature:

public void ejbCreate()

Page 272: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 33 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The setMessageDrivenContextMethod

• Allows for access to the MessageDrivenContextobject• Is typically used to save the MessageDrivenContext

object, as shown in the following example:1 public void setMessageDrivenContext(javax.ejb.MessageDrivenContextaContext) {2 context=aContext;3 }

Page 273: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 34 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The onMessageMethod

• When a message-driven bean consumes a message, theonMessage method is invoked.

• The parameter to the onMessagemethod is of the typejavax.jms.Message.

• A message-driven bean instance can only process onemessage at a time.

• The bean provider must obtain the message anddowncast it to its appropriate type, as shown in thefollowing example:

1 public void onMessage(javax.jms.Message msg) {2 TextMessage tm = (TextMessage)msg; // downcast3 String text = tm.getText();4 }

Page 274: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 35 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The ejbRemoveMethod

• The container calls the ejbRemove method when amessage-driven bean instance is removed from thebean instance pool.

• Resources used by the incoming messages should bereleased in the ejbRemove method.

• Implementing this method is optional.

Page 275: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 36 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message-Driven Bean DeploymentDescriptor

• The deployment descriptor for a message-driven EJBcomponent requires:• Name• Class• Transaction type• Destination information

• In this course, you use the IDE to create amessage-driven bean, and the deployment descriptoris generated from the bean’s properties.

Page 276: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 37 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message-Driven Bean Examples

The code examples on the following slides show a messageproducer and a message-driven bean that consumes themessages sent to the queue.

Code is provided for the following:

• Client-message producer• Message-driven bean implementation class• Message-driven bean deployment descriptor

Page 277: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 38 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Client-Message Producer

5 ...6 Context ctx = new InitialContext();7 QueueConnectionFactory factory = (QueueConnectionFactory)ctx.lookup("jms/QueueConnectionFactory");8 Queue q = (Queue)ctx.lookup("jms/Queue");9 QueueConnection qc = factory.createQueueConnection();10 QueueSession qSess = qc.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);11 QueueSender qSend = qSess.createSender(q);12 TestMessage tm = qSess.createTextMessage(“Hello World”);13 qSend.send(tm);14 ...

Page 278: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 39 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message-Driven Bean ImplementationClass

1 import javax.jms.*;2 import javax.ejb.*;34 public class SampleMDBBean implements javax.ejb.MessageDrivenBean,javax.jms.MessageListener {5 private transient javax.ejb.MessageDrivenContext context;67 public void setMessageDrivenContext(javax.ejb.MessageDrivenContextaContext) {8 context=aContext;9 }1011 public void ejbCreate() {12 // perform initialization13 }141516 public void onMessage(javax.jms.Message aMessage) {17 TextMessage tm = (TextMessage)msg;

Page 279: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 40 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message-Driven Bean Implementation Class

18 String text = tm.getText();19 // process text message20 }212223 public void ejbRemove() {24 // perform cleanup25 }2627 }

Page 280: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 41 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Message-Driven BeanDeployment Descriptor

1 <?xml version="1.0" encoding="UTF-8"?>2 <ejb-jar>3 <enterprise-beans>4 <message-driven>5 <display-name>SampleMDB</display-name>6 <ejb-name>SampleMDB</ejb-name>7 <ejb-class>SampleMDBBean</ejb-class>8 <transaction-type>Container</transaction-type>9 <resource-ref>10 <res-ref-name>jms/QueueConnectionFactory</res-ref-name>11 <res-type>javax.jms.QueueConnectionFactory</res-type>12 <res-auth>Container</res-auth>13 </resource-ref>14 <resource-env-ref>15 <resource-env-ref-name>jms/Queue</resource-env-ref-name>16 <resource-env-ref-type> javax.jms.Queue</resource-env-ref-type>17 </resource-env-ref>18 </message-driven>19 </enterprise-beans>20 </ejb-jar>

Page 281: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 8, slide 42 of 42Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• Benefits of enterprise messaging• JMS API• The role of message-driven beans• Object cardinality, life cycle, and pooling of

message-driven beans• Implementation of message-driven beans

Page 282: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 9

Web Component Model

Page 283: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 2 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Describe the role of web components in a J2EEapplication

• Define the HTTP request-response model• Compare Java servlets and JSP components• Describe the basic session management strategies• Manage thread safety issues in web components

Page 284: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 3 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Role of Web Components in a J2EEApplication

• Web-centric J2EE application architecture:

• EJB component-centric J2EE application architecture:

DBMS

<%%>

<%%>UI

DBMS

SQL

Web Container

Views

HTML Form

HTML

Client Presentation and Business Resource

Web BrowserController

<%%>

Model

BusinessServices

Entities

DBMS

<%%>

<%%>

<%%>

UI

DBMS

SQLRMI / IIOP

Web Container EJB Container

Views

HTML FormWeb Browser

Controller

HTTP

Client Presentation Business Resource

BusinessServices

Entities

Page 285: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 4 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

HTTP Request-Response Model

Web Container

Browser

Request Header

Request Body

Response Header

Response Body

2

1

Page 286: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 5 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The GETand POSTRequests

GET Request POST Request

Type of Use Default Form submission

Method of SendingForm Data

• Sent with the URI• Size is limited

• Sent in the request body• Size is unlimited

Display of FormData

Browser displays in theURI area

Browser does not normallydisplay with the URI

Page 287: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 6 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Form Data

HTML snippet:<FORM ACTION=’form_test’ METHOD=’POST’><INPUT NAME=’input1’ SIZE=’20’/><INPUT TYPE=’SUBMIT’ VALUE=’OK’/></FORM>

Browser form:

Browser request:POST /bank/form_test HTTP/1.1... request headers...

input1=this+is+a+test

Page 288: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 7 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Content Type and the Response Header

The server response includes acontent-typeheader that cancontain the following elements:

• Content type:• text/html

• text/xml

• image/jpeg

• Content encoding• Content length

Page 289: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 8 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Comparison of Servlets and JSP™Components

Servlets JSP Components

DescriptionWeb components authoredin the Java programminglanguage

Presentation content withembedded programmaticelements

Characteristics

Extend generic base classesin the API, typically theHttpServlet interface

• Can be extended withcustom tags

• Are translated intoservlets by the webcontainer

Created orManaged By

Developers Content authors

Page 290: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 9 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Life Cycle of a Web Component

X

Browser1

response

response

new

init()

service()

service()

destroy()

request

request

Browser2 Web Container Web Component

Page 291: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 10 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The serviceMethod

The web container calls the service method once for eachincoming request. The service method then typicallycompletes the following operations:

• Validates any form data• Updates the application’s data model• Collects data from the model to be rendered• Renders the data in HTML or passes the request and the

data to another component to be rendered

Page 292: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 11 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Servlet and JSP Component Examples

The examples on the following slides illustrate the similaritiesand differences between servlets and JSP components.

• Servlet example• JSP component example• Servlet and JSP component collaboration• Run-time behavior of servlets and JSP components• Web context root and alias mapping

Page 293: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 12 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Servlet Example

1 import javax.servlet.*;2 import javax.servlet.http.*;34 public class Controller extends HttpServlet {56 protected void doGet(HttpServletRequest request,

HttpServletResponse response)7 throws ServletException, IOException {8 PrintWriter out = response.getWriter();9 out.println (“<html><head/><body>\n”);10 out.println (“<h1>Hello, World!</h1>\n”);11 out.println (“The date is:\n”);12 out.println (new Date());13 out.println (“</body></html>\n”);14 out.close();15 }16 }

Page 294: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 13 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

JSP Component Example

The following code generates the same output as thepreceding servlet example:

1 <html>2 <head/>3 <body>4 <h1>Hello, World</h1>5 The date is: <%= new Date() %>6 </body>7 </html>

Page 295: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 14 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Servlet and JSP Component Collaboration

Most modern web applications use servlets and JSPcomponents in collaboration. Their capabilities are similar, butthey are expressed differently.

Servlet JSP Component

Type ofOperation

• Process form data• Perform computations• Collect data for rendering

Generate presentation,particularly HTML

RoleHandle requests, performcomputations, transfercontrol to JSP components

Render a response to theinitial request

Page 296: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 15 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Run-Time Behavior of Servlets and JSPComponents

Because JSP components are translated into servlets, JSPcomponents and servlets share run-time behaviors:

• Life cycle and container management• API and container services• Client session access

Both can be entered on multiple threads and must beimplemented accordingly.

Page 297: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 16 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Web Context Root and Alias Mapping

Servlets and JSP components are packaged into a webapplication.

• Static content, such as HTML or images, is included.• A web application URI has the following form:

http://server:port/context_root/resource

• Context root• Resource

Aliases map to Java classes in the deploymentdescriptor:http://www.mybank.com/bank/main

Page 298: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 17 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session Management

The HTTP is stateless. Conversational state might be storedon either the browser or the server:

The J2EE model provides a simple mechanism for storingconversational state on the server.

Browser Server

DescriptionSimple and does notconsume server resources

Must carry a session IDbetween the browser andserver

StorageAvailability

Limited Less restricted

Page 299: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 18 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Web Component Thread Model

Browser1

int x;public void doGet() {

x = 1

}

x = 2

? x

Browser2

Page 300: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 19 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Implications for the Developer

Because the web container enters the service method onmultiple concurrent threads to support multiplesimultaneous requests, the developer must ensure that webcomponents are thread-safe:

• Use instance variables cautiously• Use class variables very cautiously• Provide access to external resources cautiously• Use synchronization constructs to denote critical

sections:synchronized (this) {// This section is only entered by one thread at a time// ...}

Page 301: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 9, slide 20 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• The HTTP request-response model• A comparison of Java servlets and JSP components• Session management features• Thread safety issues in web components

Page 302: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 10

Developing Servlets

Page 303: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 2 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Describe the servlet API• Use the request and response APIs• Forward control and pass data• Use the session management API• Call EJB components from servlets

Page 304: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 3 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Basics of the Servlet API

The servlet API provides the following facilities to servlets:

• Callback methods for initialization and requestprocessing

• Methods by which the servlet can get configurationand environment information

• Access to protocol-specific resources

Page 305: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 4 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Structure of the Servlet API

GenericAPI Level

Protocol-SpecificAPI Level

ImplementationLevel

<<Interface>>Servlet

GenericServlet{abstract}

HttpServlet

Your HTTP Servlet

<<Interface>>ServletRequest

<<Interface>>HttpServletRequest

Vendor’sRequest Object

Page 306: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 5 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Benefits of the Protocol-Specific API

It is usually more convenient to work with theprotocol-specific classes and interfaces for a number ofreasons:

• Protocol-specific classes provide access to objects thatare protocol-specific, such as the HttpSessionimplementation.

• The method arguments and return values are definedin terms of other protocol-specific objects.

• Protocol-specific classes provide boilerplate processingfor common operations.

Page 307: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 6 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Benefits of the HttpServlet Class

Benefits of extending the HttpServlet base class include:

• A simplified, no-argument init()method, which canbe overridden to do initialization without the need toinitialize the base class

• Standard handling of HTTP request types that are not ofinterest to the servlet

• Request handler arguments that are defined in terms ofHTTP-specific request and response objects

Page 308: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 7 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The serviceMethod

Delegates

Called bycontainer

HttpServlet

+service(request, response)+doGet(request, reponse)+doPost(request, reponse)+doPut(request, reponse)...

Page 309: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 8 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Request Handling Methods

Delegates

Delegates

Called bycontainer

HttpServlet

+service(request, response)+doGet(request, reponse)+doPost(request, reponse)...

YourHttpServlet

+doGet(request, response)+doPost(request, reponse)+processRequest(request,reponse)

Page 310: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 9 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Basic Servlet

1 import javax.servlet.http.*;2 public class MyHttpServlet extends HttpServlet {34 public void doGet (HttpServletRequest request,

HttpServletResponse response) {5 processRequest (request, response);6 }78 public void doPost (HttpServletRequest request,

HttpServletResponse response) {9 processRequest (request, response);10 }1112 public void processRequest(HttpServletRequest request,

HttpServletResponse response) {13 // Process request and generate response14 }15 }

Page 311: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 10 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Using the Request and Response APIs

The servlet (web) container creates a request and responseobject for each new request. The request and response objectsare passed to the servlet’s service method.

• The request object:• Provides information about the request• Allows the servlet to obtain user information and to

pass data to other web components• The response object provides the servlet with

mechanisms to generate a response or an error code tothe browser.

Page 312: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 11 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Request Object

Generic Methods Purpose

getParameter Gets form data elements

getAttribute andsetAttribute

Gets and sets attributes, which are usedfor passing data between components

getRequestDispatcher Gets a request dispatcher to transfercontrol to another component

HTTP Specific Methods Purpose

getUserPrincipal Gets user’s identity

getCookies Gets cookies sent by browser

getSession Gets client session

Page 313: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 12 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Response Object

Generic Methods Purpose

getOutputStream,getWriter

Gets a stream or writer to send data to thebrowser

setContentType Indicates the MIME type of response body

HTTP Specific Methods Purpose

encodeURL Adds a session ID to a URL

addCookie Sends a cookie to the browser

sendError Sends an HTTP error code

Page 314: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 13 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Example of Handling Form Data andProducing Output

1 public void processRequest (HttpServletRequest request,HttpServletResponse response)

2 throws IOException {3 response.setContentType (“text/html”);4 PrintWriter out = response.getWriter();5 out.println (“<h1>Hello</h1>”);6 String name = request.getParameter (“name”);7 if (name == null || name.length() == 0)8 name = “anonymous”;9 out.println (“Hello, “ + name);10 out.close();11 }

Page 315: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 14 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Forwarding Control and Passing Data

Request processing and presentation are separated to simplifysoftware management. No component carries out bothprocessing and presentation.

The processing component typically completes the followingactions:

• Does its work and gathers data to be rendered• Puts the data into the request• Transfers control to the presentation component with

the use of a RequestDispatcher object

Page 316: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 15 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The RequestDispatcher Interface

A servlet has two ways to get access to an object thatimplements the RequestDispatcher interface:

• From the request, by URI as follows:RequestDispatcher requestDispatcher =request.getRequestDispatcher(“URI”);

• From the servlet’s run-time context, by giving the nameof the target servlet as defined in the deploymentdescriptor as follows:

RequestDispatcher requestDispatcher =getServletContext().getNamedDispatcher(“ServletName”);

Page 317: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 16 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The RequestDispatcherTarget and theContext Root

The argument to getRequestDispatcher is a URI, but it isinterpreted by the web container with reference to the currentapplication’s context. The URI must:

• Begin with a slash (/)• Not contain a context root or be a full URI

In the bank sample application, the servlet obtains the JSPcomponent to which it will transfer control using thefollowing statement:

getRequestDispatcher (“/showCustomerDetails.jsp”);

Page 318: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 17 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The forwardand includeMethods

The RequestDispatcher interface provides two methods totransfer control from a servlet (the calling component) to atarget component:

• RequestDispatcher.forward

• RequestDispatcher.include

Of these methods, forward is slightly faster but cannot mergethe output of one component into the output of another.

Page 319: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 18 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Transfer of Data in the Request Object

The request object can carry data between components:

• In the calling component:CustomerData customerData = // get customer datarequest.setAttribute (“customerData”, customerData);requestDispatcher.forward (request, response);

• If the target component is a servlet:CustomerData customerData = (CustomerData) getAttribute(“customerData”);

• If the target component is a JSP component:<jsp:useBean id=”customerData” class=”Bank.CustomerData” scope=”request”/>

Page 320: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 19 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Using the Session Management API

The J2EE platform’s session management model in the webtier is based on the HttpSession interface. A servlet cancomplete the following actions:

• Determine whether a session has just been created• Add a named item to the session• Retrieve a named item from the session• Close the session

Page 321: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 20 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

J2EE Platform Web-Tier SessionManagement Model

Browser2

Web Container

Servlet

Browser1

HttpSession

sessionID=2JQ88name=mary

[email protected]

HttpSession

sessionID=1A78Jname=fred

[email protected]

Request HeadersessionID=2JQ88

Request HeadersessionID=1A78J

Page 322: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 21 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session and Authentication

Session information is stored in the session object.

• After a user has been authenticated by the servletcontainer, the user’s ID and authentication statusbecomes part of the session.The user has to log in only once in each session.

• The servlet can use the request.getUserPrincipalmethod to get the user’s login identification.

Page 323: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 22 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session Binding

For each request, the server must be able to identify thespecific browser to select the correct session object. Thissession binding is performed using cookies or URL rewriting.

Session BindingTechnique

Advantages Disadvantages

Cookies The container reads andwrites cookies, so there is noadditional work for you.

Not all browsers supportcookies.

URI rewrite The URI rewrite techniqueworks without cookiesupport.

You must ensure that thesession ID is appended toevery URL that the browsersees.

Page 324: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 23 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Session Timeout

The web container times out idle sessions after a period ofinactivity. The web application:

• Cannot distinguish a session that has timed out from agenuinely new session.

• Must be developed to handle this situation gracefully,typically by reinitializing the session.

Page 325: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 24 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

New and Timed-Out Sessions

Problem:

In general, the web container cannot distinguish between apost-timeout request and a new session. TheHttpSession.isNew method returns true in either of thefollowing situations:

• The session is a new session with a new browser.• The current browser session timed out before this

request.

Solution:

Use design patterns to handle discrimination between a newsession and a post-timeout session.

Page 326: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 25 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Retrieving a Session Object

1 // Get a session object for the current client, creating2 // a new session if necessary3 HttpSession session = request.getSession();45 // If this is a new session, initialize it6 if (session.isNew()) {7 // Initialize the session attributes8 // to their start-of-session values9 session.setAttribute (“account”, new Account());10 // ... other initialization11 }1213 // Get this client’s ‘account’ object14 Account account = (Account) session.getAttribute(“account”);

Do not use the session object to transfer data betweencomponents because it is very inefficient.

Page 327: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 26 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Logout and Invalidation

Application design and session management can reduce thesecurity risk and memory usage of sessions that remain openafter use.

• Provide users with options for logging out or forclosing the session:• Log out after fixed number of steps• Log out with the click of a Logout button• Log out through menu operation

• To close the session, call its invalidate method:1 if (“logout”.equals(request.getParameter(“action”)) {2 session.invalidate();3 }

Page 328: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 27 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Calling EJB Components From Servlets

Servlets can freely call stateless and stateful session beans.However, the developer should observe the followingguidelines in using servlets with EJB components:

Guideline Rationale

Servlets should avoid calling entitybeans.

The narrowness of the transactionboundaries leads to inefficientsynchronization.

Servlets should generally make afew complex method calls, ratherthan many simple method calls.

Reduce RMI overheads.

EJB home objects can be located atinitialization time.

References to home objects do notchange over the life of the servlet.

Page 329: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 28 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Initializing a Reference to a Home Object

1 // Keep home object reference in2 // an instance variable3 private BankMgrHome bankMgrHome = null;45 public void init() {6 try {7 InitialContext ic = new InitialContext();8 Object o = ic.lookup (“java:comp/env/ejb/BankMgr”);9 bankMgrHome = (BankMgrHome)10 PortableRemoteObject.narrow (o,11 BankMgrHome.class);12 } catch (...) {13 // Handle exceptions14 }15 }

Page 330: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 29 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Calling Business Methods

1 public void processRequest (...) {2 try {3 BankMgr bankMgr = bankMgrHome.create();4 // call business methods on bankMgr5 bankMgr.remove()6 } catch (...) {7 // Handle exceptions8 }9 }

Page 331: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 10, slide 30 of 30Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• The servlet API• The request and response APIs• Forwarding control and passing data• The session management API• Calling EJB components from servlets

Page 332: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 11

Developing With JavaServer Pages™Technology

Page 333: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 2 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Evaluate the role of JSP technology as a presentationmechanism

• Author JSP pages• Process data received from servlets in a JSP page• Describe the use of custom tag libraries

Page 334: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 3 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

JSP Technology as a PresentationMechanism

JSP pages are text-based documents that describe how toprocess a request and create a response.

• Using JSP technology, a page designer creates adocument to generate dynamic content.

• JSP elements:• Enable external object access• Add canned programming capabilities

• Source files for JSP pages typically end with the .jspextension.

Page 335: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 4 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

JSP Technology as a PresentationMechanism

JSP technology:

• Uses beans to interact with server-side objects• Uses tag libraries to develop and extend the canned

capabilities provided by actions• Allows for a high degree of separation between the

static and dynamic content in a JSP page• Provides (where necessary) a powerful scripting

language for JSP pages• Is an integral part of the J2EE platform, and so provides

front-end access to EJB components

Page 336: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 5 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Presentation Using JSP Pages Comparedto Servlets

JSP pages are web components that are based on the servletmodel and that run as servlets:

Characteristic JSP Servlets

Request andresponse model

Same model

Use of markuplanguage

Yes, similar to HTML No, uses println statements

Runtime Have similar runtime benefits over other scripting tools suchas CGI

Page 337: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 6 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Presentation Using JSP Pages ComparedTo Servlets

Characteristic JSP Servlets

Capabilities Similar to other dynamiccontent technologies

Generated HTML response isstatic text created by printlnstatements

Automaticrecompilation

Yes No

Developer skills JSP pages can be authored bynon-software developers

Servlets are authored bysoftware developers

Debugging Quicker and easier to debuglayout and presentationproblems

More difficult to debug

Page 338: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 7 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

JSP Page Deployment Mechanism

JSP pages:

• Are translated into servlets on demand• Can be deployed in the same manner as an HTML

page, by copying the file onto the server

Page 339: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 8 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

JSP Page Translation Procedure

<%

%>

JSP Container

jsp_servlets

Internet

Web Client

Request The JSP page was not previously accessedor has been modified

Yes

No

Transform

CompileWeb Client

Web Client

JSPPage

21

34

Page 340: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 9 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Java Code Embedded in JSP Pages

Ideally, a JSP page should be concerned with presentationlogic only. A servlet is a better alternative for processing logicand for flow control. Using scripting code for processing logicand flow control within a JSP page results in problems thatinclude:

• A JSP page author:• Must code well in the scripting language• Might need more business domain knowledge

• It is more difficult to see presentation informationwhen you view the JSP page.

• Debugging is more difficult because of the addedcomplexity and decreased clarity.

Page 341: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 10 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Authoring JSP Pages

A JSP page contains:

• Standard markup tags, such as HTML or XML• Associated text data• A variety of elements that are defined by the JSP

specification

Page 342: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 11 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

JSP Page Components

<%

%>

Directives

Implicit Objects

Actions

while (it.hasNext()) {...

Scripting Elements

HTML/XML

Markup

JSP Page

Page 343: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 12 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Syntactic Forms of JSP Tags

Syntactic forms of tags based on JSP tags can be representedin two different ways:

Old Syntax – Similar toother tag-based dynamicpresentation technologies

XML Syntax – With beginning andend tags

<%! ... %> <jsp:declaration> ...</jsp:declaration>

<%= ... %> <jsp:expression> ...</jsp:expression>

<% ... %> <jsp:scriptlet> ...</jsp:scriptlet>

<%@ ... %> <jsp:directive.type ... />

Page 344: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 13 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

JSP Technology Directives

• Contain information to help a JSP container configureand run a JSP page

• Are associated with the compiled servlet that is createdfrom the JSP page

• Do not produce output• Have the following generic syntax:

<%@ directive attribute="value" ... %>

Page 345: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 14 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

JSP Directives

<%

%>

JSP Page

Compile

Run

JSP Containerimport="java.util.*, bank.*"

page

file="StatementHeader.jsp"

include

uri="http://www.XXX" prefix="bank"

taglib

Page 346: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 15 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The pageDirective

The page directive defines page-dependent attributes:

• An attribute and value pair cannot be redefined withina translation unit, with the exception of the includepage directive.

• Redefining a pagedirective results in a fatal translationerror.

Page 347: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 16 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The pageDirective

Examples using both styles of syntax:

<%@ page import="java.util.*, java.lang.*" %>

<%@ page buffer="5kb" autoFlush="false" %>

<jsp:directive.page errorPage="error.jsp" />

Page 348: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 17 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

JSP pageDirectives

<%

%>

isErrorPage="true"

language="Java"

errorPage="LoginError.jsp"

import="java.util.*,bank.*"

session="false"

isThreadSafe="true"

info="Banking App V1.1"

autoFlush="false"

buffer="none"

JSPPage

Page 349: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 18 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The includeDirective

The include directive:

• Inserts the text of the specified resource into the .jspfile at page translation time

• Treats resources as static objects• Can be other HTML files or other JSP pages that contain

text, or code, or both

Examples of the include directive:

<%@ include file="relativeURL" %>

Or

<jsp:directive.include file="relativeURL" />

Page 350: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 19 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The includeDirective

<%

%>

<HTML>

</HTML>

Compile

JSP Container

StmtHdr.html

statement.jsp

<%@ includefile="StmtHdr.html"%>

<tr>

<td><b>Date</b></td>

<td><b>Check</b></td>

<td><b>Description</b></td>

<td><b>Amount</b></td>

</tr>

include

Servlet

Page 351: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 20 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Declarations, Expressions, and Scriptlets

Scripting elements allow a page designer to provideadvanced programming capabilities. Scripting elementsinclude:

• Declarations• Expressions• Scriptlets

Page 352: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 21 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Declarations, Expressions, and Scriptlets

Declarations Expressions Scriptlets

Use To declareinstance-scopevariables and methods

To retrieve values ofpage variables,methods, or bean fields

To embed snippetsof scripting code

Syntaxrequirement

Code that must:• Conform to the

scripting languagesyntax

• Form declarativestatements

Any legal expression inthe scripting language

Raw blocks ofprogram code thatuse Java as thedefault scriptinglanguage

Description

• Are associated withthe body of thecompiled servlet

• Do not produceoutput

Are evaluated by theJSP container atruntime, with resultsconverted to a Stringobject on the page

• Are inserted intothe generatedservlet withoutmodification

• Use sparingly

Page 353: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 22 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Declaration Scripting Elements

Syntax Alternate Syntax

<%! declaration(s) %> <jsp:declaration>declaration(s)</jsp:declaration>

Example<! final String SHOWDETALS_URL = "/showdetails.jsp" >boolean hasAccounts(Customer c) { return !c.getAccounts().isEmpty(); } ><jsp:declaration> // This instance variable is assigned at initialization time protected BankMgr bankMgr = null;</jsp:declaration>

Page 354: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 23 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Expression Scripting Elements

Syntax Alternate Syntax<%=expression %> <jsp:expression>

expression</jsp:expression>

Examples<td> <%=acct.getBalance()%> </td>

Or

<td><jsp:expression>acct.getBalance()</jsp:expression></td>

Page 355: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 24 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Scriptlet Scripting Elements

Syntax Alternate Syntax<% code_segment %> <jsp:scriptlet>

code_segment</jsp:scriptlet>

Example1 <%2 if (isAllowedTransaction() == false) { url=ScreenMgr.BANK_ERRORPAGE; }3 else {4 Vector checkList = account.getCheckByAmount(amt);5 Iterator it = checkList.iterator();6 double totalCheckAmount = 0.00;7 while (it.hasNext()) {8 Check chk = (Check) it.next();9 totalCheckAmount += chk.amount();10 } // end while11 } // end if/else12 %>

Page 356: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 25 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Scriptlet Scripting Elements

Example1 <%2 Check chk;3 while (it.hasNext()) {4 chk = (Check)it.next();5 // end of first code fragment6 %>7 <%-- output check amount using HTML --%>8 <br> Check Amount: <%=chk.getAmount()%> </br>9 <%10 } // closing bracket for while loop11 // end of second code fragment12 %>

Translates to:

1 Check chk;2 while (it.hasNext()) {3 chk = (Check)it.next();4 // end of first code fragment5 out.write("\t\t<br> Check Amount: ");6 out.print(chk.getAmount());7 out.write(" </br>\r\n");8 out.write("");9 } // closing bracket for while loop10 // end of second code fragment

Page 357: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 26 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Thread-Safety Implications

Declarations occur at the instance level of the generatedservlet. Therefore:

• All requests to the JSP page share these variables andmethods.

• Thread-safety problems can occur with this technique.All of the cautions that apply to servlets andthread-safety, apply to JSP page declarations.

Page 358: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 27 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Processing Data From Servlets

The JSP specification defines a standard set of action types thatall JSP containers must implement, including:

• Create or use beans• Set and get bean properties• Include static and dynamic resources in the current

page’s context

You can define additional action types using custom taglibraries.

Page 359: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 28 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The jsp:useBeanAction

• Creates or locates a bean instance• Associates the bean instance with a scope and action ID• Makes the ID accessible by scripting elements and

custom tags• First attempts to locate an existing bean that matches

the criteria in the tag

Page 360: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 29 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The jsp:useBeanAction

Syntax of jsp:usebean:

<jsp:useBean id="name" scope="scope" typeSpec />

Alternate syntax with initialization code:

<jsp:useBean id="name" scope="scope" typeSpec > <% ...initialization code... %></jsp:useBean>

Page 361: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 30 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The jsp:useBeanAction

<%

%>

Scope

useBean

class

JSP Page

2

3

1

<jsp:useBean id= "customer" scope= "session"

class= "bank.Customer" >

<% customer.init(pageContext.getSession()) %>

</jsp:useBean>

Page 362: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 31 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The jsp:useBeanAction

This graphic shows the id attribute.

<%

%>

Session

JSP Page<%

Vector checkList = account.getCheckByAmount(amt);if (checkList != null) { Iterator it = checkList.iterator(); double totalCheckAmount = 0.00; while (it.hasNext()) { ...%>

<jsp:useBean id="account" scope="session"

class="bank.Account"/>

idattribute value

Page 363: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 32 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The jsp:useBeanAction

Examples of jsp:useBean:

• Usage example for the id attribute:<jsp:useBean id="account" class="bank.Account"/>

• To retrieve the account balance, use the expression:<%=account.getBalance() %>

Page 364: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 33 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The jsp:useBeanScopes

%> %>

%>

%>%> %>

%>

%>

JSPPa

HttpSessionsession scope

PageContext

page scope

request

request scope

JSPPage

JSPPage

JSPPage

JSPPage

JSPPages

ServletContext

application scope

JSP Container

JSPPage

JSPPage

JSPPage

JSPPage

Page 365: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 34 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Request-Scope Beans and Collecting DataFrom Servlets

The jsp:useBean action is commonly used to share databetween servlets and JSP pages:

• Servlets often perform front-end processing and thendispatch to a JSP page to display dynamic data.

• You set an attribute on the request object in the servlet.• You use jsp:useBean with the request scope

attribute to collect the data.

Page 366: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 35 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Request-Scope Beans and Collecting DataFrom Servlets

The following code snippet creates a new bank.Customerobject and saves it in a request attribute named customer:

1 public void doPost (HttpServletRequest request, HttpServletResponseresponse) {2 ...3 try {4 bank.Customer cust = new bank.Customer(firstName, lastName);5 request.setAttribute("customer", cust);67 // use a request dispatcher to forward to a JSP page8 getServletConfig().getServletContext().getRequestDispatcher("/jsp/example.jsp").forward(request, response);9 } catch (Exception ex) {10 . . .11 } // end catch12 }

Page 367: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 36 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Request-Scope Beans and Collecting DataFrom Servlets

The JSP page example.jsp that is illustrated in the followingcode snippet can then access and process the customer objectas follows:

1 <jsp:useBean id="customer" class="bank.Customer" scope="request"/>2 ...3 <jsp:getProperty name="customer" property="firstName" />4 <jsp:getProperty name="customer" property="lastName" />5 ...

Page 368: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 37 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The jsp:getPropertyAction

<jsp:getProperty name= "account" property= "cardNo" />

getProperty

JSP Page

account

fName : JameslName : Smithaddress : 1234 Way St.city : Seatlestate : WAphone : (555) 555-1212cardNo : 1234-28

1234-28

Page 369: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 38 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Custom Tag Libraries

• Provide an alternative to scriptlets for customizing JSPpages for specific business needsIt is preferable to avoid scriptlet code in JSP pages.

• Use an XML-style tag format to provide cannedcapabilities to use, modify, or create objects

Page 370: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 39 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The taglibDirective

• Extends the set of tags that a JSP container can interpret• Associates a tag prefix with a tag library that:

• Consists of a set of classes and a tag librarydescriptor

• Implements the range of operations defined in thetags

Page 371: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 40 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The taglibDirective

Format of the taglib directive:

<%@ taglib uri="iterator_tags" prefix="iterator" %>

URI mapping in deployment descriptor:

<taglib><taglib-uri>iterator_tags</taglib-uri><taglib-location>/WEB-INF/iterator_1_0.tld

</taglib-location></taglib>

Custom tag library usage:

<iterator:loop><%-- perform repetitive task --%>...

</iterator:loop>

Page 372: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 41 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The tag-libraryDescriptor and JavaClasses

• The URI mapping in the web application deploymentdescriptor maps a prefix to a TLD.

• The TLD is an XML file, which is usually packaged inthe web application, along with the classes thatimplement its range of operations.

Page 373: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 42 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

The tag-libraryDescriptor and JavaClasses

Mapping example:

• In the JSP page:<iterator:iterate id=”accounts”>

• Information from the TLD:1 <tag>2 <name>iterate</name>3 <tagclass>4 com.acme.tags.IteratorTag5 </tagclass>6 <attribute>7 <name>id</name>8 <required>true</required>9 </attribute>10 </tag>

Page 374: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 11, slide 43 of 43Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• JSP technology as a presentation mechanism• The creation of JSP pages• Data processing in JSP pages• Custom tag libraries

Page 375: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 12

Using Web-Tier Design Patterns

Page 376: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 2 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Manage complexity in the web tier• Define the Model-View-Controller design paradigm• Use the Service-to-Worker, Dispatcher View, and

Business Delegate patterns to provide a web-tierframework

Page 377: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 3 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Problems With Web-Tier Development

The complexities of web-based user interface developmentinclude:

• Addressing HTTP’s stateless request-responsesequence

• Avoiding the creation of large numbers of servlets andJSP components that handle different types of requests

• Using JSP components and servlets effectively

Page 378: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 4 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Worker Beans and Custom Tags

You can separate programmatic functionality frompresentation in JSP components in two ways:

• Incorporate classes with the <jsp:useBean> tag:• Useful for carrying data into the JSP component• Prone to tight coupling when used for application

logic• Make use of custom tag libraries:

• Most valuable when tag libraries aregeneral-purpose and reusable

• Less useful for application-specific logic, such asform processing

Page 379: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 5 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Model 1 and Model 2 Architectures

Two design strategies are involved in using JSP componentsin the web tier:

• Model 1 architecture:• JSP components handle request processing through

<jsp:useBean> classes and custom tags.• JSP components render data that is retrieved from

the business logic tier.• Model 2 architecture:

• Servlets handle request processing, interact with thebusiness logic, and collect data for display.

• JSP components render the data for display.

Page 380: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 6 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Traditional MVC Architecture

Sends events

Selects view

Renders data

Updates model

Notifies changes

Model

View Controller

Page 381: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 7 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Model 2 Architecture as MVC

<%

%>

<%

%>

<%

%>

Model Classes or Components

Selects view

Sends event

Render data

Updates model

Notifies changes

ControllerServlet

View JSPComponents

Page 382: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 8 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

MVC in the J2EE Platform

The MVC paradigm divides application logic into three roles:

• Controller• View• Model

• When the application includes EJB components• When there are no EJB components

Page 383: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 9 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Using Web-Tier Design Patterns

The web-tier developer needs to work with specific designpatterns that realize the broad, architectural paradigms ofMVC and Model 2 architecture.

Of the many available patterns, this module considers threespecific patterns, which can be used in combination:

• Service-to-Worker• Dispatcher View• Business Delegate

Page 384: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 10 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Service-to-Worker and Dispatcher ViewPatterns

<%%>

<%%>

<%%>

View JSPComponents

Controller

2

3

4

5 4a

1

Page 385: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 11 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Web-Tier Design Framework Construction

The Service-to-Worker and Dispatcher View patterns providegeneric functionality that can be extracted to form a designframework.

• Each request is handled in the same generic way, withvariations for the specific needs of the application.

• The controller element is the most generic, allowingreuse in different applications.

• The controller’s functionality can be expresseddeclaratively, rather than in code.

Page 386: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 12 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Some Available Web-Tier Frameworks

Commonly used frameworks include:

• Sun ONE Application Framework products or JATO• Struts• JavaServer™ Faces technology• Java Pet Store demo software WAF

Page 387: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 13 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Business Delegate Pattern

<%

%>

Web

Tier

Business

Logic Tier

class

BankMgrDelegate BankMgr

Controller

Page 388: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 12, slide 14 of 14Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• Complexity in the web tier• The Model-View-Controller design pattern• The Service-to-Worker, Dispatcher View, and Business

Delegate patterns

Page 389: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 13

Implementing a Transaction Policy

Page 390: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 2 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Describe transaction semantics• Compare programmatic and declarative transaction

scoping• Use JTA to scope transactions programmatically• Implement a container-managed transaction policy• Predict the effect of transaction scope on application

performance• Describe the effect of exceptions on transaction state

Page 391: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 3 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Transaction Semantics

Three transaction concepts are important in the developmentof J2EE platform-compliant applications:

• Atomicity – Operations succeed or fail together• Locking and isolation – Only one transaction at a time

can update a particular piece of data• Flat transaction model – Only one transaction is in

effect in a particular thread at any given time

Page 392: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 4 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Atomicity

$$ $$

$$

$$Account1 Account2

Account2

Account1

BEGIN

COMMIT

Page 393: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 5 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Locking and Isolation

$$

Wait

Account1

3

1 2

Page 394: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 6 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Transaction Models

There are three types of transaction management models:

TransactionModel Type

Description

Nested A transaction consists of subtransactions that run in parallel.

Chained A transaction consists of subtransactions that run in sequence.

Flat A transaction cannot be made up of subtransactions.The flat transaction model:• Is the only transaction model supported by the J2EE

specification• Is supported by all database vendors• Leads to a very simple API

Page 395: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 7 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Comparison of Programmatic andDeclarative Transactions

The J2EE application developer’s concern is with scopingtransactions. Scoping can be programmatic (bean-managedtransactions) or declarative (container-managedtransactions).

Programmatic Declarative

OperationUse JTA calls to specify whichoperations form a singletransaction

Specify the transactionproperties in the deploymentdescriptor

AvailableIn

Servlets, JSP components,session beans, andmessage-driven beans, but notin entity beans

Session beans, message-drivenbeans, and entity beans, but notin servlets or JSP components

Page 396: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 8 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Using JTA to Scope TransactionsProgrammatically

The JTA specification is relevant to developers of applicationservers and database drivers. The code is independent of thetransaction infrastructure.

• Obtain a reference to the UserTransaction objectfrom the container

• Scope the transactions using the begin and commitmethods

• Fail a transaction using the rollback method

Page 397: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 9 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Getting a Reference to theUserTransaction Interface

• In a web component:import javax.transaction.UserTransaction;InitialContext ic = new InitialContext();UserTransaction ut =

(UserTransaction) ic.lookup(“java:comp/UserTransaction”);

• In a session bean:import javax.transaction.UserTransaction;public void setSessionContext (SessionContext sc) {

this.sc = sc;}//...UserTransaction ut = sc.getUserTransaction();

Page 398: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 10 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Using the begin, commit, and rollbackMethods

Most uses of JTA to scope a transaction have the followingbasic structure:

try {ut.begin(); // Transaction starts here

//... transaction operation 1//... transaction operation 2//...

ut.commit(); // Transaction finishes here

} catch (Exception e) {ut.rollback(); // Oops: roll back

}

Page 399: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 11 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Effect of Programmatic Scoping onReusability

Programmatic transaction scoping is not preferred for EJBcomponents for two main reasons:

• Transaction scope cannot be changed at assembly time.• The container cannot create a single transaction that

encompasses a mixture of programmatic anddeclarative transaction scoping.

Declarative scoping avoids these problems.

Page 400: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 12 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Implementing a Container-ManagedTransaction Policy

Declarative or container-managed transaction scoping is thetechnique of choice in EJB components.

• No coding is necessary, but the transaction scope isaffected by the number and sequence of method calls.

• In many cases, you are only required to set all of themethods of all EJB components to have the Requirestransaction attribute.

Page 401: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 13 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

How the Container Interacts With theTransaction Management Infrastructure

<XML>

$$

Database

TransactionCoordinator

3

5

4

6

1

EJB Container

Suspend/Join/BeginCommit/Rollback/Resume

2

Page 402: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 14 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

How to Control the Container’s BehaviorUsing Transaction Attributes

Attribute Effect

Required The method becomes part of the caller’s transaction. If thecaller does not have a transaction, the method runs in its owntransaction.

RequiresNew The method always runs in its own transaction. Any existingtransaction is suspended.

NotSupported The method never runs in a transaction. Any existingtransaction is suspended.

Supports The method becomes part of the caller’s transaction if there isone. If the caller does not have a transaction, the method doesnot run in a transaction.

Mandatory It is an error to call this method outside of a transaction.

Never It is an error to call this method in a transaction.

Page 403: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 15 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Predicting the Effect of Transaction Scopeon Application Performance

Transaction scope has two conflicting effects on performancethat you have to balance:

• Wider scope reduces the need for entity beansynchronization

• Narrower scope increases database concurrency

Page 404: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 16 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Transaction Scope and Entity BeanSynchronization

The entity bean must be synchronized with the underlyingdatabase once per transaction.

• The container assumes that the database is locked bythe current transaction.

• The container makes only one call to the ejbLoadmethod and to the ejbStore method per transaction.

Page 405: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 17 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Transaction Scope and DatabaseConcurrency

Problem:

Widening transaction scope leads to decreased databaseconcurrency. When data is locked by another transaction, anythread that needs to update that data is blocked. Databasethroughput can be compromised when many threads areblocked.

Page 406: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 18 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Transaction Scope and DatabaseConcurrency

Solution:

You get a good compromise between these conflicting needsby:

• Setting the transaction attributes to Required for allmethods

• Ensuring that methods that are exposed by thebusiness logic to its clients are coarse-grained

Page 407: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 19 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Effect of Exceptions on Transaction State

Exception handling differs in programmatic and declarativetransaction scoping.

• With programmatic transaction scoping, you areresponsible for catching exceptions and failingtransactions.

• With declarative transaction scoping:• The container automatically fails the current

transaction if it catches a runtime exception.• An EJB component can use the EntityContext

object or an equivalent object to check whether thecontainer has failed a transaction.

Page 408: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 13, slide 20 of 20Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• Transaction semantics• Programmatic and declarative transaction scoping• The JTA API• Container-managed transactions• Transaction scope and application performance• The effect of exceptions on transaction state

Page 409: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform

Module 14

Implementing a Security Policy

Page 410: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 2 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Objectives

After successful completion of this module, you should beable to:

• Exploit container-managed security• Define user roles and responsibilities• Create a role-based security policy• Use the security API• Configure authentication in the web tier

Page 411: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 3 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Exploiting Container-Managed Security

The J2EE platform specification defines an end-to-end,container-managed, role-based, vendor-neutral security model.Your main task is to define roles and create the declarativesecurity policy.

• The security API relies on the container-managedsecurity model.

• The use of the security model in the J2EE platform isall-or-nothing.For example, you cannot code authentication andalso declaratively specify authorization.

Page 412: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 4 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Security Concepts

• Authentication – Establishing that the user’s claimedidentity is genuine

• Authorization – Establishing that the user is allowed tocarry out the requested action

• Confidentiality – Protecting data from unauthorizedviewing during communication

• Integrity – Ensuring that the data received is the sameas the data sent

Page 413: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 5 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

End-to-End Security Model

J2EE Security Domain

J2EE Security Domain

Browser

Controller

Application

Account

Customer

BankMgr

Page 414: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 6 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Container-Managed Security

The security model in the J2EE platform is primarily anauthorization model.

• If necessary, the container authenticates the client.• The container checks a client’s rights to carry out the

requested action on a component.• After authorization is complete, the container invokes

application code.

EJB ContainerWeb Container

Page 415: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 7 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Container-Managed Authentication

When you use container-managed authentication, thecontainers and the server infrastructure implementauthentication procedures for login or certificate exchange.

Authentication considerations include:

• Authentication in the web tier• Web-tier authentication challenge methods• Authentication from the web tier to the EJB tier• Authentication of non-web clients• Interaction with the security infrastructure

Page 416: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 8 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Authentication in the Web Tier

Is resourcerestricted?

Is the sessionauthenticated?

User credentialsaccepted?

Deliver challenge

Deliver requestedresource

(Authorization)

No

No

No

Yes

Yes

Yes

Page 417: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 9 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Web-Tier Authentication ChallengeMethods

• HTTP basic – The web browser prompts the user for auser name and password, and supplies thisinformation in the request header.

• Client certificate – The client presents the user’s digitalcertificate in response to a challenge from the server.

• Form-based – The developer controls the look and feel ofthe authentication process by supplying HTML forms.

Page 418: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 10 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Basic Authentication Dialog Box

Page 419: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 11 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Authentication From the Web Tier to theEJB Tier

You should not attempt to supply authentication credentialsto the EJB tier in code. Authentication is passed from the webtier to the EJB tier as follows:

• A client of an EJB component must pass a verifiablesecurity context with each method call that allows theuser to be identified.

• When the client is a web component in the sameapplication as the EJB component, it is the webcontainer’s responsibility to pass the user credentials tothe EJB container.

Page 420: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 12 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Authentication of Non-Web Clients

For standalone clients that are implemented in the Javaprogramming language:

• Consider using an application client container• Remember that authentication remains the

responsibility of the container• Explore the possibility of customizing the look and feel

of the login procedure

Page 421: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 13 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Authentication of Non-Web Clients

For clients that are not implemented in the Java programminglanguage:

• The client can use IIOP API calls directly to supply thesecurity context.

• It has only been possible to use IIOP API calls portablysince the introduction of the CSIv2 protocol.

Page 422: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 14 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Interaction With the Security Infrastructure

• Remember, the security model in the J2EE platform isvendor-neutral and platform-independent.

• User credentials and permissions are stored in variousways, such as directory servers and relational databasetables.

• The application server interacts with the securityinfrastructure. Applications cannot do this without lossof portability.

• The range of security infrastructures supported by theapplication server can be extended by the use of JAASmodules.

Page 423: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 15 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

User Roles and Responsibilities

A role is an abstraction of a set of user authorizationprivileges:

• Users in the same role have broadly similar rights andresponsibilities.

• The role structure of the security model in the J2EEplatform is flat, not hierarchical.

• Individual users can, and often will, occupy more thanone role.

• There is some correspondence between a role and agroup in many security infrastructures, but themapping of real users or groups to roles isplatform-specific.

Page 424: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 16 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Role-Based J2EE Security Model

Gerald

Platform-Specific Security Infrastructure

J2EE Security Domain

Vanessa

Manager

Customer

ShowAccount

CreateAccount

Erin

Page 425: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 17 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

End-to-End Roles

Roles are typically defined for the application:

• Roles are subsequently applied in the web tier and theEJB tier.

• It is easier to ensure security when roles are consistentacross the application.

Page 426: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 18 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Creating a Role-Based Security Policy

Creating an end-to-end, role-based security policy is afour-step procedure:

1. Elucidate the roles.2. Assign roles to URL patterns in the web tier by

editing the web.xml file or by using an IDE.3. Assign roles to methods in the EJB tier by editing the

ejb-jar.xml file or by using an IDE.4. Expose the roles you have used by editing the

application.xml file or by using an IDE.

Page 427: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 19 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Role-Based Authorization in the Web Tier

<XML>

Web Container

23

41

http://server/bank/ShowAccount

CustomerSession Store

Page 428: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 20 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Role-Based Authorization in the EJB Tier

EJB Container

<XML>

23

41

BankMgr.getAccount()

Customer

Protocol SecurityContext

Page 429: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 21 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Using the Security API

The security API is only available to applications that usecontainer-managed authentication. The API provides twobasic facilities that you can use to determine identity and roleallocation.

Method Calls to DetermineUser or Client Identity

Method Calls to DetermineUser Role Allocations

Web Tier getUserPrincipal isUserInRole

EJB Tier getCallerPrincipal isCallerInRole

Page 430: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 22 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Web-Tier Security API

String user = request.getUserPrincipal().getName();String message ="Welcome to the on-line bank, " + user;

if (request.isUserInRole("manager")) {//... show manager menu}

In this example, manager is a role reference, not a role.

Page 431: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 23 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

EJB-Tier Security API

EJB component context object saved in an instance variable:

// In the BankMgr EJB...

public void setSessionContext(SessionContext sc) {this.sc = sc;

}

public Collection getMyAccounts() {String user = sc.getCallerPrincipal().getName();return getAccountsByUser (user);

}

Page 432: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 24 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Configuring Authentication in the Web Tier

Web-tier authentication is a complex topic. This courseaddresses only:

• Selecting the authentication type• Creating an HTML log-in page for form-based

authentication

Page 433: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 25 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Selecting the Authentication Type

Each of the three types of web tier authentication that arerecognized by the J2EE platform specification has its ownconfiguration requirements.

Authentication Method Configuration Requirements

HTTP basic Specify this type in the web.xml deploymentdescriptor

Client certificate • Specify this type of authentication in web.xml• Configure the web container’s certificate database

and assign trust levels per vendor instructions

Form-based • Specify this type in web.xml• Create and package the login page and error page• Specify names of these pages in web.xml

Page 434: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 26 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Creating an HTML Login Page forForm-Based Authentication

Minimal section of HTML:

<form action=”j_security_check” method=”post”>

<-- layout code not shown for clarity -->

Username:<input name=”j_username”/><br/>Password:<input name=”j_password” type=”password”/><br/>

<input type=”submit” name=”submit” value=”Log in”/>

</form>

Page 435: FJ-310 - Javapradeepjava.weebly.com/uploads/5/8/2/8/582894/fj310_oh.pdf · Sun Services Developing Applications for the J2EE™ Platform Developing Applications for the J2EE™ Platform

Sun Services

Developing Applications for the J2EE™ Platform Module 14, slide 27 of 27Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D.3

Summary

The following topics were presented in this module:

• Container-managed security• User roles and responsibilities• Role-based security policies• The security API• Configuration of authentication in the web tier