Saturday, June 14, 2008

EJB [Stateful Session Bean]

Introduction:
In last article, discussed about Stateless Session Bean with example. In this I will discuss about Stateful Session Bean which is part of EJB, contains information about Stateful Session Bean, advantages, limitations, when to use this bean, and a complete example as well as steps to develop Stateful Session Bean using Sun Java System Application Server 8.2 with Netbeans 5.0. Software and version used in this are:


  • Jdk1.5.0
  • Sun Java System Application Server 8.2
  • Net Beans 5.0
  • EJB 2.2

Definition:
It is a server-side enterprise component that encapsulates the business logic of an application. Implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute “Stateful”. Called "stateful" because they maintain a conversational state with the client, in other word we can say that, a client want to store information across various request, means we want to maintain all actions performed by client, for e.g. Online Shopping Application.

Following are advantages of Stateful Session Bean:

  • Maintains the state of a client
  • Stores client state in instance variable
  • Can used when information need to be used various methods calls

Limitations of Stateful Session Bean:

  • Stateful bean instance can service the requests of a single client only
  • Not having persistent storage mechanism
  • Reduces application scalability

When to Use Stateful Session Beans?

  • The bean's state represents the interaction between the bean and a specific client.
  • The bean needs to hold information about the client across method invocations.
  • The bean mediates between the client and the other components of the application, presenting a simplified view to the client.
  • Behind the scenes, the bean manages the work flow of several enterprise beans.

Life Cycle of Stateful Session Bean
Following figures shows the life cycle stages of a Stateful session Bean. The client initiates the life cycle by invoking the create method. The EJB container instantiates the bean and then invokes the setSessionContext and ejbCreate methods in the session bean. The bean is now ready to have its business methods invoked.

Life Cycle of a Stateful Session Bean

While in the ready stage, the EJB container may decide to deactivate, or passivate, the bean by moving it from memory to secondary storage. (Typically, the EJB container uses a least-recently-used algorithm to select a bean for passivation.)

The EJB container invokes the bean's ejbPassivate method immediately before passivating it. If a client invokes a business method on the bean while it is in the passive stage, the EJB container activates the bean, calls the bean's ejbActivate method, and then moves it to the ready stage.

At the end of the life cycle, the client invokes the remove method, and the EJB container calls the bean's ejbRemove method. The bean's instance is ready for garbage collection.

How to Create Stateful Session Bean:

Following are Steps to Create EJB [Stateful Session Bean] with NetBean 5.0 using Sun Java System Application Server 8

  • File -> New Project-> Enterprise -> EJB Module
  • Type Project Name: MyCourseEJB

  • Click on Finish Button.
  • Right Click on MyCourseEJB -> New-> SessionBean

  • EJB Name: Course -> Package : university
  • Session Type: Stateful -> Create Interface : Remote

  • Click on Finish
  • MyCourseEJB -> Source Package -> university
  • Delete CourseRemoteBusiness.java

  • Replace CourseBean with Following Code

//CourseBean.java

package university;

import java.util.Enumeration;
import java.util.Vector;
import javax.ejb.*;

/**
* This is the bean class for the CourseBean enterprise bean.
* @author rahulk
*/
public class CourseBean implements SessionBean
{
private SessionContext context;

String studentName;
String studentRollNo;
Vector selectedCourse;

public void setSessionContext(SessionContext aContext)
{
context = aContext;
}

public void ejbActivate() { }

public void ejbPassivate() { }

public void ejbRemove()
{
studentName = null;
studentRollNo = null;
}

public void ejbCreate(String sName, String sRollNo) throws CreateException
{

if(sName == null)
{
throw new CreateException ("Null Person not allowed");
}
else
{
studentName = sName;
studentRollNo = sRollNo;
}
selectedCourse = new Vector();
}

public String addCourse(String Cname)
{
if (Cname==null)
{
return "";
}
try
{
if(!selectedCourse.isEmpty())
{
Enumeration enumer = selectedCourse.elements();
String title="";
while(enumer.hasMoreElements())
{
title = (String)enumer.nextElement();
if(title!=null)
{
/* Checks whether a same course is again selected.*/
if(Cname.equals(title))
{
return "You have already selected this course";
}
}
} // end of while loop

/* Adds the course in the cart.*/

selectedCourse.addElement(Cname);
} // end of if
else
{
/* Adds the course in the cart.*/
selectedCourse.addElement(Cname);
}
}
catch(Exception e)
{
return "Error : " + e.toString();
}
return "";
}

public String removeCourse(String Cname)
{

/* Removes a course from the cart.*/
boolean result = selectedCourse.removeElement(Cname);
if (result == false)
{
return Cname + "course is not in cart.";
}
return "Course Removed";
}

public Vector getSelectedCourse()
{
return selectedCourse;
}

}

  • Replace CourseRemote with Following Code

//CourseRemote.java

package university;

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


/**
* This is the remote interface for Course enterprise bean.
*/
public interface CourseRemote extends EJBObject
{

public String addCourse(String cName)throws RemoteException;
public String removeCourse(String cName) throws RemoteException;
public Vector getSelectedCourse() throws RemoteException;
}

  • Replace CourseRemoteHome with Following Code

//CourseRemoteHome.java

package university;

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


