ejb lecture

Upload: jignesh-prajapati

Post on 04-Jun-2018

237 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/13/2019 EJB Lecture

    1/33

    Page 1, 5-Nov-03Component Technologies

    EJB

    Enterprise Java BeansEnterprise Java Beans

    Mikael kerholm

    Page 2, 5-Nov-03Component Technologies

    EJB

    LectureLecture StuctureStucture

    Introduction1. Java

    2. JavaBeans

    3. J2EE

    J2EE1. EJB

    2. Java Serverlets, JSP, and clients

    3. Packaging and Deployment

    Summary, Questions

  • 8/13/2019 EJB Lecture

    2/33

    Page 3, 5-Nov-03Component Technologies

    EJB

    ReferencesReferences

    Literature:Enterprise JavaBeans, R.M. Haefel, 3rd OReilly 2001

    The Source for Java Technology, good, up to date,tutorials, specifications, and reference implementations

    http://java.sun.com/

    Page 4, 5-Nov-03Component Technologies

    EJB

    JavaJava

    The current main release is the Java 2 platform, it ismodular and include three parts:

    J2SE, Java 2 Platform, Standard Editionprovides the essential compiler, tools, runtimes, and APIs for writing,deploying, and running applets and applications

    J2EE, Java 2 Platform, Enterprise Editioncomponent based model, simplifies enterprise development anddeployment; manages the infrastructure and supports the web services toenable development business applications

    J2ME, Java 2 Platform, Micro Editiona highly optimized Java runtime environment, specifically addresses thevast consumer space (embedded systems), from smart cards to more PClike applications

  • 8/13/2019 EJB Lecture

    3/33

  • 8/13/2019 EJB Lecture

    4/33

    Page 7, 5-Nov-03Component Technologies

    EJB

    Java 2 Enterprise Edition (J2EE)Java 2 Enterprise Edition (J2EE)

    For enterprise applications (distributed businessapplications)

    Demands Availability

    Security

    Reliability

    Scalability

    From the early 90sShift from 2-tier, client-server application models to more flexible 3-tier (and n-tier)application models

    The new models separated business logic from system services and the user interface

    Page 8, 5-Nov-03Component Technologies

    EJB

    Java 2 Enterprise Edition (J2EE)Java 2 Enterprise Edition (J2EE)

    DatabaseDatabase

    Tier Boundary

    Business

    logic

    Business

    logic

    Databasedriver

    Databasedriver

    Business

    logic

    Business

    logic

    PresentationPresentation

    Data tier

    Business tier

    Tier Boundary

    Presentation tier

  • 8/13/2019 EJB Lecture

    5/33

    Page 9, 5-Nov-03Component Technologies

    EJB

    Java 2 Enterprise Edition (J2EE)Java 2 Enterprise Edition (J2EE)

    Page 10, 5-Nov-03Component Technologies

    EJB

    Java 2 Enterprise Edition (J2EE)Java 2 Enterprise Edition (J2EE)

    J2EE Application Programming Model Applications on the client

    Java Server Pages (JSP), web components on the server,extension of Serverlets; in the end these are concerned withclients

    EJB, business components on the server side

  • 8/13/2019 EJB Lecture

    6/33

    Page 11, 5-Nov-03Component Technologies

    EJB

    EnterpriseEnterprise JavaBeanJavaBean (EJB)(EJB)

    Javas component model for distributed enterpriseapplications, released 1998

    EJB technology defines a model for the development ofreusable Java server componentsDef:

    Enterprise Java Beans is a standard server-side componentfor computer transaction monitors.

    Applications written using EJB are:Scalable

    Transactional

    Multi-User secure

    Page 12, 5-Nov-03Component Technologies

    EJB

    EJB != JBEJB != JB

    Once and for allJB

    Desktop Components

    EJBEnterprise Distributed Components

    Could of course be implemented using JavaBeans

  • 8/13/2019 EJB Lecture

    7/33

    Page 13, 5-Nov-03Component Technologies

    EJB

    J2EEJ2EE

    Page 14, 5-Nov-03Component Technologies

    EJB

    ContentsContents

    1. EJB ComponentsGeneral

    Interfaces and classes

    Architechture

    Different types

    Transactions

    2. Java Serverlets, JSP and clientsBrief

    3. Packaging and DeploymentBrief

  • 8/13/2019 EJB Lecture

    8/33

    Page 15, 5-Nov-03Component Technologies

    EJB

    What is an EnterpriseWhat is an Enterprise JavaBeanJavaBean ??

    A server-side component thatencapsulates the business logic of anapplication

    Page 16, 5-Nov-03Component Technologies

    EJB

    When to use Enterprise JavaBeansWhen to use Enterprise JavaBeans

    If any of these requirements hold for yourapplication:

    The application must be scalable anddistributable

    Transactions are required to ensure dataintegrity

    The application will have a variety of clients

  • 8/13/2019 EJB Lecture

    9/33

    Page 17, 5-Nov-03Component Technologies

    EJB

    Enterprise JavaBeansEnterprise JavaBeans

    Entity Beans

    Persistent

    Primary key

    Session Beans

    Receive their state from the client

    Live as long as the client need them

    Message-Driven Beans (EJB 2.0)

    Asynchronously

    Only a bean class no interfaces

    Page 18, 5-Nov-03Component Technologies

    EJB

    Classes and InterfacesClasses and Interfaces

    Remote Interface

    Specifies the beans business methods

    Home Interface

    Defines the beans life cycle methods

    Bean Class

    Implements the beans business methods

    Primary Key

    Provides a pointer into the database

  • 8/13/2019 EJB Lecture

    10/33

    Page 19, 5-Nov-03Component Technologies

    EJB

    A Beans interfacesA Beans interfaces

    Remote InterfaceBusiness methods to do the beans work

    Implemented by the shadowdy Bean Object

    Remote Home InterfaceDefines the beans life cycle methods

    Implemented by EJB Home

    Local Interface (EJB 2.0)Business methods used by other beans in the samecontainer

    Local Home Interface (EJB 2.0)Life-cycle methods used by other beans in the samecontainer

    Page 20, 5-Nov-03Component Technologies

    EJB

    A Beans classesA Beans classes

    The Bean ClassImplement the business methods

    Do not implement Remote (or local) and (local) HomeInterfaces

    Beans exist in the middle of client software and datasources

    Clients never interact directly with the bean class, usesmethods of the Remote and Home Interface, interactingwith automatically generated stubs

  • 8/13/2019 EJB Lecture

    11/33

    Page 21, 5-Nov-03Component Technologies

    EJB

    EJB ArchitectureEJB Architecture

    HomeObjectHomeObject

    EJB Server

    BeanClassBeanClass

    EJB Container

    EJB Client

    EJBObjectEJB

    Object

    Home InterfaceHome Interface

    Remote InterfaceRemote Interface

    (or Local Interface)(or Local Interface)

    HomeStub

    HomeStub

    ObjectStub

    ObjectStub

    Page 22, 5-Nov-03Component Technologies

    EJB

    When to use Entity BeansWhen to use Entity Beans

    The bean represents a business entity, not aprocedure

    To provide a safe and consistent interface to a set ofshared data

  • 8/13/2019 EJB Lecture

    12/33

    Page 23, 5-Nov-03Component Technologies

    EJB

    Entity BeansEntity Beans

    Represents a business object in a persistentstorage mechanism

    Can be shared by multiple clients

    Two types of persistence:

    Container-managed

    Bean-managed

    Page 24, 5-Nov-03Component Technologies

    EJB

    Container Container --managed persistencemanaged persistence

    They are the simplest to develop

    The beans code contain no database accesscalls

  • 8/13/2019 EJB Lecture

    13/33

    Page 25, 5-Nov-03Component Technologies

    EJB

    BeanBean --managed persistencemanaged persistence

    Explicitly write persistence logic

    More flexibility in how state is managed betweenthe bean instance and the database

    Used when deployment tools are inadequate

    Page 26, 5-Nov-03Component Technologies

    EJB

    Life CycleLife Cycle

  • 8/13/2019 EJB Lecture

    14/33

    Page 27, 5-Nov-03Component Technologies

    EJB

    When to use Session BeansWhen to use Session Beans

    Only one client has access to the beans instance

    Non persistent and existing only for a short period oftime

    Page 28, 5-Nov-03Component Technologies

    EJB

    Session BeansSession Beans

    Useful for describing interactions

    Does not represent shared data in the database,but can access shared data

    Two types:Stateless

    Stateful

  • 8/13/2019 EJB Lecture

    15/33

    Page 29, 5-Nov-03Component Technologies

    EJB

    Stateless Session BeansStateless Session Beans

    Supports multiple clients

    Relatively easy to develop and very efficient

    Require few server resources

    Stateless session beans are appropriate if:

    The bean's state has no data for a specific client

    A generic task is performed in a single methodinvocation

    The bean fetches a set of read-only data

    Page 30, 5-Nov-03Component Technologies

    EJB

    Life CycleLife Cycle

  • 8/13/2019 EJB Lecture

    16/33

    Page 31, 5-Nov-03Component Technologies

    EJB

    StatefulStateful Session BeansSession Beans

    Dedicated to one client for the life of the beaninstance

    Instance variables represent the state of a uniqueclient-bean session

    Stateful session beans are appropriate if:

    The bean needs to hold information about theclient across method invocations

    The bean mediates between the client and theother components of the application

    Page 32, 5-Nov-03Component Technologies

    EJB

    Life CycleLife Cycle

  • 8/13/2019 EJB Lecture

    17/33

    Page 33, 5-Nov-03Component Technologies

    EJB

    When to use MessageWhen to use Message --Driven BeansDriven Beans

    To receive messages asynchronously

    When consuming JMS messages

    Page 34, 5-Nov-03Component Technologies

    EJB

    MessageMessage --Driven BeansDriven Beans

    Has only a bean class

    Can consume and process messagesconcurrently

    Acts as a JMS message listener Deliver messages to a virtual channel

    Currently process only JMS messages

  • 8/13/2019 EJB Lecture

    18/33

    Page 35, 5-Nov-03Component Technologies

    EJB

    Life CycleLife Cycle

    Page 36, 5-Nov-03Component Technologies

    EJB

    Calling an EJBCalling an EJB

    HomeObjectHomeObject

    EJB Server

    BeanClassBeanClass

    EJB Container

    EJBObjectEJB

    Object

    4 Create EJB Object

    7 Wraps the call to the Bean Class

    EJB Client

    1 Ask for Home object

    2 Returnreferencehome stub

    JNDI

    3 Ask for EJB Object

    5 Return Obj stub

    6 Invoke a method

  • 8/13/2019 EJB Lecture

    19/33

    Page 37, 5-Nov-03Component Technologies

    EJB

    Transactions withTransactions with EJBsEJBs

    Managed automatically

    No use of APIDefined at deployment

    Possible to explicitly manage transactions but notrecommended

    Page 38, 5-Nov-03Component Technologies

    EJB

    A TransactionA Transaction

    Transactions is the execution of a unit-of-work thataccesses on or more resources, usually databasesA unit-of-work is a set of activities that relate to eachother and must be completed together

    The objective with transactions is to execute an unit-ofwork that results in a reliable exchangeTransactions are often complex and usually involvemanipulation of dataTransactions must work perfectly every time or not beexecuted at all

  • 8/13/2019 EJB Lecture

    20/33

    Page 39, 5-Nov-03Component Technologies

    EJB

    AcidAcid--propertiesproperties

    Atomic A transaction must execute completely or not at all

    Consistent A transaction always leads to a correct transformation ofthe system state by preserving the state invariance

    IsolatedThe data a transaction access cannot be affected by anyother parts of the system until the transaction iscompleted

    Durable All the data changes made during the course of

    transaction must be written to a physical storage beforethe transactions is physically completed

    Page 40, 5-Nov-03Component Technologies

    EJB

    Transaction ManagementTransaction Management

    Declarative transaction managementThe transactional behavior controls by usingtransactions attribute in the deployment descriptor

    One of the primary advantages of EJB

    Reduce the complexity for the developers

    Makes it easier to create robust transaction applications

    Explicit transaction managementDifficult to use

    Will not be covered in this talk

  • 8/13/2019 EJB Lecture

    21/33

    Page 41, 5-Nov-03Component Technologies

    EJB

    Transactions AttributeTransactions Attribute You can set the runtime transaction attribute as a XML-attribute in the deployment descriptor by hand, but wewill use a deployment wizardIt is more efficient and easier to use transactionattributes than to control transactions explicitlyIt is possible to set a transaction attribute for the entirebean or to set different transactions attribute forindividual methodsThere exist six transaction attributes in EJB 2.0:

    NotSupported

    Supports

    Required

    RequiresNewMandatory

    Never

    Page 42, 5-Nov-03Component Technologies

    EJB

    The Different Transactions AttributesThe Different Transactions Attributes

    NotSupportedInvoking a method on a bean with this transactionattribute suspends the transactions until the method iscompleted

    SupportsMeans that the bean method will be included in thetransactions scope if it is invoked within a transaction

    RequiredMeans that the bean method must be invoked within thescope of a transaction

  • 8/13/2019 EJB Lecture

    22/33

    Page 43, 5-Nov-03Component Technologies

    EJB

    The Different Attributes, Cont.The Different Attributes, Cont.

    RequiresNewMeans that a new transactions always starts

    MandatoryMeans that the bean method must always be made partof the transaction scope of the calling client

    Never Means that the bean method must never be invokedwithin the scope of a transaction

    Page 44, 5-Nov-03Component Technologies

    EJB

    JavaJava ServerletsServerlets , JSP and clients, JSP and clients

  • 8/13/2019 EJB Lecture

    23/33

    Page 45, 5-Nov-03Component Technologies

    EJB

    ServerletsServerlets

    A serverlet is a server side component, which isdeployed in the same fashion as a EJB

    Used to dynamically create html pages, for clientsSince it is server side, it extends the reach for clients tobackend components (e.g., EJBs) in the server

    A servelet is assigned to handle an access for a specifichtml page

    When the specific page is requsted by a browser, amethod in the servelet is envoked which posts the htmlpage back

    When a client looks at the html code posted from theserver, it looks just like a static html page

    Page 46, 5-Nov-03Component Technologies

    EJB

    JavaServer JavaServer Pages, JSPPages, JSP

    An extension of serverlets, simplifies the creation ofdynamic htmlSimply lets the developer incorporate real java code intoa html page when desired (as a scripting language)

    Is actually compiled to servelets

  • 8/13/2019 EJB Lecture

    24/33

    Page 47, 5-Nov-03Component Technologies

    EJB

    ClientsClients

    Web clients with serverlets or JSP, JSP possibly morepowerful

    Can also create application clients An client side component, that access EJBs

    Easy and straightforward to create, deploted in the samefashion as EJBs

    Page 48, 5-Nov-03Component Technologies

    EJB

    Packaging and DeploymentPackaging and Deployment

  • 8/13/2019 EJB Lecture

    25/33

    Page 49, 5-Nov-03Component Technologies

    EJB

    Deployment and Deploy ToolsDeployment and Deploy Tools

    PackagingCreate JAR files

    A compressed platform-independent file

    Bean and Beans interface and help classes

    Create deployment descriptorsXML files specifying

    Access control

    Bean references

    External Resource references

    Transactional attributes

    DeploymentDeploy the application on a server

    Page 50, 5-Nov-03Component Technologies

    EJB

    PackagingPackaging andand DeploymentDeployment

    Can be done by handGives full control

    Time consuming

    Graphical deplytool with wizards included in thereference implementation

    Easy, fast

  • 8/13/2019 EJB Lecture

    26/33

    Page 51, 5-Nov-03Component Technologies

    EJB

    SummarySummary

    JB != EJBEJBs Typically used for 3 or more tiers bussinessapplicationsEJBs, server side components, with remote and homeinterfaces; packaged in JAR files with deploymentdescriptors

    Session, Entity, Message

    Clients, can be applications or web pages throughservelets or JSP

    Page 52, 5-Nov-03Component Technologies

    EJB

    ExampleExample

    Entity Bean PersonEntity Bean PersonLets look how to build a bean

  • 8/13/2019 EJB Lecture

    27/33

    Page 53, 5-Nov-03Component Technologies

    EJB

    The Remote InterfaceThe Remote Interface

    /**/**Remote InterfaceRemote InterfaceBusiness methods for Person beansBusiness methods for Person beans

    */*/

    importimport javax.ejb.Exceptionjavax.ejb.Exception ;;

    public interface Person extendspublic interface Person extends javax.ejb.EJBObjectjavax.ejb.EJBObject {{StringString getNamegetName () throws() throws RemoteExceptionRemoteException ;;voidvoid setName(StringsetName(String n) throwsn) throws RemoteExceptionRemoteException ;;

    }}

    Page 54, 5-Nov-03Component Technologies

    EJB

    The Home InterfaceThe Home Interface

    /**/**Home InterfaceHome InterfaceLife cycle method for Person beansLife cycle method for Person beans*/*/

    importimport java.rmi.RemoteExceptionjava.rmi.RemoteException ;;importimport javax.ejb.CreateExceptionjavax.ejb.CreateException ;;importimport javax.ejb.FinderExceptionjavax.ejb.FinderException ;;

    public interfacepublic interface PersonHomePersonHome extendsextends javax.ejb.EJBHomejavax.ejb.EJBHome {{

    //responsible for//responsible for initalizinginitalizing an instance of the beanan instance of the beanpublic Personpublic Person create(intcreate(int id)id)

    throwsthrows CreateExceptionCreateException ,, RemoteExceptionRemoteException ;;

    //look up a bean in a DB//look up a bean in a DBpublicpublic findByPK(PersonPKfindByPK(PersonPK pkpk ))

    throwsthrows FinderExceptionFinderException ,, RemoteExceptionRemoteException ;;}}

  • 8/13/2019 EJB Lecture

    28/33

    Page 55, 5-Nov-03Component Technologies

    EJB

    The Bean ClassThe Bean Class/**/**Bean ClassBean ClassImplements the business methods for Person componentImplements the business methods for Person componentPerson Bean is a Entity BeanPerson Bean is a Entity Bean*/*/public classpublic class PersonBeanPersonBean implementsimplements javax.ejb.EntityBeanjavax.ejb.EntityBean {{

    privateprivate intint id;id;private String name;private String name;

    //business methods//business methodspublic Stingpublic Sting getNamegetName () {() {

    return name;return name;}}

    public voidpublic void setName(StringsetName(String n) {n) {name=n;name=n;

    }}

    // continue next slide// continue next slide

    Page 56, 5-Nov-03Component Technologies

    EJB

    // and the bean class continues// and the bean class continues//// ejb.entityejb.entity methodsmethods

    publicpublic PersonPKPersonPK ejbCreate(intejbCreate(int i) {i) {id=i;id=i;return null;return null;

    }}

    public voidpublic void ejbPostCreate(intejbPostCreate(int i) {/*+*/}i) {/*+*/}public voidpublic void ejbSetEntityContext(EntityContextejbSetEntityContext(EntityContext ctxctx ) {}) {}public voidpublic void ejbUnsetEntityContextejbUnsetEntityContext () {/*+*/}() {/*+*/}public voidpublic void ejbActivateejbActivate () {}() {}public voidpublic void ejbPassivateejbPassivate () {}() {}public voidpublic void ejbLoadejbLoad () {/*+*/}() {/*+*/}public voidpublic void ejbStoreejbStore () {/*+*/}() {/*+*/}public voidpublic void ejbRemoveejbRemove () {}() {}

    // + note: session beans do not have these methods// + note: session beans do not have these methods}}

  • 8/13/2019 EJB Lecture

    29/33

    Page 57, 5-Nov-03Component Technologies

    EJB

    ExampleExampleSimple JSP pageSimple JSP page

    How to build a web client

    Page 58, 5-Nov-03Component Technologies

    EJB

  • 8/13/2019 EJB Lecture

    30/33

    Page 59, 5-Nov-03Component Technologies

    EJB

    publicpublic voidvoid jspDestroyjspDestroy () {() {converterconverter == nullnull ;;

    }}%>%>

    0 ) {

    BigDecimalBigDecimal d = newd = new BigDecimalBigDecimal (( amountamount ););%>%>

    Euro.Euro.

    Page 60, 5-Nov-03Component Technologies

    EJB

    ExampleExample

    A deployment descriptor A deployment descriptor Good to understand, when time allows!

  • 8/13/2019 EJB Lecture

    31/33

    Page 61, 5-Nov-03Component Technologies

    EJB

    XML Document Header XML Document Header

    XML documents start with two general information tags:

    1. Specifies the XML version the file use

    2. Specifies the DTD that defines the XML fileProvides the URL to the DTD, you can download it andvalidate the XML file

    Page 62, 5-Nov-03Component Technologies

    EJB

    XML Descriptors BodyXML Descriptors Body

    The Body start with a root element defined by the DTD.The root element describing:

    Bean/ Beans Entity or Session Beans

    Primary KeyEnvironment Entries

    Reference to other Beans

    Reference to External Resources (such as a Database)

    Security Roles

    Bean/Beans Assembly Transactional attributes

    Security roles & Method permissions

  • 8/13/2019 EJB Lecture

    32/33

    Page 63, 5-Nov-03Component Technologies

    EJB

    XML Body exampleXML Body example

    a body examplea body example

    -- -- --

    -- -- --

    -- -- --

    -- -- --

    Page 64, 5-Nov-03Component Technologies

    EJB

    a Bean example a Bean example PlayerBeanPlayerBean com.chess.player.PlayerHomecom.chess.player.PlayerHome com.chess.player.Playercom.chess.player.Player com.chess.player.PlayerBeancom.chess.player.PlayerBean

    ididfield>FalseFalseididfield>

    -- -- --namenamefield>

    XML Bean exampleXML Bean example

  • 8/13/2019 EJB Lecture

    33/33

    Page 65, 5-Nov-03Component Technologies

    EJB

    ...

    allows to read/writeeveryone

    everyone

    myBean*

    XMLXMLSecurity Roles and Method permissionsSecurity Roles and Method permissions