Anda di halaman 1dari 53

-1-

Introduction To Enterprise Java Beans (EJB)


Enterprise Java Bean architecture is the component architecture for the development and
deployment of robust, world class component-based distributed application using the java
language. EJB is a complex topic and requires a lot of effort to master it.

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:

1. Introduction to Distributed Applications and Components


2. Introduction to J2EE architecture.
3. Enterprise Java Beans (EJB) - An Introduction
4. Why Enterprise Java Beans (EJB)?
5. Application Servers Available in the market.
6. Downloading and Installing the WebLogic 6.0 server.
7. Introduction to Enterprise Java Beans and developing you first web component.
8. Developing Hello World Session Bean
9. Writing Deployment Descriptor and Client Code for Stateless Session Bean
10. Deploying Hello World Session Bean on WebLogic Server
11. Writing Calculator Session Bean and Testing on WebLogic Server
12. Understanding Stateful and Stateless Session Beans Life cycle
13. Writing Stateless Session Bean
14. Introduction to the Entity Beans
15. Writing your first Entity Bean
16. Writing Entity Bean with Container Managed Persistence
17. Writing Entity Bean with Bean Managed Persistence
18. Deploying Entity Bean
19. Summing up
-2-

1. Introduction to Distributed Applications and Components

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.

Problems of Two-tier Architecture

• Easy to install, but very difficult to maintain.


• Problem of installing and upgrading data access software on each client machine.
• It is very difficult to reuse the business and presentation logic.
• These two-tier applications are not very scalable and therefore not well suited to
the Internet and Intranet Applications.

Multi tiered J2EE Architecture

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.

J2EETM Architecture consists of following technologies:

• Java Database Connectivity (JDBC)


• Java Naming and Directory Interface (JNDI)
• Enterprise Java Beans (EJB)
• Java Server Pages (JSP)
• Java Servlets
• Remote Method Invocation (RMI)
• Java IDL/CORBA

1. Java Database Connectivity or JDBC for short


-3-

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

2. Java Naming and Directory Interface (JNDI)

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.

Visit: http://java.sun.com/products/jndi for downloading and more information.

3. Enterprise JavaBeans or EJB for short

Sun Microsystem's definition of Enterprise JavaBeans is:

"The Enterprise JavaBeans architecture is a component architecture for developing and


deployment of component-based distributed applications. Applications written using the
Enterise JavaBeans are scalable, transactional, and multi-user secure. These applications
may be written once, and then deployed on any server platform that supports the
Enterprise JavaBeans specification."

The EJB specification defines the EJB component architecture and the interfaces between
the Enterprise JavaBeans technology-enabled server and the component.

There are three types of Beans:

A) Stateless Session Beans:

These beans do not maintain the state, and the information stored in these beans are lost
when the server crashes.

b) Statefull Session Beans:

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.

4. Java Server Pages or JSP for short:


-4-

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 .

6. Remote Method Invocation (RMI)

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.

2. Introduction to J2EE architecture

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.

Enterprise Distributed Object Computing (EDOC)

Distributed computing allows a business system to be more accessible. Distributed


systems allow parts of the system to be located on separate computers located in different
locations, where they make the most sense. That is, distributed computing allows
business logic and data to be reached from remote locations at any time from anywhere
by any one. The most recent development in distributed computing is distributed object
computing. The technologies such as Java RMI, CORBA and Microsoft's DCOM help to
accomplish distributed object computing paradigm by allowing objects running on one
computer to be accessed for servicing the clients in other computers.

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.

Transaction Processing (TP) Monitors


-6-

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.

Object Request Brokers (ORBs)

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.

Component Transaction Monitor (CTM)

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-

address the complexities of managing a component in a high-volume, mission-critical


environment, an area where TP monitors have always excelled.

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.

Consequently, a critical mass of enterprise computing vendors - developers of application


servers, transaction process monitors, object request brokers, database management
systems, and others - are rolling out precise, robust and powerful implementations of the
EJB technology specifications. Component-based, multi-tier applications are the future of
enterprise computing. EJB is poised to realize the benefits of these components:
portability, scalability to a wide range of enterprise servers, simplified development,
deployment, and maintenance. With this brief background information on EJBs, let us
enter a very brief discussion on EJB's robust architecture.

3. Enterprise JavaBeans - An Introduction

Enterprise JavaBeans (EJB) is a comprehensive technology that provides the


