Anda di halaman 1dari 33

Enterprise Java Beans

Mikael kerholm

Component Technologies EJB

Page 1, 5-Nov-03

Lecture Stucture
Introduction
1. 2. 3.

Java JavaBeans J2EE EJB Java Serverlets, JSP, and clients Packaging and Deployment

J2EE
1. 2. 3.

Summary, Questions

Component Technologies EJB

Page 2, 5-Nov-03

References
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/

Component Technologies EJB

Page 3, 5-Nov-03

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

J2SE, Java 2 Platform, Standard Edition


provides the essential compiler, tools, runtimes, and APIs for writing, deploying, and running applets and applications

J2EE, Java 2 Platform, Enterprise Edition


component based model, simplifies enterprise development and deployment; manages the infrastructure and supports the web services to enable development business applications

J2ME, Java 2 Platform, Micro Edition


a highly optimized Java runtime environment, specifically addresses the vast consumer space (embedded systems), from smart cards to more PC like applications

Component Technologies EJB

Page 4, 5-Nov-03

JavaBeans
A desktop component model for Java, included among the J2SE technologies A Java API and a Specification Software reuse for Software Development Object-Oriented Focus on lightweight components for small-scale CBD
Component Technologies EJB

Page 5, 5-Nov-03

JavaBeans
Use standard naming conventions Have public interfaces Packaged in JAR files Interface composed of:

Properties:
Simple, Boolean or Indexed Could be Bound or Constrained

Events:
signaled by changing properties signaled for custom state changes

Methods:
default is any public method Built via BeanInfo class or Reflection API
Component Technologies EJB
Page 6, 5-Nov-03

Java 2 Enterprise Edition (J2EE)


For enterprise applications (distributed business applications)

Demands
Availability Security Reliability Scalability

From the early 90s


Shift 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

Component Technologies EJB

Page 7, 5-Nov-03

Java 2 Enterprise Edition (J2EE)


Presentation Presentation
Tier Boundary

Presentation tier

Business Business logic logic

Business Business logic logic Business tier Database Database driver driver

Tier Boundary

Database Database

Data tier

Component Technologies EJB

Page 8, 5-Nov-03

Java 2 Enterprise Edition (J2EE)

Component Technologies EJB

Page 9, 5-Nov-03

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 with clients EJB, business components on the server side

Component Technologies EJB

Page 10, 5-Nov-03

Enterprise JavaBean (EJB)


Javas component model for distributed enterprise applications, released 1998 EJB technology defines a model for the development of reusable Java server components Def: Enterprise Java Beans is a standard server-side component for computer transaction monitors. Applications written using EJB are:

Scalable Transactional Multi-User secure


Component Technologies EJB
Page 11, 5-Nov-03

EJB != JB
Once and for all JB

Desktop Components Enterprise Distributed Components Could of course be implemented using JavaBeans

EJB

Component Technologies EJB

Page 12, 5-Nov-03

J2EE

Component Technologies EJB

Page 13, 5-Nov-03

Contents
1.

EJB Components
General Interfaces and classes Architechture Different types Transactions

2. 3.

Java Serverlets, JSP and clients


Brief

Packaging and Deployment


Brief

Component Technologies EJB

Page 14, 5-Nov-03

What is an Enterprise JavaBean?

A server-side component that encapsulates the business logic of an application

Component Technologies EJB

Page 15, 5-Nov-03

When to use Enterprise JavaBeans


If any of these requirements hold for your application: The application must be scalable and distributable Transactions are required to ensure data integrity The application will have a variety of clients

Component Technologies EJB

Page 16, 5-Nov-03

Enterprise JavaBeans
Entity Beans

Persistent Primary key Receive their state from the client Live as long as the client need them Asynchronously Only a bean class no interfaces
Component Technologies EJB
Page 17, 5-Nov-03

Session Beans

Message-Driven Beans (EJB 2.0)


Classes 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
Component Technologies EJB
Page 18, 5-Nov-03

A Beans interfaces
Remote Interface

Business methods to do the beans work Implemented by the shadowdy Bean Object Defines the beans life cycle methods Implemented by EJB Home Business methods used by other beans in the same container Life-cycle methods used by other beans in the same container
Component Technologies EJB
Page 19, 5-Nov-03

Remote Home Interface


Local Interface (EJB 2.0)


Local Home Interface (EJB 2.0)


A Beans classes
The Bean Class

Implement the business methods Do not implement Remote (or local) and (local) Home Interfaces Beans exist in the middle of client software and data sources Clients never interact directly with the bean class, uses methods of the Remote and Home Interface, interacting with automatically generated stubs

