You are on page 1of 13

Introduction To Enterprise Java Bean(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

Distributed Architecture

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


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


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.

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

Why EJB (Enterprise Java Beans)?


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 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 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 comes 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's else 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 model for capturing distributed business components. It hides from us the details we might have to worry about ourself if we were writing an RMI application.

Application Servers Available in Market


Application Servers

BEA WebLogic Server iPlanet Oracle Orion Server WebSphere NetDynamics JRun Server Tomcat JOnAS Pramati Server

Power Tier for J2EE

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. 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 provide 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 'Webinf' which contains the web deployment descriptor (web.xml), classes and the lib directory. 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: <session-config> <session-timeout>54</session-timeout> </session-config>

Writing 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 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. 2. 3. 4. 5. Define Home Interface Define Remote Interface Develop EJB class Write deployment descriptors 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 { 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. 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 import import import import java.rmi.RemoteException; javax.ejb.CreateException; javax.ejb.EJBException; javax.ejb.SessionBean; 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 EJBException { } public void ejbActivate() throws EJBException { } 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; } }

You might also like