infrastructure for building enterprise-level server-side distributed Java components. The
EJB technology provides a distributed component architecture that integrates several
enterprise-level requirements such as distribution, transactions, security, messaging,
persistence, and connectivity to mainframes and Enterprise Resource Planning (ERP)
systems. When compared with other distributed component technologies such as Java
RMI and CORBA, the EJB architecture hides most the underlying system-level semantics
that are typical of distributed component applications, such as instance management,
object pooling, multiple threading, and connection pooling. Secondly, unlike other
component models, EJB technology provides us with different types of components for
business logic, persistence, and enterprise messages.
-8-

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

Any distributed component technology should have the following requirements:

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

2. We need to obtain a reference to client-side proxy object. In order to communicate with


the server-side object, the client needs to obtain a reference to the proxy.

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.

Enterprise JavaBeans server-side components come in two fundamentally different types:


entity beans and session beans.

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.

Session beans are transaction-aware. In a distributed component environment, managing


transactions across several components mandates distributed transaction processing. The
EJB architecture allows the container to manage transactions declaratively. This
mechanism lets a bean developer to specify transactions across bean methods. Session
beans are client-specific. That is, session bean instances on the server side are specific to
the client that created them on the client side. This eliminates the need for the developer
to deal with multiple threading and concurrency.

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: Stateful and Stateless

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.

Entity Beans: Container and Bean Managed Persistence

An example entity bean in a B2B application is given as follows. A purchase order is a


business identity and requires persistence store such as a relational database. The various
purchase order attributes can be defined as the attributes of an entity bean. Since database
operations involve create, update, load, delete, and find operations, the EJB architecture
- 11 -

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

4. Why Enterprise Java Beans (EJB)?

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.

3. Transactions - The most important feature for a distributed component model is


transactions. RMI does not support transactions. If we develop an RMI-based application,
we need to address how we will support transactions. That is, we need to keep track of
when a client begins a transaction, what RMI objects that client changes, and commit and
roll back those changes when the client is done. This is further compounded by the fact
that most distributed object systems support more than one client at a time. Different
transaction models are much more incompatible than different searching or security
models. While client coders can get around differences in search and security models by
being aware of those differences, transaction models can almost never be made to work
together.

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.

5. Application Servers Available in Market

Application Servers

1. BEA WebLogic Server

2. iPlanet

3. Oracle

4. Orion Server

5. WebSphere

6. NetDynamics

7. JRun Server

8. Tomcat

9. JOnAS

10. Pramati Server

11. Power Tier for J2EE

6. Downloading and Installing WebLogic server 6.0

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.

Download the weblogic610sp3_win.exe from http://www.bea.com. To start the


installation double click on the weblogic610sp3_win.exe file. This will start the
InstallAnywhere installer as shown below.

Installer will display Installation wizard as show below.

Click on the Next button. License Agreement page.


- 16 -

Select "Yes" and then click on Next button.

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 values and click on the next button.

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.

To start the Administrative consol of WebLogic type "http://localhost:7001/console". This


will ask you the user and password; give 'system' as user and the password of the
WebLogic server. Now explore the administrative console yourself.

7. Developing web component

Introduction to Java Beans

J2EE specification defines the structure of a J2EE application. According to the


specification J2EE application consists of two components, web component and the
enterprise bean.

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.

Writing and deploying the web component

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.

Directory Structure of Web Component


/
index.htm, JSP, Images etc..
Web-inf
web.xml
classes
servlet classes
lib
jar files

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:

c:\mydir\lesson1> jar cf lesson1.war *

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.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!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>

and the following code sets the session time:


- 23 -

<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.

8. Developing Hello World Session Bean

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.

What is Session Bean?


Session is one of the EJBs and it represents a single client inside the Application Server.
Stateless session is easy to develop and its efficient. As compare to entity beans session
beans require few server resources.

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.

Session Bean Types


Session Beans are of two types, Stateful Session Bean and Stateless Session Bean.

Stateless Session Beans

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.

Stateful Session Beans

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.

Writing Stateful Session Bean


A Session Bean is composed of the following parts:

• 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:

1. Define Home Interface


2. Define Remote Interface
3. Develop EJB class
4. Write deployment descriptors
5. Package, deploy and test the application

Define Home Interface


The Session bean's home interface defines one or more create(...) methods and each
create method must be named create and must match one of the ejbCreate methods
defined in the enterprise Bean class. The return type of a create method is the Bean's
remote interface type.

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.

Here is the source code of our home interface:

/*
* TestSessionBeanHome.java
*/
package examples;

/**
* Home interface for TestSessionBean.
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
*/

public interface TestSessionBeanHome


extends javax.ejb.EJBHome
- 25 -