Component Technologies EJB

Page 20, 5-Nov-03

EJB Architecture
Home Interface EJB Client Home Home Stub Stub Object Object Stub Stub EJB Server EJB Container Home Home Object Object EJB EJB Object Object Remote Interface (or Local Interface)

Bean Bean Class Class

Component Technologies EJB

Page 21, 5-Nov-03

When to use Entity Beans


The bean represents a business entity, not a procedure To provide a safe and consistent interface to a set of shared data

Component Technologies EJB

Page 22, 5-Nov-03

Entity Beans
Represents a business object in a persistent storage mechanism Can be shared by multiple clients Two types of persistence:

Container-managed Bean-managed

Component Technologies EJB

Page 23, 5-Nov-03

Container-managed persistence
They are the simplest to develop The beans code contain no database access calls

Component Technologies EJB

Page 24, 5-Nov-03

Bean-managed persistence
Explicitly write persistence logic More flexibility in how state is managed between the bean instance and the database Used when deployment tools are inadequate

Component Technologies EJB

Page 25, 5-Nov-03

Life Cycle

Component Technologies EJB

Page 26, 5-Nov-03

When to use Session Beans


Only one client has access to the beans instance Non persistent and existing only for a short period of time

Component Technologies EJB

Page 27, 5-Nov-03

Session Beans
Useful for describing interactions Does not represent shared data in the database, but can access shared data Two types:

Stateless Stateful

Component Technologies EJB

Page 28, 5-Nov-03

Stateless 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 method invocation The bean fetches a set of read-only data
Component Technologies EJB

Page 29, 5-Nov-03

Life Cycle

Component Technologies EJB

Page 30, 5-Nov-03

Stateful Session Beans


Dedicated to one client for the life of the bean instance Instance variables represent the state of a unique client-bean session Stateful session beans are appropriate if: The bean needs to hold information about the client across method invocations The bean mediates between the client and the other components of the application
Component Technologies EJB

Page 31, 5-Nov-03

Life Cycle

Component Technologies EJB

Page 32, 5-Nov-03

When to use Message-Driven Beans

To receive messages asynchronously When consuming JMS messages

Component Technologies EJB

Page 33, 5-Nov-03

Message-Driven Beans
Has only a bean class Can consume and process messages concurrently Acts as a JMS message listener Deliver messages to a virtual channel Currently process only JMS messages

Component Technologies EJB

Page 34, 5-Nov-03

Life Cycle

Component Technologies EJB

Page 35, 5-Nov-03

Calling an EJB
2 Return reference home stub JNDI 1 Ask for Home object 5 Return Obj stub EJB Client 3 Ask for EJB Object EJB Server EJB Container Home Home Object Object 4 Create EJB Object EJB EJB Object Object 6 Invoke a method Bean Bean Class Class

7 Wraps the call to the Bean Class

Component Technologies EJB

Page 36, 5-Nov-03

Transactions with EJBs


Managed automatically No use of API Defined at deployment Possible to explicitly manage transactions but not recommended

Component Technologies EJB

Page 37, 5-Nov-03

A Transaction
Transactions is the execution of a unit-of-work that accesses on or more resources, usually databases A unit-of-work is a set of activities that relate to each other and must be completed together The objective with transactions is to execute an unit-of work that results in a reliable exchange Transactions are often complex and usually involve manipulation of data Transactions must work perfectly every time or not be executed at all

Component Technologies EJB

Page 38, 5-Nov-03

Acid-properties
Atomic

A transaction must execute completely or not at all A transaction always leads to a correct transformation of the system state by preserving the state invariance The data a transaction access cannot be affected by any other parts of the system until the transaction is completed All the data changes made during the course of transaction must be written to a physical storage before the transactions is physically completed
Component Technologies EJB
Page 39, 5-Nov-03

Consistent

Isolated

Durable

Transaction Management
Declarative transaction management

The transactional behavior controls by using transactions 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 management


Difficult to use Will not be covered in this talk


Component Technologies EJB

Page 40, 5-Nov-03

Transactions Attribute
You can set the runtime transaction attribute as a XMLattribute in the deployment descriptor by hand, but we will use a deployment wizard It is more efficient and easier to use transaction attributes than to control transactions explicitly It is possible to set a transaction attribute for the entire bean or to set different transactions attribute for individual methods There exist six transaction attributes in EJB 2.0:

NotSupported Supports Required RequiresNew Mandatory Never


Component Technologies EJB
Page 41, 5-Nov-03

The Different Transactions Attributes


NotSupported

