Vous êtes sur la page 1sur 16

Enterprise Java Beans

Sun Microsystems introduced the J2EE application server and the Enterprise
JavaBean (EJB) specifications as a venture into the multitier server side component
architecture market. It is important to note that though EJB and JavaBeans are both
component models, they are not same. EJBs are interprocess components and JavaBeans
are intraprocess components. EJB is a specification for creating server side components
that enables and simplifies the task of creating distributed objects.

The Key features of EJB are as follows

 EJB components are server side components written using Java


 EJB components implement the business logic only. We need not write code for
system level services, such as managing transactions and security.
 EJB components provides services, such as transaction and security management and
can be customized during deployment.
 EJB can maintain state information across various method calls.

Enterprise JavaBeans Component Architecture

Client
Home Interface
EJB Home Home Interface
EJB
Home
Stub EJB Server
Remote Interface EJB Object
EJB Container Remote Intf
EJB
Object
Stub Bean Class

EJB Server which contains the EJB container.

EJB container, which contains enterprise beans

Enterprise bean, which contains methods that implement the business logic.

EJB Server

EJB Server provides some low level services, such as network connectivity to the
container. It also provides the following services:

1. Instance Passivation – If a container needs resource, it can decide to temporarily


swap out a bean from the memory storage.
2. Instance Pooling – If an instance of the requested bean exists in the memory, the
bean is reassigned to another client.
3. Database Connection Pooling – When an Enterprise bean wants the access a
database, it does not create a new database connection of the database connection
already exists in the pool.

4. Precached Instances – The EJB server maintains a cache. This cache information
about the state of the enterpirse bean.

EJB Container

The EJB container acts as an interface between and Enterprise bean and the clients.
Clients communicate with the enterprise bean through the Remote and Home Interfaces
provide by the container.

The client communicating to the enterprise bean through the container enables the
container to service the client’s request with great flexibility. For Instance, the container
manages a pool of enterprise beans and uses them as the need arises, instead of creating a
new instance of the bean for each client request.

The container also provides the following services:

1. Security
2. Transaction Management
3. Persistance -> Permanent Storage
4. Life Cycle Management

Enterprise Bean

Enterprise JavaBeans are write once, run anywhere, middle tier components that consists
of methods that implements the business rule. The enterprise bean encapsulates the
business logic. There are two types of enterprise bean.

1. Entity Bean
2. Session Bean

Entity Bean

Entity Beans are enterprise beans that persist across multiple sessions and
multiple clients. There are two types of Entity bean:

1. Bean Managed Persistance


2. Container Managed Persistance

In a Bean managed persistance, the programmer has to write the code for database
calls. On the other hand, in container managed persistance, the container takes care of
database calls.
Session Bean

Session bean perform business tasks without having a persistent storage


mechanism, such as a database and can use the shared data. There are two types of
session beans:

1. Stateful Session Bean


2. Stateless Session Bean

A Stateful session bean can store information in an instance variable to be used


across various method calls. Some of the application require information to be stored
across various method calls.

A Stateless session bean do not have instance variables to store information.


Hence, stateless session beans can be used in situations where information need not to be
used across method calls.

Life Cycle of a Stateless Session Bean

Does not exists

newInstance()
setSessionContext() ejbRemove()
ejbCreate()

Method Ready

Does not Exists -> when the bean has not been instantiated.
Method Ready -> When the container requires it.

Class.newInstance() -> Create a new instance of the stateless session bean and allocates
the required memory

SessionBean.setSessionContext(SessionContext ct) -> Sets the bean reference to the


session context. A session context enables the enterprise bean to interact with the
container. The enterprise bean can use the session context to query the container for
information, such as transactional and security state.

ejbCreate() -> It is similar to the constructor of EJB class. It is invoked only once in the
life cycle of the stateless session bean, when the client invokes the create() method of the
home interface. The ejbCreate() method must not take any argument, as stateless session
bean do not store any information in the instance variable.
ejbRemove() -> ends the life cycle of the stateless session bean. This method closes any
open resource and frees the memory space.

Stateless Bean

Home Interface
Remote Interface
Bean Class
Client Application

Remote Interface
A remote interface defines all the business methods of the enterprise bean that the
EJB client would invoke. The remove interface does not include system level operations,
such as persistence, security and transactions.

Home Interface
The home interface defines methods that allow EJB clients to create and find EJB
components.

Bean Class
The EJB class implements all the business methods declared in the remote
interface.

Eg:

Calculator.java

//Remote Interface

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Calculator extends EJBObject


{
public double dollarToRs(double dollars) throws RemoteException;
}

CalculatorHome.java

// Home Interface

import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface CalculatorHome extends EJBHome


{
Calculator create() throws RemoteException, CreateException;
}

CalculatorEJB.java

//Enterprise Bean class


import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