/**
* This is the home interface for Course enterprise bean.
*/
public interface CourseRemoteHome extends EJBHome
{

CourseRemote create(String sName, String sRollNo) throws CreateException, RemoteException;

}

  • Right Click on MyCourseEJB -> DeployProject

Step to Create EJB(Stateful Session Bean) Web Client Application

  • File -> New Project -> Category : web -> Web Application

  • Next- > Project Name: MyCourseWeb -> Server : Sun Java System Application Server

  • Click on Finish Button.

Add the Reference of EJB Module to Client

  • MyCourseWeb -> Right Click on Libraries -> Add Project

  • Select the Name of EJB Module [MyCourseEJB] -> Add Project JAR Files

Replace index.jsp page with following code

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Details</title>
</head>
<body bgcolor="pink">

<h1><center>Student Information</center></h1>
<hr>
<br><h2> <center> Please Enter the Following Details !!!</center> </h2> <br>
<form method="get" name="f1" action="courseCart.jsp">

<table align="center">
<tr>
<td> <b>Name of Student : </b></td>
<td> <input type="text" name="stdname" size="20"> </td> </tr>
<tr>
<td> <b>Student Roll Number: </b> </td>
<td> <input type="text" name="stdrollno" size="20"></td>
</tr>
<tr>
<td align="right"> <b><input type="submit" value="Submit"> </b> </td>
<td align="center"> <b> <input type="reset" value="Reset"> </b></td>
</tr>
</table>

</form>
</body>
</html>

Steps to create a JSP file

  • Right click on Web Pages -> New -> JSP…
  • JSP File Name : courseCart

  • Click on Finish Button

Replace courseCart.jsp page with following code

< %@ page import="javax.ejb.*,javax.naming.*, javax.rmi.PortableRemoteObject,java.rmi.RemoteException,university.*,java.util.*" %>

< %!
private CourseRemote course = null;
CourseRemoteHome home=null;
public void _jspInit()
{
/* Locating the stateful session bean.*/
try
{
Context ic = new InitialContext();
Object objRef = ic.lookup("ejb/CourseBean");
home=(CourseRemoteHome)PortableRemoteObject.narrow(objRef, CourseRemoteHome.class);
}
catch(Exception ex){ } } %>
< html> < head>
< title>University Registration Application< /title> < /head>
< body bgcolor="pink">
< form method="get" name="f1">
< %
String stdname = request.getParameter("stdname");
String stdrollno = request.getParameter("stdrollno");
if ( stdname != null && stdname.length() > 0 )
{
if ( stdrollno != null && stdrollno.length() > 0 )
{
/* Creating a bean instance.*/
course = home.create(stdname,stdrollno);
} } %>
< H1>University Registration Application< /h1>
< p>Welcome < %=stdname%> !!!< /p>
< p> Please a Course Subject
< select name=ch size=1>
< option>C, C++< /option> < option>Core Java< /option>
< option>J2EE< /option> < option>VB.NET< /option>
< option>C#.NET< /option> < option>ASP.NET< /option>
< option>Oracle< /option> < option selected value="--"> Select a Course< /option>
< /select> < br>

< % int i=1;
String choice=request.getParameter("ch");
if(choice!=null)
{
if(!choice.equals("--"))
{
String str=course.addCourse(choice); %>
< p> < %=str%>
< % } }
String rmcourse=request.getParameter("c");
if(rmcourse!=null)
{
course.removeCourse(rmcourse);
}
Vector courseList = new Vector();
courseList = course.getSelectedCourse();
Enumeration enumer = courseList.elements(); %>
< form method="get" name="f2">
< p> < p> < table border=1>
< th> Course Name < /th>
< th> Select Course to remove < /th> < % while (enumer.hasMoreElements())
{
String title = (String) enumer.nextElement();
if (title!=null)
{
%>
< tr> < td> < %=title%> < /td>
< td> < input type=radio name=c value='< %=title%> ' > < /td>
< /tr>
< % }
} %>
< /table>
< input type="hidden" name="stdname" size="25" value=< %=stdname%> >

< input type="submit" value="Submit">
< input type="reset" value="Reset">
< /form>
< /body>
< /html>

  • Right Click on MyCourseWeb -> Build Project

  • Right Click on MyCourseWeb -> Run Project

  • Following page is Welcome Page of Web Application using Stateful Session Bean

  • Enter Name of Student : John -> and Roll No. : 101 -> Click on Submit Button

  • Above page will display Welcome message followed by Name of Student
  • Now you are ready to select or remove any course.
  • Select any Course (Core Java)-> Click on Submit

  • Your Selected Course Will display in your Course Cart

  • Select other Course (J2EE)-> Click on Submit Button

  • Select same (Which already in Course Cart) for e.g. J2EE -> Click on Submit

  • Display message “You have already selected this course”

  • Now click on any radio button to remove the course

  • Your checked course is remove from Course Cart

Conclusion:

In this I used Concept of Stateful Session Bean. You can run this example using network with multiple client, will find that every client will get own selected course. Here details of every client stored in instance variable, and values of instance variable used in various method call like addCourse( ), removeCourse( ), getSelectedCourse( ).

1 comment:

Unknown said...

Really a very useful article.
Due to every steps described using pictures,it is very helpful to everybody.