Invoking a method on a bean with this transaction attribute suspends the transactions until the method is completed

Supports

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

Required

Means that the bean method must be invoked within the scope of a transaction
Component Technologies EJB
Page 42, 5-Nov-03

The Different Attributes, Cont.


RequiresNew

Means that a new transactions always starts

Mandatory

Means that the bean method must always be made part of the transaction scope of the calling client

Never

Means that the bean method must never be invoked within the scope of a transaction

Component Technologies EJB

Page 43, 5-Nov-03

Java Serverlets, JSP and clients

Component Technologies EJB

Page 44, 5-Nov-03

Serverlets
A serverlet is a server side component, which is deployed in the same fashion as a EJB Used to dynamically create html pages, for clients

Since it is server side, it extends the reach for clients to backend components (e.g., EJBs) in the server

A servelet is assigned to handle an access for a specific html page


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

When a client looks at the html code posted from the server, it looks just like a static html page
Component Technologies EJB
Page 45, 5-Nov-03

JavaServer Pages, JSP


An extension of serverlets, simplifies the creation of dynamic html Simply lets the developer incorporate real java code into a html page when desired (as a scripting language) Is actually compiled to servelets

Component Technologies EJB

Page 46, 5-Nov-03

Clients
Web clients with serverlets or JSP, JSP possibly more powerful Can also create application clients

An client side component, that access EJBs Easy and straightforward to create, deploted in the same fashion as EJBs

Component Technologies EJB

Page 47, 5-Nov-03

Packaging and Deployment

Component Technologies EJB

Page 48, 5-Nov-03

Deployment and Deploy Tools


Packaging

Create JAR files


A compressed platform-independent file Bean and Beans interface and help classes

Create deployment descriptors


XML files specifying Access control Bean references External Resource references Transactional attributes

Deployment

Deploy the application on a server

Component Technologies EJB

Page 49, 5-Nov-03

Packaging and Deployment


Can be done by hand

Gives full control Time consuming

Graphical deplytool with wizards included in the reference implementation


Easy, fast

Component Technologies EJB

Page 50, 5-Nov-03

Summary
JB != EJB EJBs Typically used for 3 or more tiers bussiness applications EJBs, server side components, with remote and home interfaces; packaged in JAR files with deployment descriptors

Session, Entity, Message

Clients, can be applications or web pages through servelets or JSP

Component Technologies EJB

Page 51, 5-Nov-03

Example Entity Bean Person


Lets look how to build a bean

Component Technologies EJB

Page 52, 5-Nov-03

The Remote Interface


/** Remote Interface Business methods for Person beans */ import javax.ejb.Exception; javax.ejb.Exception; public interface Person extends javax.ejb.EJBObject { String getName() getName() throws RemoteException; RemoteException; void setName(String n) throws RemoteException; RemoteException; }

Component Technologies EJB

Page 53, 5-Nov-03

The Home Interface