public class CalculatorEJB implements SessionBean


{
public double dollarToRs(double dollars)
{
return dollars * 47.20;
}

public CalculatorEJB() {}
public void ejbCreate() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
}

Compile the Source files

s.bat

path=%path%;d:\jdk1.2\bin;d:\j2sdkee1.2\bin

set classpath=d:\j2sdkee1.2\lib\j2ee.jar;d:\demo\ejb;

set java_home=d:\jdk1.2

set j2ee_home=d:\j2sdkee1.2

EJB Servers
Sun Java Server (J2EE Server)
Web Logic (BEA)
Websphere (IBM)
J2EE SDK Architecture

It is a platform for developing and deploying enterprise and multitier applications


in a distributed environment. The J2EE SDK architecture consists of :

• J2EE Server
• EJB Container
• Web Container

Enterprise Bean
EJB Container

Enterprise Bean
J2EE Server

JSP File
Web Container

Servlet

J2EE Server
The J2EE server contains the EJB container and the Web Container. The J2EE
server provides the following services to the EJB container and the Web container.

1. It enforces security by authenticating users.


2. It allows clients to interact with the enterprise beans
3. It facilitates a Web browser to access servlets and JSP files.
4. It provides naming and directory services to locate and search services and
components.

EJB Container
The EJB Container contains the enterprise bean. The container provides remote
and home interfaces through which clients communicate with the enterprise bean. It also
provides services such as transaction management, security, life cycle management and
persistence.

Web Container
The Web container is a runtime environment for servlets and JSP files.

J2EE application components


A J2EE application is assembled from three components: J2EE application
clients, enterprise beans, and web components. Each component is packaged into a file
with a specific file format.

A J2EE application client is a Java application that runs in an environment, which enable
it to access the J2EE services. A J2EE application client is packaged in to .jar file

A Web component may contain servlet, JSP, HTML and GIF files. These Web
component files are packaged in a .war file.

An enterprise bean consists of three files: the EJB class, home and remote interfaces. The
enterprise bean files are bundled into an EJB. Jar file.

The .jar,.war and EJB.jar files are assembled into a J2EE application, which is an .ear
file. The .ear file is then deployed on the J2EE server.

Enterprise Bean Web component


(.jar files) (.war files)

Assembled
J2EE application
(.ear file)

Deployed

J2EE
server

Deployment Descriptor
An enterprise beans has to be managed at runtime. Moreover, the J2EE server
must know how to apply the primary services, such as security, naming, and transaction
service. To do this, deployment descriptor is used.

Deployment descriptor is an .XML file and contains information about deployment of an


enterprise bean.
JNDI
JNDI is a standard extension to the Java platform that provides multiple naming
and directory services. A naming services provides a mechanism for locating distributed
objects.

The client uses JNDI to initiate a connection to and EJB server and to locate a specific
EJB home.

Deploying an Enterprise JavaBean

1. Start the J2EE Server j2ee –verbose (First Command Prompt)


2. Start the Deploytool Application deploytool (Second Command Prompt)
3. File -> New Application -> Browse -> CalculatorAppln.ear
4. File -> New Enterprise Bean -> Next Click
5. Jar File name -> CalcJar
6. Contents -> Add Click -> Calculator.class, CalculatorHome.class,
CalculatorEJB.class
7. Click Next
8. Select CalculatorEJB.class (Enterprise Bean Class), Home Interface
(CalculatorHome), RemoteInterface (Calculator), Bean Display Name ->
Calculator. Bean Type -> Session -> Stateless
9. Click Next
10. Click Finish
11. Tools -> Deploy Application -> check “Return Client.jar”
12. Click Next
13. Enter JNDI Name “CalculatorJNDI”
14. Click Finish

CalculatorClient.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

public class CalculatorClient extends JFrame


{
public static int w = 500;
public static int h = 95;
public static String str = "Earnest Bank Welcomes You";
Container c;
JLabel l,result;
JTextField t;
JButton b;

public static String value;


public static double dbl;
public static double amt;

public CalculatorClient()
{
super(str);

c = getContentPane();
c.setLayout(new GridLayout(2,2,2,2));

l = new JLabel("Enter the amount in Dollars($)");


c.add(l);

t = new JTextField(10);
c.add(t);

b = new JButton("Calculator");
c.add(b);

result = new JLabel();


c.add(result);
value = t.getText();
b.addActionListener(new addEvent());
setSize(w,h);
show();
}
public class addEvent implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
value = t.getText();
dbl = Double.parseDouble(value);
try
{
Context ic = new InitialContext();
Object obj = ic.lookup("CalculatorJNDI");
CalculatorHome home = (CalculatorHome)
PortableRemoteObject.narrow(obj,CalculatorHome.class);
Calculator calc = home.create();
amt = calc.dollarToRs(dbl);
result.setText("Result(Rs.): " + String.valueOf(amt));
}catch(Exception ex)
{
System.err.println("Caught an unexpected exception!");
ex.printStackTrace();
}
}
}
public static void main(String args[])
{
CalculatorClient m = new CalculatorClient();
}
}

