Download Stateful Session Bean

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
The Stateful Session Bean
• A stateful session bean represents a specific client
and holds related data for this client during the
session. For example, a shopping cart session bean
or a student registration session bean is stateful
because the session must keep track of which items
or courses have been selected so far.
• A session bean class may have a Collection type
data member pertaining to the client during a session
but it does not have any permanent data storage to
support. The operations of a stateful EJB are context
dependent which use and update the state data and
the operations are performed on behalf a client.
• A stateful session bean is not supposed to be shared
by multiple clients but it keeps its data for a client in
many request transactions within a same session.
Life Cycle of a Stateful Session Bean
The Life Cycle of a Stateful
Session Bean (cont.)
• The life cycle of a stateful session bean is more
complicated than a staeless session bean in that it has an
additional inactive pool state. The main flow of the life
cycle is as follows.
• Clients invoke bean’s home create() method in client
application via the stub, EJB container instantiates a
instance, calls the setSessionContext() and ejbCreate()
methods, and move it in the method ready stage.
• The EJB container may instantiate a number of bean
instances when the server starts. While in the method
ready stage, the EJB container may passivate the bean
by calling ejbPassivate() to move it from memory to
secondary storage following a least-recently-used rule.
The Life Cycle of a Stateful
Session Bean (cont.)
• If a client invokes a business method of 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 method ready stage.
• When a client invokes the remove() method, the EJB
container calls the bean's ejbRemove() method.
• All the methods whose name with ejbXXX are invoked by
the EJB container. The ejbCreate() method, for example,
is inside the bean class, lets you perform certain
initiazation operations such as database connection right
after the bean is instantiated.
The Life Cycle of a Stateful
Session Bean (cont.)
• There are three ways for a stateful session bean to
move in the method ready stage. The EJB container
allocates and instantiates the instance when the server
starts or when clients invoke the create() method
causing the EJB container to call the ejbCreate() and
ejbPostCreate() methods , or the EJB container invokes
the ejbActivate() method when it is needed.
• While a bean is in the method ready stage, it's business
methods can be invoked.
• There are two ways to move beans away from the
method ready stage. Clients can invoke the remove()
method, which causes the EJB container to call the
ejbRemove() method. Second, the EJB container can
invoke the ejbPassivate() method.
Your First Stateful Session Bean
• You will see a simple on-line shopping cart stateful
session bean class with its Home interface and Remote
interface.
• This stateful session been has a vector data state which
is a cart holding all the items customer put in during the
shopping session.
• The customer can also remove any items from this cart
and review the cart during that session.
– Home interface (CartHome)
– Remote interface (Cart)
– Session bean class (CartBean)
Your First Stateful Session Bean
(cont.)
• The home interface is like an EJB factory that defines
the create() methods and clients may invoke it to
create a new instance of the bean. For example,
clients call this create() method:
Cart myCart = home.create(“Allen”);
• Every create() method in the home interface has its
corresponding ejbCreate() callback method in the
bean class. The signatures of the ejbCreate()
methods in the CartBean class is as follows.
public void ejbCreate(String name)
throws CreateException
Your First Stateful Session Bean
(cont.)
• The CartHome.java is a Home interface file for this
stateless session bean. This home interface extends
the javax.ejb.EJBHome interface.
package shoppingCart;
import java.rmi.RemoteException;
import javax.ejb.*;
public interface CartHome extends EJBHome {
Cart create(String name) throws RemoteException,
CreateException;}
Your First Stateful Session Bean
(cont.)
• The Cart.java is a Remote interface file which declares
all business methods that the CartBean implements.
This Remote interface extends javax.ejb.EJBObject,
and defines the business methods that a remote client
may invoke.
package shoppingCart;
import java.util.*;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface Cart extends EJBObject {
public void addItem(String item) throws
RemoteException;
public void removeItem(String item)
throws RemoteException;
public Vector getCart()
throws RemoteException;
}
Your First Stateful Session Bean
(cont.)
• The CartBean.java is a stateful session bean class
file which implements all bean interface and overrides
the container callback methods.
package shoppingCart;
import java.util.*;
import javax.ejb.*;
import java.rmi.*;
public class CartBean implements SessionBean {
String name;
Vector cart;
SessionContext sessionContext;
Your First Stateful Session Bean
(cont.)
//ejbCreate() is called back by EJB container after
//clients invoke create() method. Some initialization
//is done here. The main job here is to create a vector
//to hold all shopped items for this cart.
public void ejbCreate(String name)
throws
CreateException {
if (name == null) {
throw new CreateException("creation failed.");
}
else {
this.name = name;
}
cart = new Vector();
}
Your First Stateful Session Bean
(cont.)
//Add a new item to the cart
public void addItem(String item) {
cart.add(item);
}
//Remove an existing item from the cart
public void removeItem(String item) throws
RemoteException {
boolean result = cart.remove(item);
if (result == false) {
throw new RemoteException(“Can’t find it”);
}
}
Your First Stateful Session Bean
(cont.)
//Return this cart
public Vector getCart() {
return cart;
}
public CartBean() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc)
{sessionContext = sc;}
// sessionContext is useful when this session needs to
// use other resources in the session context
}
An Application Client of this
Stateful Session Bean
• The following code shows a simple application of this
stateful session bean.
• A client “Allen” creates his shopping cart, and added
two items, then viewed the cart, and then decided to
remove the first item he added.
• This client application is written in Java command line
application but it is very easy to convert it to a Web
application as shown for the stateless session
example.
An Application Client of this Stateful
Session Bean (cont.)
import java.util.*;
import javax.naming.*;
import javax.rmi.*;
public class Client {
public static void main(String[] args) {
try {
//Locate the bean with a deployed name “myCart”
Context ic = new InitialContext();
CartHome cartHome =
(CartHome)PortableRemoteObject.narrow(
ic.lookup("java:comp/env/ejb/myCart"),CartHome.class);
An Application Client of this
Stateful Session Bean (cont.)
//Create a shopping cart for Allen
Cart myCart = home.create("Allen");
//Add two items
myCart.addItem("Item1");
myCart.addItem("Item2");
//Browse the cart
Vector v = new Vector();
v = myCart.getCart();
Iterator iterator = v.iterator();
An Application Client of this
Stateful Session Bean (cont.)
while (iterator.hasNext()) {
String item = (String) iterator.next();
System.out.println(item);
}
//Remove one item from the cart
myCart.removeItem("Item1");}
catch (Exception ex) {
System.err.println("Exception!");
ex.printStackTrace();
}
}
}
An Application Client of this
Stateful Session Bean (cont.)
• A client locates the home object of this session bean by
the Java Naming and Directory Interface (JNDI). The
InitialContext class is the context for performing JNDI
naming operations. The lookup() method takes the
bean's JNDI name(deployed name) as the argument:
Context initialContext = new InitialContext();
CartHome cartHome = (CartHome)PortableRemoteObject.
narrow(initialContext.lookup(
"java:comp/env/ejb/myCart"),CartHome.class);
• The PortableRemoteObject.narrow() method must be
used on the object returned from the JNDI lookup for a
remote home object. This method converts the RMI-IIOP
compatible remote home stub into a Java object.
An Application Client of this
Stateful Session Bean (cont.)
• For a local clients, the return value of the
InitialContext.lookup() method is not a stub and can
be directly cast to the local home interface.
CartHome cartHome =
(CartHome)initialContext.lookup(
"java:comp/env/ejb/myCart");
• The rest of code is not difficult to follow. The vector
of the Cart holds a conversation state during the
client’s session. It does not have permanent
persistent state stored in the database although it
has a state for the current session.
A Web Client of this
Stateful Session Bean
• Here is another Web client application of this
Stateful session bean.
• A Web client can access this stateful session
bean on-line by any Web browser.
• The following is the catalog.jsp which is a front
page showing the catalog and letting clients
select items from the catalog and put in the
shopping cart.
A Web Client of this
Stateful Session Bean (cont.)
<%@ page language="java" import = "java.util.*" %>
<html>
<body bgcolor="#ffffff">
<center>
<h3>Product Catalog</h3>
<table border="1"><thread><tr>
<th width="120">Product Name</th>
<th width="100">Add to Cart</th>
</tr></thread>
<% String itemName = "";
for ( int i = 1; i < 6; i++ ) {
itemName = "Item" + i;
%>
A Web Client of this Stateful
Session Bean (cont.)
<form name="Catalog" action="Catalog.jsp" method="POST">
<tr>
<td> <center> <%= itemName %></Center></td>
<input type="hidden" name= "itemSelected" value=
"<%= itemName %>"</input>
<td><center><input type="submit"
value="Add"></input><center>
</td>
</tr>
</form>
<%
}
%>
</table>
<p>
<jsp:include page="DisplayCart.jsp" flush="true" />
</center>
</body>
</html>
A Web Client of this Stateful
Session Bean (cont.)
A Web Client of this
Stateful Session Bean (cont.)
• Here is the displayCart.jsp which is responsible in
showing the contents of the shopping cart. It is
included as a part of catalog.jsp.
<%@ page language="java"
import="shoppingCart.*,java.util.*,java.text.*,
javax.naming.*,
javax.rmi.*" %>
A Web Client of this Stateful
Session Bean (cont.)
<%
Cart myCart = (Cart)
session.getAttribute("ShoppingCart");
if (myCart == null) { try {
InitialContext ic = new InitialContext();
Object objRef =
ic.lookup("java:comp/env/ejb/SimpleCart");
CartHome home =
(CartHome)PortableRemoteObject.narrow(objRef,
CartHome.class);
myCart = home.create("customer");
} catch (Exception ex) {
System.out.println("Exception "+
ex.getMessage());
}
session.setAttribute("ShoppingCart", myCart);
} %>
A Web Client of this
Stateful Session Bean (cont.)
<%
if (request.getParameter("itemSelected") != null) {
myCart.addItem(request.getParameter("itemSelected"));
}
%>
<%-- Display the header for the shopping cart table --%>
<%
Vector items = myCart.getCart();
if (items.size() != 0) {
%>
<h3>My Shopping Cart</h3>
<table border=1>
<tr><th width="120">Items in Cart</tr>
A Web Client of this Stateful
Session Bean (cont.)
<%
Iterator i = items.iterator();
while (i.hasNext()) {
String item = (String) i.next();
%>
<tr><td><center><%= item %></center></td></tr>
<%
}
}
%>
</table>
A Web Client of this Stateful
Session Bean (cont.)
• The shopping cart after inserting items1 and 3
A Web Client of this Stateful
Session Bean (cont.)
• We can see that a stateful session bean has a
data state for the current client in the current
session. A stateless session bean does not
keep any state for a particular client during the
conversation.