Example 2: Developing of Stateful Session Bean
The purpose
To develop a counter, i.e. the component capable of holding a numeric
value, incrementing it and providing the current value.
Decision of the bean type
Since the value of the counter has to be maintained separately for each instance of
the counter bean, the bean was decided to be stateful.
Development steps
- Remote Interface:
// File Counter.java
public interface Counter extends javax.ejb.EJBObject {
void increment() throws java.rmi.RemoteException;
int value() throws java.rmi.RemoteException;
}
- Home Interface:
// File CounterHome.java
public interface CounterHome extends javax.ejb.EJBHome {
Counter create(int initialValue)
throws java.rmi.RemoteException, javax.ejb.CreateException;
}
Note the custom create() method with the numeric argument.
- The Bean Class:
// File CounterBean.java
public class CounterBean implements javax.ejb.SessionBean {
private javax.ejb.SessionContext _context;
private int _value;
public void setSessionContext(javax.ejb.SessionContext sessionContext)
{ _context = sessionContext; }
public void ejbCreate(int initialValue) throws java.rmi.RemoteException
{ _value=initialValue; }
public void increment() throws java.rmi.RemoteException
{ _value++; }
public int value() throws java.rmi.RemoteException
{ return _value; }
// ...
// empty implementations of ejbRemove(), ejbActivate() and ejbPassivate()
}
- The Client:
// File CounerClient.java
public class CounterClient {
public static void main(String[] args) throws Exception {
// get a JNDI context using the Naming service
javax.naming.Context context = new javax.naming.InitialContext();
Object ref = context.lookup("myCounterBean");
CounterHome home =
(CounterHome) javax.rmi.PortableRemoteObject.narrow(ref, CounterHome.class);
Counter c1 = home.create(0);
Counter c2 = home.create(10);
for (int i=0; i<10; i++) {
c1.increment(); c2.increment();
}
System.out.println("c1="+c1.value()+", c2="+c2.value());
c1.remove();
c2.remove();
}
}
- The deployment descriptor looks like in the previous example,
only the < session-type > tag specifies the bean type as Stateful.
- The process of the compilation, deployment and running of the bean in the container
is the same as in the previous example
Hint: Try to redefine the Counter bean type as stateless and run it !
|