Beruflich Dokumente
Kultur Dokumente
Course Description:
In this EJB course we will teach you how to develop component-based Java Applications
using Enterprise Java Beans. Tutorial also shows you how to program enterprise bean,
and how to deploy them in an Enterprise Beans Container such as WebLogic Server 6.0.
We will use WebLogic 6.0 Server for testing and running the applications. This tutorial is
ideal for programmers and developers who need to develop the server-side of industrial
strength distributed applications for Intranets and the web using Enterprise Java
beans(EJB) compliant application servers.
Prerequisites:
To understand this course you must have hands-on Java programming language
experience. Understanding of object-oriented programming, distributed computing and
component technology helpful. Prior knowledge of Servlets, JSP and JDBC programming
are highly recommended.
Course Content:
Two-tier application:
In the past two-tier applications were used. Two-tier applications are also know as
client/server applications. In most of the cases these architecture were providing only the
database functionality and all the business logic and presentation of the data logic were
installed on the client machine. This architecture was very difficult to maintain.
Sun's J2EE architecture is multi tiered architecture and it eliminates all the problems of
two-tier architecture. It also eliminates the need of writing thin-client multithread
applications, which were earlier used to write distributed transactional applications for
the enterprise. Thin-client multi tiered applications are very fast, secure and reliable. But
writing the thin-client multi tiered applications are not easy and it involves many lines of
intricate code to handle transaction and state management, multithreading, resource
pooling and other complex low-level details.
In the Java TM 2 Platform, Enterprise Edition (J2EE tm), low-level details are separated
from the business logic. Now the developers will more concentrate on the business logic
rather than the low-level details. Low-level details are managed by the application
container of the application server.
The JDBC API allows the java programs to access the database. For more information
and tutorial on JDBC visit http://www.roseindia.net/jdbc/jdbc.htm
Sun's JNDI API is a standard extension to the Java TM platform and it allows the java
applications to access naming and directory services. With the help of JNDI java
application can seamlessly access the heterogeneous enterprise naming and directory
services like DNS, LDAP, local file system, or objects in an application server.
The EJB specification defines the EJB component architecture and the interfaces between
the Enterprise JavaBeans technology-enabled server and the component.
These beans do not maintain the state, and the information stored in these beans are lost
when the server crashes.
These beans are also short lived and do not survive the server crashes. These beans are
used to maintain the session of a client. Shopping cart is developed using the session
beans.
c) Entity Beans:
These beans represents the data stored in a database. These beans survive the server
crashes because it reconstruct the data from the database when server comes up. An
example of an entity bean is the users information.
Java Server Pages allows the developers to embed the java code into html pages. It is a
mean by which dynamic content can be generated using the static HTML pages and the
data from the database. For more information visit http://www.roseindia.net/jsp/jsp.htm
5. Java Servlets:
Java Servlets are server side components that provides a powerful mechanism for
developing serverside applications. For more information and tutorial visit
http://www.roseindia.net/servlets/servlets.htm .
It is used to invoke methods on remote objects. EJB's uses the RMI for their functionality
and this is not the topic that any web application developer should learn.
7. CORBA:
Java's IDL support allows the developers to integrate Java with CORBA.
8. XML:
Java and XML combination provides the portable data. And this is ideal for the exchange
of data over the Internet and the Intranet.
The J2EE Architecture allows the programmers to divide their work into two major
categories:
• Business Logic
• Presentation Logic
Presentation Logic:
Presentation Logic consists of all the program (JSP and Servlets), images and html files
that are used to interact with the client. These files are archived into .war file. These
files are installed on the web server and these interacts with the users.
Business Logic:
These are EJB applications which implements the business logic of the system and are
archived into .jar file. Business logic runs on the application server.
-5-
These two types of archives are bundled into complete J2EE applications, and delivered
as Enterprise Archive (EAR) file.
Let's took an example of form processing. In this example J2EE application could have
and HTML form, which prompts the user to input the data, a servlet to receive the data
from the form and process it, and also an Enterprise Bean to store the data in a database.
In this example the HTML form and servlet are archived in a WAR file, and the
Enterprise Java Bean is archived into JAR file. These two archive files (WAR and JAR)
both are added to the EAR file, which is finally deployed on the server
One of Java's most important features is platform independence. Since its arrival, Java
has been depicted as "write once, run anywhere". But Enterprise JavaBeans (EJBs) go
one step further. They are not only platform independent but also implementation
independent. That is, EJBs can run in any application server that implements the EJB
specifications. In this overview, I discuss about the background, necessity and
motivations for the emergence of EJBs in the enterprise distributed computing arena and
a short EJB architectural overview.
Object-oriented (OO) programming languages, such as Java, C++ and Smalltalk, are used
to code software that fulfills the goals such as flexibility, extensibility and reusability, of
OO technology. In business systems, OO languages are being used to improve
development of GUIs, to simplify access to data and above all, to encapsulate the
business logic into business objects. As a business's products, processes,and objectives
evolve over time, the software that models the business has to be flexible, extensible,
adaptable and reusable. The OO programming methodologies, namely encapsulation,
polymorphism and inheritance, play a very important share in accomplishing the above
mentioned goals. As today's enterprises are being shaped to comprise a number of
business objects fulfilling various tasks, distributed computing is all set to take a very
significant role in developing and deploying enterprise-class software in the days ahead.
In the following sections, I discuss some of the earlier computing paradigms and the
context in which EJB architecture came out and promises to shape the future
requirements.
TP monitors have been evolving for about 30 years and have become powerful, high-
speed server platforms for mission-critical applications. TP monitors are operating
systems for business systems whose applications are written in languages like COBOL.
TP monitors automatically manage the entire environment that a business system runs in,
including transactions, resource management, and fault tolerance and thus are eligible to
be called operating systems. The business logic in TP monitors is made up of procedural
applications that are often accessed through network messaging or remote procedural
calls (RPC). RPC is a distributed mechanism that allows clients to invoke procedures on
applications in a TP monitor as if the procedure was executed locally.
The downside for TP monitors is as follows: TP monitors are not object oriented and they
work with procedural code that can perform complex and mission-critical tasks but no
sense of identity. Accessing a TP monitors through RPC is like executing static methods;
there is no such thing as a unique and distinct object. Also the business logic, which is
procedural, is not as flexible, extensible, or reusable as business logic, which is object-
oriented.
Distributed objects allow unique objects that have state and identity to be distributed
across a network so that they can be accessed by other systems. Distributed object
computing technologies like CORBA and Java RMI grew out of RPC with one
significant and necessary difference that the invoking method is on an object instance, not
an application procedure. Distributed objects are usually deployed on some kind of ORB,
which is responsible for helping client applications find distributed objects in a
transparent manner. The down side for an ORB is as follows: ORBs do not define an
operating system for distributed objects. That is, all the responsibility for concurrency,
transactions, resource management and fault tolerance rests on the application
developers. These services may be available from the ORB vendors or can be purchased
from third party vendors and can be implemented in an ORB, but the developer has to
write the glue code to incorporate them into the business objects.
As the advantages of distributed objects became visible, the number of systems deployed
using ORBs gets increased. But as indicated above, there happened to be a number of
deficiencies on server side due to the poor server-side component model, which ORB
architecture has been blessed with. The vital and relevant server-side services according
to the ORB architecture specifications have been made to be explicitly accessed through
APIs by the distributed object, resulting in more complexity. Also, the resource
management strategies such as instance swapping, resource pooling, and activation may
not be supported at all in this component model. These strategies are mainly responsible
for distributed object systems to scale, improving performance and throughput and
reducing latency. Without automatic support for resource management, application
developers must implement home-grown resource management solutions, which requires
a very sophisticated understanding of distributed object systems. Further on, ORBs fail to
-7-
Having realized that combining these two revolutionary technologies will do wonders for
enterprises, companies like IBM and BEA started to design a hybrid of ORBs and TP
monitor systems, which is referred to as component transaction monitors (CTMs) or
application servers. These types of application servers combine the flexibility and
accessibility of distributed object systems based on ORBs with the robust operating
system of a TP monitor. CTMs provide a comprehensive environment for server-side
components by managing concurrency, transactions, object distribution, load balancing,
security and resource management automatically.
CTMs have started to come out of several different industries including the relational
database industry, the application server industry, the web server industry, the CORBA
ORB industry, and the TP monitor industry. Each vendor offers products that reflect their
particular area of expertise. But a CTM that supports the Enterprise JavaBeans standard
server-side component model from Sun Microsystems seems to be a more elegant and
productive choice. There are a number of reasons for this fine architectural decision. Sun
Microsystems has framed a number of excellent standard server-side specifications for
several technologies and made the Java implementation an open standard quite
successfully. The Java Database Connectivity API (JDBC) was one of the shining
examples.
Thus, an Enterprise Java Bean is a remote object with semantics specified for creation,
invocation and deletion. The EJB container is assigned the system-level tasks mentioned
above. What a web container does for Java servlets and JSPs in a web server, the EJB
container is for EJBs.
EJB Architecture
1. There should be a mechanism to create the client-side and server-side proxy objects. A
client-side proxy represents the server-side object on the client-side. As far as the client is
concerned, the client-side proxy is equivalent to the server-side object. On the other hand,
the purpose of the server-side proxy is to provide the basic infrastructure to receive client
requests and delegate these request to the actual implementation object
3. There should be a way to inform the distributed component system that a specific
component is no longer in use by the client.
In order to meet these requirements, the EJB architecture specifies two kinds of interfaces
for each bean. They are home interface and remote interface. These interfaces specify the
bean contract to the clients. However, a bean developer need not provide implementation
for these interfaces. The home interface will contain methods to be used for creating
remote objects. The remote interface should include business methods that a bean is able
to serve to clients. One can consider using the home interface to specify a remote object
capable of creating objects conforming to the remote interface. That is, a home interface
is analogous to a factory of remote objects. These are regular Java interfaces extending
the javax.ejb.EJBHome and javax.ejb.EJBObject interfaces respectively.
As discussed below, the EJB architecture specifies three types of beans - session beans,
entity beans, and message-driven beans. A bean developer has to specify the home and
remote interfaces and also he has to implement one of these bean interfaces depending
upon the type of the bean. For instance, for session beans, he has to implement the
javax.ejb.SessionBean interface. The EJB architecture expects him to implement the
methods specified in the bean interface and the methods specified in the home and remote
interfaces. During the deployment time, he should specify the home and remote interfaces
and bean implementation class to define a bean. The EJB container relies on specific
method names and uses delegation for invoking methods on bean instances.
Thus regarding the first requirement, the EJB container generates the proxy objects for all
beans. For the second one, the EJB container for each bean implement a proxy object to
the home interface and publishes in the JNDI implementation of the J2EE platform. One
can use JNDI to look for this and obtain a reference. As this object implements the home
interface only, he can use one of the creation methods of the home object to get a proxy
-9-
to the remote interface of the bean. When one invokes a creation method on the home
proxy object, the container makes sure that a bean instance is created on the EJB
container runtime and its proxy is returned to the client. Once the client gets hold of the
proxy for the remote interface, it can directly access the services of the bean.
Finally, once the client decides to stop accessing the services of the bean, it can inform
the EJB container by calling a remote method on the bean. This signals the EJB container
to disassociate the bean instance from the proxy and that bean instance is ready to service
any other clients.
Types of EJBs
The EJB architecture is based on the concept that in an enterprise computing system,
database persistence-related logic should be independent of the business logic that relies
on the data. This happens to be a very useful technique for separating business logic
concerns from database concerns. This makes that business logic can deal with the
business data without worrying about how the data is stored in a relational database.
Basically entity beans model business concepts that can be expressed as nouns. For
example, an entity bean might represent a customer, a piece of equipment, an item in
inventory. Thus entity beans model real-world objects. These objects are usually
persistent records in some kind of database.
Session beans are for managing processes or tasks. A session bean is mainly for
coordinating particular kinds of activities. That is, session beans are plain remote objects
meant for abstracting business logic. The activity that a session bean represents is
fundamentally transient. A session bean does not represent anything in a database, but it
can access the database.
Thus an entity bean has persistent state whereas a session bean models interactions but
does not have persistent state.
Unlike session beans, entity beans have a client-independent identity. This is because an
entity bean encapsulates persistent data. The EJB architecture lets a developer to register
a primary key class to encapsulate the minimal set of attributes required to represent the
- 10 -
identity of an entity bean. Clients can use these primary key objects to accomplish the
database operations, such as create, locate, or delete entity beans. Since entity beans
represent persistent state, entity beans can be shared across different clients. Similar to
session beans, entity beans are also transactional, except for the fact that bean instances
are not allowed to programmatically control transactions.
These two types of beans are meant for synchronous invocation. That is, when a client
invokes a method on one of the above types, the client thread will be blocked till the EJB
container completes executing the method on the bean instance. Also these beans are
unable to service the messages which comes asynchronously over a messaging service
such as JMS. To overcome this deficiency, the EJB architecture has introduced a third
type of bean called message-driven bean. A message-driven bean is a bean instance that
can listen to messages from the JMS.
Unlike other types of beans, a message-driven bean is a local object without home and
remote interfaces. In a J2EE platform, message-driven beans are registered against JMS
destinations. When a JMS message receives a destination, the EJB container invokes the
associated message-driven bean. Thus message-driven beans do not require home and
remote interfaces as instances of these beans are created based on receipt of JMS
messages. This is an asynchronous activity and does not involve clients directly. The
main purpose of message-driven beans is to implement business logic in response to JMS
messages. For instance, take a B2B e-commerce application receiving a purchase order
via a JMS message as an XML document. On receipt of such a message in order to
persist this data and perform any business logic, one can implement a message-driven
bean and associate it with the corresponding JMS destination. Also these beans are
completely decoupled from the clients that send messages.
Session beans can be either stateful or stateless. Stateful session beans maintain
conversational state when used by a client. Conversational state is not written to a
database but can store some state in private variables during one method call and a
subsequent method call can rely on this state. Maintaining a conversational state allows a
client to carry on a conversation with a bean. As each method on the bean is invoked, the
state of the session bean may change and that change can affect subsequent method calls.
Stateless session beans do not maintain any conversational state. Each method is
completely independent and uses only data passed in its parameters. One can specify
whether a bean is stateful or not in the bean's deployment descriptor.
requires entity beans to implement these operations. Entity beans should implement the
javax.ejb.EntityBean interface that specifies the load and delete operations among others.
In addition, the bean developer should specify the appropriate create and find methods on
the home interface, and provide their implementation in an entity bean.
There are two types of entity beans and they are distinguished by how they manage
persistence. Container-managed beans have their persistence automatically managed by
the EJB container. This is a more sophisticated approach and here the bean developer
does not implement the persistence logic. The developer relies on the deployment
descriptor to specify attributes whose persistence should be managed by the container.
The container knows how a bean instance's fields map to the database and automatically
takes care of inserting, updating, and deleting the data associated with entities in the
database.
Beans using bean-managed persistence do all this work explicitly: the bean developer has
to write the code to manipulate the database. The EJB container tells the bean instance
when it is safe to insert, update, and delete its data from the database, but it provides no
other help. The bean instance has to do the persistence work itself.
EJB Container: The environment that surrounds the beans on the EJB server is often
referred to as the container. The container acts as an intermediary between the bean class
and the EJB server. The container manages the EJB objects and EJB homes for a
particular type of bean and helps these constructs to manage bean resources and apply the
primary services relevant to distributed systems to bean instances at run time. An EJB
server can have more than one container and each container in turn can accommodate
more than one enterprise bean.
Remote Interface: This interface for an enterprise bean defines the enterprise bean's
business methods that clients for this bean can access. The remote interface extends
javax.ejb.EJBObject, which in turn extends java.rmi.Remote.
Home interface: This interface defines the bean's life cycle methods such as creation of
new beans, removal of beans, and locating beans. The home interface extends
javax.ejb.EJBHome, which in turn extends java.rmi.Remote.
Bean Class: This class has to implement the bean's business methods in the remote
interface apart from some other callback methods. An entity bean must implement
javax.ejb.EntityBean and a session bean must implement javax.ejb.SessionBean. Both
EntityBean and Session Bean extend javax.ejb.EnterpriseBean.
Primary Key: This is a very simple class that provides a reference into the database.
This class has to implement java.io.Serializable. Only entity beans need a primary key.
Deployment Descriptors: Much of the information about how beans are managed at
runtime is not supplied in the interfaces and classes mentioned above. There are some
common primary services related with distributed systems apart from some specific
- 12 -
services such as security, transactions, naming that are being handled automatically by
EJB server. But still EJB server needs to know beforehand how to apply the primary
services to each bean class at runtime. Deployment descriptors exactly do this all
important task.
JAR Files: Jar files are ZIP files that are used specifically for packaging Java classes that
are ready to be used in some type of application. A Jar file containing one or more
enterprise beans includes the bean classes, remote interfaces, home interfaces, and
primary keys for each bean. It also contains one deployment descriptor.
Deployment is the process of reading the bean's JAR file, changing or adding properties
to the deployment descriptor, mapping the bean to the database, defining access control in
the security domain, and generating vendor-specific classes needed to support the bean in
the EJB environment. Every EJB server product comes with its own deployment tools
containing a graphical user interface and a set of command-line programs.
For clients like enterprise bean itself, Java RMI or CORBA client, to locate enterprise
beans on the net, Java EJB specifications specify the clients to use Java Naming and
Directory Interface (JNDI). JNDI is a standard Java extension that provides a uniform
Application Programming Interface (API) for accessing a wide range of naming and
directory services. The communication protocol may be Java RMI-IIOP or CORBA's
IIOP
There are some special integrated application development tools such as Inprise's
JBuilder, Sun's Forte and IBM's VisualAge, for designing EJBs in the market
Enterprise Java Beans or EJB for short is the server-side component architecture for
the Java 2 Platform, Enterprise Edition (J2EE) platform. EJB technology enables rapid
and simplified development of distributed, transactional, secure and portable applications
based on Java technology.
Sun Microsystems in the beginning put forward Java Remote Method Invocation
(RMI) API as a distributed object computing technology. RMI specifies how to write
objects so that they can talk to each other no matter where on the network they are found.
At its core, however, RMI is nothing more than an API to which our distributed objects
must conform. RMI says nothing about other characteristics normally required of an
enterprise-class distributed environment. For example, it does not say anything about
how a client might perform a search for RMI objects matching some criteria. It also does
not specify how those distributed objects work together to construct a single transaction.
Thus there is a realization for a need of a distributed component model.
A component model is a standard that defines how components are written so that
systems can be built from components by different developers with little or no
customization. There is already a component model called as JavaBeans in Java. It is a
- 13 -
component model that defines how we write user interface components so that they may
be plugged into third-party applications. The magic thing about JavaBeans is that there is
very little API behind the specification; we neither implement nor extend any special
classes and we need not call any special methods.
Enterprise JavaBeans is a more complex extension of this concept. While there are API
elements behind Enterprise JavaBeans, it is more than an API. It is a standard way of
writing distributed components so that the written components can be used with the
components we write in someone else's system. RMI does not support this ability for
several reasons listed below. Here come the features that are not available with RMI.
1. Security - RMI does not worry about security. RMI alone basically leaves our system
wide open. Any one who has access to our RMI interfaces can forge access to the
underlying objects. If we do not impose complex security restrictions to authenticate
clients and verify access by writing extra code, we will have no security at all. Thus our
components are therefore unlikely to interoperate with other's components unless we
agree to some sort of security model.
2. Searching - RMI provides the ability to do a lookup only for a specific, registry-bound
object. It specifies nothing about how we find unbound objects or perform searches for a
group of objects meeting certain requirements. For example, writing a banking
application, we might want to support the ability to find all accounts with negative
balances. In order to do this in an RMI environment, we would have to write our own
search methods in bound objects. Our custom approach to handling searches will not
work with someone else’s custom approach to searching without forcing clients to deal
with both search models.
4. Persistence - RMI does not care about how RMI objects persist across time. There is a
persistence utility that supports saving RMI objects to a database using JDBC. But it is
very difficult to integrate with RMI objects designed to use some other persistence model
because the other persistence model may have different persistence requirements.
Enterprise JavaBeans addresses all of these points so that we can literally pick and choose
the best designed business components from different vendors and make them work and
play well with one another in the same environment. EJB is now the standard component
- 14 -
model for capturing distributed business components. It hides from us the details we
might have to worry about our self if we were writing an RMI application
Before we go into the grater details of the EJB let's look at some of the EJB Application
Servers available in the market.
Application Servers
2. iPlanet
3. Oracle
4. Orion Server
5. WebSphere
6. NetDynamics
7. JRun Server
8. Tomcat
9. JOnAS
You can download the BEA WebLogic Server for http://www.bea.com to test and run the
examples described in this tutorial.
This tutorial shows you how to install Web Logic 6.1 Server on windows machine. You
can download the BEA WebLogic Server for http://www.bea.com to test and run the
examples described in this tutorial. BEA WebLogic Server™, is world class Web and
Wireless Application Server. It delivers scalability, flexibility, and reliability. BEA
WebLogic Server's trial version is available and it you can download it from the BEA's
Download Center: http://commerce.bea.com/.
- 15 -
Installation of the WebLogic 6.0 is cool and only you have to do is to double click it and
it will start installing the software. Follow the installation instruction and install the
software.
On the above screen leave "Sever with Examples" selected and click on the next button.
- 17 -
Leave BEA home directory "C:\\bea" abd Click on the next button.
Leave the default values and click on the next button on the above "Choose Product
Directory" dialog box.
- 18 -
Leave the default selection ( as we don't want the Bea to run as service) and click on the
next button.
- 19 -
Enter password "system123" and click on "Install" button. This will start the WebLogic
installation.
- 20 -
Once the installation is completed, it installer will display the "Install Complete"
confirmation window. Click on the "Done" button to exit the installer.
To run it go to the start menu --> Programs --> BEA WebLogic E-Business Platform-->
Start Default Server. It will ask the password, type the password that you provided during
the installation and then press 'Enter Button'. It will start the WebLogic Server. To check
it open your browser and the key in "http://localhost:7001" and this will show the
welcome page.
Web component consists of all the programs and the files used to provide the user
interface and these may contain JSP, Servlets, images, html files etc. These files are
archived into .war file and deployed on the web server.
- 21 -
Enterprise Bean consists of all the program necessary to provide the business to the
application. These files are archived into .jar file and are deployed on the application
server such as WebLogic 6.0.
You can deploy the web component and the ejb components separately on the web
server and the application server respectively. J2EE specification also provides a way to
package these files into one archive .ear file and then deploy on the server.
In this section we are going to describe you how to write and deploy the web component
on the WebLogic 6.0 web server.
Web component follows the standard directory structure defined in the J2EE
specification.
Root directory of the web archive ('.war' file) contains all the html, jsp, images files and
the additional directories containing these files. In the root directory there is a special
directory 'Web-Inf' which contains the web deployment descriptor (web.xml), classes
and the lib directory.
- 22 -
To download the code for this lesson click here. To deploy this web component download
the code and then extract it in you favorite directory. One directory will be created with
the name of lesson1, go to the leson1 directory and to create the war file issue the
following command from dos prompt:
Web component file with the name of lesson1.war will be created. You can deploy it to
the WebLogic 6.0 server using console. After deploying it using the WebLogic 6.0's
console type http://localhost:7001/lesson1/ to view. Server will serve index.jsp to your
browser.
Now let's see the web.xml file which describes the content of the web component. Here is
the content of web.xml file.
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<welcome-file>
index.jsp
</welcome-file>
<session-config>
<session-timeout>54</session-timeout>
</session-config>
</web-app>
web.xml file start with xml declaration and after the document type declaration <web-
app> tag starts. All the information regarding the content of the .war file are written
between <web-app> and </web-app> tags in the xml format.
In the first lesson we are setting index.jsp as our welcome page and the following lines of
the web.xml file is used to accomplish this.
<welcome-file>
index.jsp
</welcome-file>
<session-config>
<session-timeout>54</session-timeout>
</session-config>
To learn more about writing the web.xml file and deploying the web application on
WebLogic 6.0 please visit:
http://e-docs.bea.com/wls/docs60/adminguide/config_web_app.html
In the next lesson we will write stateless session bean and then deploy on the WebLogic
6.0 Server.
In this lesson you will learn how to develop Hello World Session Bean. We will use ant to
build the application. Our application will be deployed on the Web Logic Application for
testing.
A session bean is similar to an interactive session and is not shared; it can have only one
client, in the same way that an interactive session can have only one user. A session bean
is not persistent and it is destroyed once the session terminates.
A stateless session bean does not maintain a conversational state for the client. When a
client invokes the method of a stateless bean, the bean's instance variables may contain a
state, but only for the duration of the invocation.
Because stateless session beans can support multiple clients, they can offer better
scalability for applications that require large numbers of clients. Typically, an application
requires fewer stateless session beans than stateful session beans to support the same
number of clients.
The state of an object consists of the values of its instance variables. In a stateful session
bean, the instance variables represent the state of a unique client-bean session. Because
- 24 -
the client interacts ("talks") with its bean, this state is often called the conversational
state.
• Remote Interface: The Remote Interface is the client view of the bean.
• Home Interface: The Home Interface contains all the methods for the bean life
cycle (creation, suppression) used by the client application.
• Bean Class: The bean implementation class implements the business methods.
• Deployment Descriptor: The deployment descriptor contains the bean
properties that can be edited at assembly or deployment time.
Steps involved in developing the Stateful Session Bean can be summarized in following
steps:
In case of Stateless Session Bean there is one create method with no arguments. A
remote home interface extends the javax.ejb.EJBHome interface, while a local home
interface extends the javax.ejb.EJBLocalHome interface.
/*
* TestSessionBeanHome.java
*/
package examples;
/**
* Home interface for TestSessionBean.
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
*/
{
public examples.TestSessionBean create()
throws javax.ejb.CreateException,java.rmi.RemoteException;
/*
* TestSessionBean.java
*
*/
package examples;
/**
* Remote interface for TestSessionBean.
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
*/
• public voidejbActivate();
This method is invoked by the container when the instance has just been
reactivated.
/*
* SessionBean.java
*
*/
package examples;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
*/
/**
* The method that returns Hello Message
*
*/
public String SayHello(){
String msg="Hello! I am Session Bean";
System.out.println(msg);
return msg;
}
In the next lesson we will write the deployment descriptors and the servlet to test the
Hello World Session bean
In this section we will write the deployment descriptor for the session bean. We need the
deployment descriptor for application (application.xml), ejb deployment descriptors (ejb-
jar.xml and weblogic-ejb-jar.xml) and web.xml files.
We need the following application deployment descriptor to create our ear file
(example.ear).
<application>
<display-name>Stateless Session Bean Example</dislay-name>
<module>
<web>
<web-uri>example.war</web-uri>
<context-root>/example</context-root>
- 28 -
</web>
</module>
<module>
<ejb>example.jar</ejb>
</module>
</application>
To create example.jar file we need ejb-jar.xml and weblogic-ejb-jar.xml files. Here is the
code for ejb-jar.xml file:
<ejb-jar >
<description>EJB Examples</description>
<display-name>EJB Examples</display-name>
<enterprise-beans>
<ejb-name>ShoppingCart</ejb-name>
<home>examples.ShoppingCartHome</home>
<remote>examples.ShoppingCart</remote>
<ejb-class>examples.ShoppingCartStatefulSessionBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Container</transaction-type>
</session>
<session >
<description>EJB Test Session Bean</description>
<display-name>EJB Test Session Bean</display-name>
<ejb-name>TestSessionBean</ejb-name>
- 29 -
<home>examples.TestSessionBeanHome</home>
<remote>examples.TestSessionBean</remote>
<local-home>examples.TestSessionBeanLocalHome</local-home>
<local>examples.TestSessionBeanLocal</local>
<ejb-class>examples.MyTestSessionBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<env-entry>
<env-entry-name>testSessionBean</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Test Bean</env-entry-value>
</env-entry>
</session>
<session >
<description>EJB Calculator Session Bean</description>
<display-name>EJB Calculator Session Bean</display-name>
<ejb-name>CalculatorBean</ejb-name>
<home>examples.CalculatorBeanHome</home>
<remote>examples.CalculatorBean</remote>
<local-home>examples.CalculatorBeanLocalHome</local-home>
<local>examples.CalculatorBeanLocal</local>
<ejb-class>examples.CalculatorSessionBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<env-entry>
<env-entry-name>CalculatorBean</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Calculator bean</env-entry-value>
</env-entry>
</session>
</enterprise-beans>
<method-permission >
<description>Session Bean</description>
<unchecked/>
<method >
<description>Session Bean</description>
<ejb-name>ShoppingCart</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
</ejb-jar>
The name of our session bean is TestSessionBean, we will call this bean from servlet (as
described in the next page).
<weblogic-ejb-jar>
<description>Session Bean Example</description>
<weblogic-enterprise-bean>
<ejb-name>ShoppingCart</ejb-name>
<stateful-session-descriptor>
</stateful-session-descriptor>
<reference-descriptor>
</reference-descriptor>
<jndi-name>ShoppingCart</jndi-name>
</weblogic-enterprise-bean>
<weblogic-enterprise-bean>
<ejb-name>TestSessionBean</ejb-name>
<stateless-session-descriptor>
</stateless-session-descriptor>
- 31 -
<reference-descriptor>
</reference-descriptor>
<jndi-name>TestSessionBean</jndi-name>
<local-jndi-name>TestSessionBeanLocal</local-jndi-name>
</weblogic-enterprise-bean>
<weblogic-enterprise-bean>
<ejb-name>CalculatorBean</ejb-name>
<stateless-session-descriptor>
</stateless-session-descriptor>
<reference-descriptor>
</reference-descriptor>
<jndi-name>CalculatorSessionBean</jndi-name>
<local-jndi-name>CalculatorBeanLocal</local-jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
The JNDI name for our Stateless Session bean is TestSessionBean. We will use this
JNDI name to lookup the Bean and call it from Servlet.
web.xml file describes the example.war file, which is our web application. Here is the
code of web.xml file:
<web-app >
<distributable/>
<servlet>
<servlet-name>sessionTest</servlet-name>
<display-name>Session Test Servlet</display-name>
<servlet-class>net.roseindia.web.servlets.SessionTestServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sessionTest</servlet-name>
<url-pattern>/SessionServlet</url-pattern>
</servlet-mapping>
</web-app>
- 32 -
Note that in the above web.xml file we have define a servlet named sessionTest. We will
use this servlet to call the Staleless Session Bean. Here is the code of servlet used to call
session bean:
/*
* SessionTestServlet.java
*
*/
package net.roseindia.web.servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import examples.*;
/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
* @web.servlet name="sessionTest"
* display-name="Session Test Servlet"
* load-on-startup="1"
* @web.servlet-mapping url-pattern="/SessionServlet"
*/
TestSessionBeanHome testSessionBean;
TestSessionBeanHome.class);
} catch (Exception NamingException) {
NamingException.printStackTrace();
}
PrintWriter out;
response.setContentType("text/html");
String title = "EJB Example";
out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World Servlet!</title>");
out.println("</head>");
out.println("<body>");
out.println("<p align=\"center\"><font size=\"4\" color=\"#000080\">Serv
let
try{
TestSessionBean beanRemote;
beanRemote = testSessionBean.create();
out.println("<p align=\"center\"> Message from Session Bean is: <b>" +
beanRemote.SayHello() + "</b></p>");
beanRemote.remove();
}catch(Exception CreateException){
CreateException.printStackTrace();
}
out.close();
}
In the next section I will show you how to deploy and test the application.
In this EJB tutorial we will build, deploy and test the Stateles Session Bean developed in
the last section. We will use ant build tool to build ear file. We will deploy our application
using WebLogic console.
I am assuming that you have ant build tool installed on your development environment.
Download the source code from here and extract in your favorite directory. Open
command prompt and navigate to the directory <extracted directory>/sessionbean/code
and type ant there. Ant build tool will compile, package and create example.ear in the
<extracted directory>/sessionbean directory. Here is the code of our ant build file:.
<?xml version="1.0"?>
<target name="init">
<!-- Define -->
<property name="dirs.base" value="${basedir}"/>
<property name="classdir" value="${dirs.base}/build/classes"/>
<property name="src" value="${dirs.base}/src"/>
<property name="web" value="${dirs.base}/web"/>
<property name="deploymentdescription" value="${dirs.base}/deploymentdescriptors"/>
<mkdir dir="${classdir}"/>
</target>
<copy todir="${warDir}/WEB-INF">
<fileset dir="${deploymentdescription}/web/" includes="web.xml" />
</copy>
<copy todir="${warDir}">
<fileset dir="${web}" includes="**/*.*" />
</copy>
</target>
<copy todir="${jarDir}/META-INF">
<fileset dir="${deploymentdescription}/jar/" includes="ejb-jar.xml,weblogic-cmp-rdbms-
jar.xml,weblogic-ejb-jar.xml" />
- 36 -
</copy>
</target>
</project>
Browse "example.ear" and then click on the Upload button. This will upload the file to
the WebLogic server directory and then install the application.
- 39 -
Click on the link "Call Session Test Servlet", it should show you the following output:
- 41 -
check the WebLogic server dos console, it should be displaying the message "Hello! I am
Session Bean" as show below in the screen shot:
In this lesson we learnt how to deploy Session Bean and test on Web Logic Server.
In this EJB tutorial we will learn how to Write Staleles Session Bean for multiplying the
values entered by user. We will use ant build tool to build ear file. We will deploy our
application using WebLogic console.
All remote interfaces must extend javax.ejb.EJBObject. Remote interface is the client
view of session bean. Methods defined in the remote interface are accessible to the client.
In our example we have defined the
public int multiply(int a, int b)
method for calling from JSP. Here is code of our Remote Interface:
- 42 -
package examples;
/**
* Remote interface for CalculatorBean.
*/
public interface CalculatorBean
extends javax.ejb.EJBObject
{
/**
* The method that returns the multiplied value
*/
public int multiply( int val1,int val2 )
throws java.rmi.RemoteException;
package examples;
/**
* Home interface for CalculatorBean.
*/
public interface CalculatorBeanHome
extends javax.ejb.EJBHome
{
public static final String COMP_NAME="java:comp/env/ejb/CalculatorBea
n";
public static final String JNDI_NAME="CalculatorSessionBean";
All Bean class are defined as public and implements the javax.ejb.SessionBean. In the
bean class we have implemented the code for
public int multiply(int a, int b)
1. ejbCreate()
2. ejbRemove()
- 43 -
3. ejbActivate()
4. ejbPassivate()
5. setSessionContext(SessionContext aContext)
/*
* SessionBean.java
*
*/
package examples;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
*/
/**
* This is the Test Session Bean
*
*/
/**
* The method that returns the multiplied value
*
*/
public int multiply(int val1, int val2){
System.out.println("I am from multiply : " + val1 + " * " + val2);
return val1*val2;
}
For creating example.jar ejb-jar.xml and weblogic-ejb-jar.xml files are required which
explains the content of jar file.
ejb-jar.xml file:
<ejb-jar >
<description>EJB Examples</description>
<display-name>EJB Examples</display-name>
<enterprise-beans>
<ejb-name>ShoppingCart</ejb-name>
<home>examples.ShoppingCartHome</home>
<remote>examples.ShoppingCart</remote>
<ejb-class>examples.ShoppingCartStatefulSessionBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Container</transaction-type>
</session>
<session >
<description>EJB Test Session Bean</description>
<display-name>EJB Test Session Bean</display-name>
<ejb-name>TestSessionBean</ejb-name>
- 45 -
<home>examples.TestSessionBeanHome</home>
<remote>examples.TestSessionBean</remote>
<local-home>examples.TestSessionBeanLocalHome</local-home>
<local>examples.TestSessionBeanLocal</local>
<ejb-class>examples.MyTestSessionBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<env-entry>
<env-entry-name>testSessionBean</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Test Bean</env-entry-value>
</env-entry>
</session>
<session >
<description>EJB Calculator Session Bean</description>
<display-name>EJB Calculator Session Bean</display-name>
<ejb-name>CalculatorBean</ejb-name>
<home>examples.CalculatorBeanHome</home>
<remote>examples.CalculatorBean</remote>
<local-home>examples.CalculatorBeanLocalHome</local-home>
<local>examples.CalculatorBeanLocal</local>
<ejb-class>examples.CalculatorSessionBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<env-entry>
<env-entry-name>CalculatorBean</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Calculator bean</env-entry-value>
</env-entry>
</session>
</enterprise-beans>
<method-permission >
<description>Session Bean</description>
<unchecked/>
<method >
<description>Session Bean</description>
<ejb-name>ShoppingCart</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
- 46 -
</ejb-jar>
Above deployment descriptor defines remote, home and bean class for the bean and
assigns a name 'CalculatorBean' to the session bean. Please note that bean of Stateless type
and is defined by:
<session-type>Stateless</session-type>
weblogic-ejb-jar.xml file:
<weblogic-ejb-jar>
<description>Session Bean Example</description>
<weblogic-enterprise-bean>
<ejb-name>ShoppingCart</ejb-name>
<stateful-session-descriptor>
</stateful-session-descriptor>
<reference-descriptor>
</reference-descriptor>
<jndi-name>ShoppingCart</jndi-name>
</weblogic-enterprise-bean>
<weblogic-enterprise-bean>
<ejb-name>TestSessionBean</ejb-name>
<stateless-session-descriptor>
</stateless-session-descriptor>
<reference-descriptor>
</reference-descriptor>
<jndi-name>TestSessionBean</jndi-name>
<local-jndi-name>TestSessionBeanLocal</local-jndi-name>
</weblogic-enterprise-bean>
<weblogic-enterprise-bean>
<ejb-name>CalculatorBean</ejb-name>
<stateless-session-descriptor>
</stateless-session-descriptor>
<reference-descriptor>
</reference-descriptor>
<jndi-name>CalculatorSessionBean</jndi-name>
- 47 -
<local-jndi-name>CalculatorBeanLocal</local-jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
Our JSP file access the session bean and uses it for the calculation and displays the result.
For this purpose we are using calculator.jsp which displays a form to accept two numbers
from the user and submits the form data to calculator.jsp. Here is our calculator.jsp:
<%@page language="java"
import="examples.*,javax.naming.*,javax.rmi.PortableRemoteObject"%>
<%!
}
}
%>
<html>
<head>
<title>Calculator Bean</title>
</head>
- 48 -
<body>
%>
<td width="310"><input type="text" name="val1" size="8" value="<%=val1%>"> <b>*
</b><input type="text" name="val2" size="8" value="<%=val2%>"><input type="submit"
value="Calculate" name="B1"></td>
</tr>
<%
if(request.getParameter("val1")!=null){
int result=0;
try{
result=beanRemote.multiply(Integer.parseInt(val1),Integer.parseInt(val2));
}catch(Exception e){
System.out.println(e.getMessage());
}
%>
<tr>
<td width="86"><b>Result</b></td>
<td width="310"><b> = <%=result%></b></td>
</tr>
<%
%>
<tr>
<td width="396" colspan="2"></td>
</tr>
</table>
</center>
</div>
- 49 -
</form>
</body>
</html>
For creating war file we need web.xml, which is same as in previous lesson.
For creating example.ear application.xml, file is required which explains the content of
enterprise archive, which is same as in previous lesson.
I am assuming that you have ant build tool installed on your development environment.
Download the source for from here and extract in your favorite directory. Open
command prompt and navigate to the directory <extracted directory>/sessionbean/code
and type ant there. Ant build tool will compile, package and create example.ear in the
<extracted directory>/sessionbean directory. Here is the code of our ant build file:.
Please refer to previous lesson for deploying the application on WebLogic Server.
Click on the link "Calculator Links", it should display the form to enter the two values:
Click on the Calculate button to view the result. Following should be displayed:
- 51 -
In this lesson we learnt how to develop, build, deploy and test Calculator Session Bean
on Web Logic Server.
In this section of EJB tutorial, we will learn about the lifecycle of Stateful and Stateless
Session Beans.
There are two stages in the Lifecycle of Stateless Session Bean. These are:
There are there stages in the life cycle of Stateful Session bean Life cycle. These are:
c) Passive state
In the Passive state the bean is passivated to conserve the resource. The passivate method
is called before the instance enters the "passive" state. The instance should release any
resources that it can re-acquire later in the ejbActivate() method. After the passivate
method completes, the instance must be in a state that allows the container to use the Java
Serialization protocol to externalize and store away the instance's state. ejbRemove or
Timeout moves the bean into Does Not Exist stage.
- 53 -