compile CalculatorClient.java
Before Execution (classpath -> D:\demo\ejb\CalculatorApplnClient.jar)
Stateful Session Bean

• The bean instance needs to be initialized when it is needed


• The client application is an interactive one
• The client is likely to invoke multiple method – calls
• The bean needs to store client – specific information across method calls.

Life Cycle of a Stateful session bean

Does not
exists
remove()
Create() ejbRemove()
newInstance()
setSessionContext() ejbPassivate()
ejbCreate()

Ready Passive
ejbActivate()

Eg:

Problem Statement

Earnest Bank’s Chief Technology Officer (CTO) has entrusted the development
team with the task of creating an application to validate the credit card information
entered by the user.

The team is responsible for justifying the choice of stateful session bean as the
bean type and writing code for the required application

Eg:

Card.java

import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface Card extends EJBObject
{
public int validate(String CardNo) throws RemoteException;
}

CardHome.java

import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface CardHome extends EJBHome


{
Card create(String person,String CardNo) throws
RemoteException,CreateException;
}

CardEJB.java

import javax.ejb.*;
import java.rmi.RemoteException;

public class CardEJB implements SessionBean


{
String CustomerName;
String CardNo;

public void ejbCreate(String person,String cardNo) throws CreateException


{
if(person.equals("") || cardNo.equals(""))
{
throw new CreateException("Null person or card Number not
allowed");
}
CustomerName = person;
CardNo = cardNo;
}

public int validate(String cardNo) throws RemoteException


{
int len = CalcLen(cardNo);
if (len > 16)
return 0;
else
return 1;
}

public int CalcLen(String cardNo) throws RemoteException


{
return cardNo.length();
}
public CardEJB() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbRemove() {}
public void setSessionContext(SessionContext ctx) {}
}
CardClient.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

public class CardClient extends JFrame


{
public static int w = 690;
public static int h =95;
public static String str = "Earnest Shopping Center Welcomes You";
Container c;
JLabel lname,lcard,result;
JTextField tname,tcard;
JButton b;

public int res;


public static String uname;
public static String ccno;
public CardClient()
{
super(str);
c = getContentPane();
c.setLayout(new GridLayout(3,2,2,2));
lname = new JLabel("Name:");
c.add(lname);
tname = new JTextField(20);
c.add(tname);
lcard = new JLabel("Card Number");
c.add(lcard);
tcard = new JTextField(16);
c.add(tcard);
b = new JButton("Submit");
c.add(b);
result = new JLabel();
c.add(result);
b.addActionListener(new addEvent());
setSize(w,h);
show();
}

public class addEvent implements ActionListener


{
public void actionPerformed(ActionEvent avt)
{
uname = tname.getText();
ccno = tcard.getText();
System.out.println(uname);
System.out.println(ccno);
try
{
Context initial = new InitialContext();
Object objref = initial.lookup("Cardjndi");
CardHome home =
(CardHome)PortableRemoteObject.narrow(objref,CardHome.class);
Card Creditcard = home.create(uname,ccno);
res = Creditcard.validate(ccno);
System.out.println(res);
if(res == 0)
{
result.setText("The Card Number " + ccno + " is valid");
}
else
{
result.setText("Sorry! The card Number " + ccno + " is
invalid");
}
}catch(Exception ex)
{
System.out.println("Exception Raised : " + ex);
result.setText("Check if you have entered your name and also card
number!");
}
}
}
public static void main(String args[])
{
CardClient c;
c = new CardClient();
}
}

1
Entity Bean

Session Bean Entity Bean


It is used to carry out tasks based on It is used to represent a business entity
request from clients object in a data store
It can be accessed by just a single client It can be accessed by multiple clients
It cannot model persistent Data It can model persistent data

Problem Statement

Earnest Banks Chief Technology Officer (CTO) has entrusted the development team with
the task of creating an application that will enable the bank staff store the details of ATM
transactions carried out by an account holder, in the central SQL – Server 2000 database.
The staff should be able to store transaction details such as account id, transaction date,
transaction particulars, check number and amount withdrawn or deposited.

Database

Registration

cRegistrationID int
cFirst_Name char(50)
cLast_Name char(50)
cAddress char(50)
cAccount_tyoe char(30)
mAnnual_Income money(8)
cPhone_No char(10)

Account_Holder

cAccount_id char(10)
cRegistrationID int
mBalance money(8)

Account_Holder_Transaction

cAccount_id char(10)
dDate_of_Trans datetime
vcParticulars varchar(50)
cCheck_No char(10)
mAmount money

Vous aimerez peut-être aussi