/** Home Interface Life cycle method for Person beans */ import java.rmi.RemoteException; java.rmi.RemoteException; import javax.ejb.CreateException; javax.ejb.CreateException; import javax.ejb.FinderException; javax.ejb.FinderException; public interface PersonHome extends javax.ejb.EJBHome { //responsible for initalizing an instance of the bean public Person create(int id) throws CreateException, CreateException, RemoteException; RemoteException; //look up a bean in a DB public findByPK(PersonPK pk) pk) throws FinderException, FinderException, RemoteException; RemoteException; }
Component Technologies EJB

Page 54, 5-Nov-03

The Bean Class


/** Bean Class Implements the business methods for Person component Person Bean is a Entity Bean */ public class PersonBean implements javax.ejb.EntityBean { private int id; private String name; //business methods public Sting getName() getName() { return name; } public void setName(String n) { name=n; } // continue next slide
Component Technologies EJB
Page 55, 5-Nov-03

// and the bean class continues //ejb.entity //ejb.entity methods public PersonPK ejbCreate(int i) { id=i; return null; } public public public public public public public public }
Component Technologies EJB

void void void void void void void void

ejbPostCreate(int i) {/*+*/} ejbSetEntityContext(EntityContext ctx) ctx) {} ejbUnsetEntityContext() ejbUnsetEntityContext() {/*+*/} ejbActivate() ejbActivate() {} ejbPassivate() ejbPassivate() {} ejbLoad() ejbLoad() {/*+*/} ejbStore() ejbStore() {/*+*/} ejbRemove() ejbRemove() {}

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

Page 56, 5-Nov-03

Example Simple JSP page


How to build a web client

Component Technologies EJB

Page 57, 5-Nov-03

<%-<%-- A jsp file that use a session bean --%> --%> <%@ page import="Converter,ConverterHome,javax.ejb.*, import="Converter,ConverterHome,javax.ejb.*, java.math.*, java.math.*, javax.naming.*, javax.naming.*, javax.rmi.PortableRemoteObject, javax.rmi.PortableRemoteObject, java.rmi.RemoteException" java.rmi.RemoteException" %> <%! private Converter converter = null; null; <%-<%-- The init method, method, JNDNI lookup --%> --%> public void jspInit() jspInit() { try { InitialContext ic = new InitialContext(); InitialContext(); Object objRef = ic.lookup("java:comp/ ic.lookup("java:comp/env/ env/ejb/ ejb/TheConverter"); TheConverter"); ConverterHome home = (ConverterHome)PortableRemoteObject.narrow(objRef,ConverterHome.c lass); lass); converter = home.create(); home.create(); } catch (Exception ex) { System.out.println("Couldn't create converter bean."+ bean."+ ex.getMessage()); ex.getMessage()); }
Component Technologies EJB
Page 58, 5-Nov-03

public void jspDestroy() jspDestroy() { converter = null; null; } %> <html> <form method="get"> method="get"> <input type="text" type="text" name="amount" name="amount" size="25"> <input type="submit" type="submit" value="Submit"> value="Submit"> </form> <% String amount = request.getParameter("amount"); request.getParameter("amount"); if ( amount != null && amount.length() amount.length() > 0 ) { BigDecimal d = new BigDecimal (amount); amount); %> <%= amount %> Kronor are <%= converter.yenToEuro(d) converter.yenToEuro(d) %> Euro. <% } %> </body > </body> Component Technologies </html> Page 59, 5-Nov-03 EJB

Example A deployment descriptor


Good to understand, when time allows!

Component Technologies EJB

Page 60, 5-Nov-03

XML Document Header


XML documents start with two general information tags: 1. Specifies the XML version the file use

<?xml version=1.0?> Provides the URL to the DTD, you can download it and validate the XML file <!DOCTYPE ejb-jar PUBLIC -//Sun Microsystems, Inc.//DTD Enterprise JavaBean 1.1//EN http://java.sun.com/j2ee/dtds/ejb-jar.dtd>

2. Specifies the DTD that defines the XML file


Component Technologies EJB

Page 61, 5-Nov-03

XML Descriptors Body


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

Bean/ Beans <enterprise-beans>


Entity or Session Beans Primary Key Environment Entries Reference to other Beans Reference to External Resources (such as a Database) Security Roles

Bean/Beans Assembly <assembly-description>


Transactional attributes Security roles & Method permissions

Component Technologies EJB

Page 62, 5-Nov-03

XML Body example


<ejb<ejb-jar> <description>a body example</description> <enterprise<enterprise-bean> <session> - - </session> <entity> - - </entity> - - </enterprise</enterprise-bean> <assembly<assembly-descriptor> - - </assembly</assembly-descriptor> </ejb</ejb-jar>

Component Technologies EJB

Page 63, 5-Nov-03

XML Bean example


<entity> <description> a Bean example </description> <ejb</ejb-name> <ejb-name>PlayerBean name>PlayerBean</ejb <home>com.chess.player.PlayerHome </home> <home>com.chess.player.PlayerHome</home> <remote>com.chess.player.Player</remote> <ejb-class> <ejb-class> com.chess.player.PlayerBean</ejb com.chess.player.PlayerBean</ejb<persistence<persistence-type>Container</persistencetype>Container</persistence-type> <prim<prim-keykey-class>java.lang.Integer</primclass>java.lang.Integer</prim-keykey-class> <primkey-field> primkey-field>id</primkey field>id</primkey<reentrant>False</reentrant> <cmp-field> cmp-field><fieldfield><field-name>id</fieldname>id</field-name></cmp name></cmp- - <cmp-field> cmp-field><fieldfield><field-name>name</fieldname>name</field-name></cmp name></cmp</entity>

Component Technologies EJB

Page 64, 5-Nov-03

XML Security Roles and Method permissions


<ejb-jar> <enterprise-beans>...</enterprise-beans> <assembly-descriptor> <container-transaction> </container-transaction> <security-role> <description>allows to read/write</description> <role-name>everyone</role-name> </security-role> <method-permission> <role-name>everyone</role-name> <method> <ejb-name>myBean</ejb-name> <method-name>*</method-name> </method> </method-permission> </assembly-descriptor>

Component Technologies EJB

Page 65, 5-Nov-03

Anda mungkin juga menyukai