{
public examples.TestSessionBean create()
throws javax.ejb.CreateException,java.rmi.RemoteException;

Define Remote Interface


As mentioned earlier, Remote Interface is the client view of the bean and the functions
defined in the remote interface is visible to the client. There should be an implementation
in the Bean class for the all the functions defined in the remote interface.

Here is the source code of our Remote Interface:

/*
* TestSessionBean.java
*
*/
package examples;

/**
* Remote interface for TestSessionBean.
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
*/

public interface TestSessionBean


extends javax.ejb.EJBObject
{
/**
* The method that returns Hello Message
*/
public java.lang.String SayHello( )
throws java.rmi.RemoteException;

Define Enterprise Bean Class


In the EJB class we write all the business methods along with required that is necessary
to implement. In the EJB class methods are defined public. The Session Bean interface
methods that the EJB provider must must be defined in the Session bean class are:

• public void setSessionContext(SessionContext ic);


This method is used by the container to pass a reference to the SessionContext to
the bean instance.
• public void ejbRemove();
This method is invoked by the container when the instance is in the process of
being removed by the container.
• public void ejbPassivate();
This method is invoked by the container when it wants to passivate the instance.
- 26 -

• public voidejbActivate();
This method is invoked by the container when the instance has just been
reactivated.

A stateful session Bean with container-managed transaction demarcation can optionally


also implements the javax.ejb.SessionSynchronization interface.

The Session Synchronization interface methods that must be developed are:

• public void afterBegin();


This method notifies a session Bean instance that a new transaction has started.
• public void afterCompletion(boolean committed);
This method notifies a session Bean instance that a transaction commit protocol
has completed and tells the instance whether the transaction has been committed
or rolled back.
• public void beforeCompletion();
This method notifies a session Bean instance that a transaction is about to be
committed.

Here is the source code of our Session Bean class:

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

public class MyTestSessionBean implements SessionBean{

public void ejbCreate() throws CreateException {

public void setSessionContext( SessionContext aContext ) throws EJBExc


eption {

public void ejbActivate() throws EJBException {


- 27 -

public void ejbPassivate() throws EJBException {

public void ejbRemove() throws EJBException {

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

9. Writing Deployment Descriptor and Client Code for


Stateless 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.

Application Deployment descriptor:

We need the following application deployment descriptor to create our ear file
(example.ear).

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE application PUBLIC '-//Sun Microsystems, Inc.//DTD J2EE Application 1.2//EN'


'http://java.sun.com/j2ee/dtds/application_1_2.dtd'>

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

EJB Deployment descriptor:

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:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"
"http://java.sun.com/dtd/ejb-jar_2_0.dtd">

<ejb-jar >

<description>EJB Examples</description>
<display-name>EJB Examples</display-name>

<enterprise-beans>

<!-- Session Beans -->


<session >
<description>Shopping Cart Session Bean</description>
<display-name>Shopping Cart Session Bean</display-name>

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

<!-- Relationships -->

<!-- Assembly Descriptor -->


<assembly-descriptor >
- 30 -

<method-permission >
<description>Session Bean</description>
<unchecked/>
<method >
<description>Session Bean</description>
<ejb-name>ShoppingCart</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>

<!-- transactions -->


<container-transaction >
<method >
<ejb-name>ShoppingCart</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
</assembly-descriptor>

</ejb-jar>

The name of our session bean is TestSessionBean, we will call this bean from servlet (as
described in the next page).

The code for weblogic specific ejb deployment descriptor(weblogic-ejb-jar.xml) is as


follows:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE weblogic-ejb-jar PUBLIC "-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB//EN"
"http://www.bea.com/servers/wls600/dtd/weblogic-ejb-jar.dtd">

<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 for war file:

web.xml file describes the example.war file, which is our web application. Here is the
code of web.xml file:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<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"
*/

public class SessionTestServlet extends HttpServlet {

TestSessionBeanHome testSessionBean;

public void init(ServletConfig config) throws ServletException{


//Look up home interface
try {
InitialContext ctx = new InitialContext();
Object objref = ctx.lookup("TestSessionBean");
testSessionBean = (TestSessionBeanHome)PortableRemoteObject.narr
ow(objref,

TestSessionBeanHome.class);
} catch (Exception NamingException) {
NamingException.printStackTrace();
}

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
- 33 -

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

Calling Session Bean</font></p>");

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.println("<p align=\"center\"><a href=\"javascript:history.back()\">G


o to Home</a></p>");
out.println("</body>");
out.println("</html>");

out.close();
}

public void destroy() {


System.out.println("Destroy");
}
}

In the next section I will show you how to deploy and test the application.

10.Deploying Hello World Session Bean on WebLogic Server

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.

Building ear file using ant build tool


- 34 -

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"?>

<project name="WebLogic Tutorials" default="all" basedir=".">

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

<property name="warFile" value="example.war"/>


<property name="earFile" value="example.ear"/>
<property name="jarFile" value="example.jar"/>

<property name="earDir" value="${dirs.base}/build/ear"/>


<property name="warDir" value="${dirs.base}/build/war"/>
<property name="jarDir" value="${dirs.base}/build/jar"/>

<!-- classpath for Project -->


<path id="library.classpath">
<pathelement path ="libext/servlet-api.jar"/>
<pathelement path ="libext/j2ee.jar"/>
<pathelement path ="libext/jdbc2_0-stdext.jar"/>
<pathelement path ="${classpath}"/>
</path>

<!-- Create Web-inf and classes directories -->


<mkdir dir="${warDir}/WEB-INF"/>
<mkdir dir="${warDir}/WEB-INF/classes"/>

<!-- Create Meta-inf and classes directories -->


<mkdir dir="${earDir}/META-INF"/>
<mkdir dir="${jarDir}/META-INF"/>
- 35 -

<mkdir dir="${classdir}"/>

</target>

<!-- Main target -->


<target name="all" depends="init,build,buildWar,buildJar,buildEar"/>

<!-- Compile Java Files and store in /build/src directory -->


<target name="build" >
<javac srcdir="${src}" destdir="${classdir}" debug="true" includes="**/*.java" >
<classpath refid="library.classpath"/>
</javac>
</target>

<!-- Create the web archive File -->


<target name="buildWar" depends="init">
<copy todir="${warDir}/WEB-INF/classes">
<fileset dir="${classdir}" includes="**/*.class" />
</copy>

<copy todir="${warDir}/WEB-INF">
<fileset dir="${deploymentdescription}/web/" includes="web.xml" />
</copy>

<copy todir="${warDir}">
<fileset dir="${web}" includes="**/*.*" />
</copy>

<!-- Create war file and place in ear directory -->


<jar jarfile="${earDir}/${warFile}" basedir="${warDir}" />

</target>

<!-- Create the jar File -->


<target name="buildJar" depends="init">
<copy todir="${jarDir}">
<fileset dir="${classdir}" includes="**/*.class" />
</copy>

<copy todir="${jarDir}/META-INF">
<fileset dir="${deploymentdescription}/jar/" includes="ejb-jar.xml,weblogic-cmp-rdbms-
jar.xml,weblogic-ejb-jar.xml" />
- 36 -

</copy>

<!-- Create jar file and place in ear directory -->


<jar jarfile="${earDir}/${jarFile}" basedir="${jarDir}" />

</target>

<!-- Create the ear File -->


<target name="buildEar" depends="init">
<copy todir="${earDir}/META-INF">
<fileset dir="${deploymentdescription}/ear" includes="application.xml" />
</copy>

<!-- Create ear file and place in ear directory -->


<jar jarfile="../${earFile}" basedir="${earDir}" />
</target>

</project>

Deploying the Application on Web Logic 6.0 Server

Run the WebLogic default server:

To deploy the application we will use WebLogic console. Type


http://localhost:7001/console and enter user name and password to open the WebLogic
console.
- 37 -

Navigate to "Applications" and then click on "Install a new Application", following


screen will be displayed:
- 38 -

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 -

Testing the application


To test the application open browser and type http://localhost:7001/example/index.jsp,
following page should be displayed:
- 40 -

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.

11.Writing Calculator Session Bean and Testing on WebLogic


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.

Enterprise Bean remote interface

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;

Enterprise Bean Home interface

All home interfaces must extend javax.ejb.EJBHome. 'create()' method of home


interface of the application enables the client to create and remove the session object.

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";

public examples.CalculatorBean create()


throws javax.ejb.CreateException,java.rmi.RemoteException;

Enterprise Bean class

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)

Besides this method other required methods which is to be implemented are:

1. ejbCreate()
2. ejbRemove()
- 43 -

3. ejbActivate()
4. ejbPassivate()
5. setSessionContext(SessionContext aContext)

Here is the code for our Calculator Session Bean:

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

public class CalculatorSessionBean implements SessionBean{

public void ejbCreate() throws CreateException {

public void setSessionContext( SessionContext aContext ) throws EJBExc


eption {

public void ejbActivate() throws EJBException {

public void ejbPassivate() throws EJBException {

public void ejbRemove() throws EJBException {


- 44 -

/**
* 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;
}

Jar Descriptor File

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:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans
2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">

<ejb-jar >

<description>EJB Examples</description>
<display-name>EJB Examples</display-name>

<enterprise-beans>

<!-- Session Beans -->


<session >
<description>Shopping Cart Session Bean</description>
<display-name>Shopping Cart Session Bean</display-name>

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

<!-- Relationships -->

<!-- Assembly Descriptor -->


<assembly-descriptor >

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

<!-- transactions -->


<container-transaction >
<method >
<ejb-name>ShoppingCart</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
</assembly-descriptor>

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

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE weblogic-ejb-jar PUBLIC "-//BEA Systems, Inc.//DTD WebLogic 6.0.0
EJB//EN" "http://www.bea.com/servers/wls600/dtd/weblogic-ejb-jar.dtd">

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

The WebLogic deployment descriptor assigns jndi name 'CalculatorSessionBean' to the


'CalculatorBean' bean.

Writing JSP and Web/Ear component

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"%>

<%!

private CalculatorBean beanRemote=null;

public void jspInit(){


//Look up home interface
try {
CalculatorBeanHome calculatorBean;
InitialContext ctx = new InitialContext();
Object objref = ctx.lookup("CalculatorSessionBean");
calculatorBean = (CalculatorBeanHome)PortableRemoteObject.narrow(objref,
CalculatorBeanHome.class);
beanRemote=calculatorBean.create();
} catch (Exception NamingException) {
NamingException.printStackTrace();
}
}

public void jspDestroy(){


try {
//calculatorBean.remove();
beanRemote.remove();
}catch(Exception e){

}
}

%>
<html>

<head>
<title>Calculator Bean</title>
</head>
- 48 -

<body>

<form method="POST" action="calculator.jsp">


<div align="center">
<center>
<table border="0" cellpadding="0" cellspacing="0" width="400">
<tr>
<td colspan="2" width="398"><b><font size="5">Calculator</font></b></td>
</tr>
<tr>
<td width="86"><b>Calculate</b></td>
<%
String val1 = request.getParameter("val1");
String val2 = request.getParameter("val2");
if(val1==null) val1="10";
if(val2==null) val2="5";

%>
<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>&nbsp; = <%=result%></b></td>
</tr>
<%

%>
<tr>
<td width="396" colspan="2"></td>
</tr>
</table>
</center>
</div>
- 49 -

</form>

</body>

</html>

Web-Component Descriptor File

For creating war file we need web.xml, which is same as in previous lesson.

J2EE Enterprise Archive (ear) Descriptor File

For creating example.ear application.xml, file is required which explains the content of
enterprise archive, which is same as in previous lesson.

Building ear file using ant build tool

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:.

Deploying the Application on Web Logic 6.0 Server

Please refer to previous lesson for deploying the application on WebLogic Server.

Testing the application


To test the application open browser and type http://localhost:7001/example/index.jsp,
following page should be displayed:
- 50 -

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.

12.Understanding Stateful and Stateless Session Beans Life


cycle

In this section of EJB tutorial, we will learn about the lifecycle of Stateful and Stateless
Session Beans.

Stateless Session Bean Life cycle

There are two stages in the Lifecycle of Stateless Session Bean. These are:

a) Does Not Exist


In the Does Not Exist stage, bean does not have instance in the memory. In this stage
bean has not been instantiated.

b) Method Ready Pool


In the Method Ready Pool stage bean has instance(s) in the memory of the EJB container
and it is ready to serve clients. On the startup of the EJB container some instances of the
bean are created and placed in the pool. EJB container creates the new instance of the
Bean and then sets the session context (setSessioncontext()) and it calls the ejbCreate()
method to place the bean in the Method Ready Pool stage. Container calls the
ejbRemove() method to move the bean into Does Not Exist state.

Following Diagram shows the Life cycle of Stateless Session Bean


- 52 -

Stateful Session Bean Life cycle

There are there stages in the life cycle of Stateful Session bean Life cycle. These are:

a) Does Not Exist


This is the Does Not Exist stage, bean does not have instance in the memory. In this stage
bean has not been instantiated.

b) Method Ready Pool


In the Method Ready Pool stage bean has instance in the memory of the EJB container
and it is ready to serve client. One instance of the Stateful Session Bean servers only one
client. When Client Calls create(args) method on the Home Interface, server creates new
instance of the bean and sets the Session Context and then container calls the
ejbCreate(args) method on the bean and places the bean into Method Ready Pool stage.
ejbRemove or Timeout moves the bean into Does Not Exist stage.

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 -

Following Diagram shows the Life cycle of Statelful Session Bean

Anda mungkin juga menyukai