Wednesday, June 29, 2016

Enterprise Java Bean: Stateless and Stateful Session Bean Example


Stateless Session Bean

Acts like global variable of a program. It does not preserve client state. Stateless bean objects are pooled by the container. And value of object retained the whole application scope until modified by another client. That means each instance of bean will get same reference and same modified value.


Stateful Session Bean:

Acts like local variable. It preserves client state i.e. conversational state of multiple method calls. That means each new instance will get different reference and value.

Now we'll see example of Stateless and Stateful Bean. And a remote client to call them.

1. Create EJB Project

2. Create Remote interface using @Remote annotation.

3. Create Stateless Session Bean using @Stateless annotation and Stateful Session Bean using @Stateful annotation - Both are implmenting same remote interface for simplicity.

4. Create web application client MyEJBWebClient to test the beans.

5. Test Stateless Session Bean where we'll see value is retain in every instance of the bean that means same reference are getting in whole application.

6. Test Stateful Session Bean where we'll see that new reference is getting from each new instance so value would be different. 





 1. Create EJB Project named MyEJB in following way







 2. Create a Remote interface using javax.ejb.Remote annotation.



@Remote
public interface BankRemote {

    boolean withdraw(int amount);

    void deposit(int amount);

    int getBalance();
}




3. Create Stateless and Stateful Session Bean with name using  @Stateless (mappedName="") and @Stateful(mappedName="") annotation and both are implementing BankRemote interface.

// define custom name for stateless session bean
@Stateless(mappedName="stateless123")
public class BankSateless implements BankRemote {

    private int amount = 0;
    @Override
    public boolean withdraw(int amount) {
        if(amount<=this.amount)
        {
            this.amount-=amount;
            return true;
        }
        else
        {
            return false;
        }
    }

    @Override
    public void deposit(int amount) {
        this.amount+=amount;
    }

    @Override
    public int getBalance() {
        return amount;
    }     
}


// define custom name for stateful session bean
@Stateful(mappedName="sateful123")
public class Bank implements BankRemote{

    private int amount = 0;
    @Override
    public boolean withdraw(int amount) {
        if(amount<=this.amount)
        {
            this.amount-=amount;
            return true;
        }
        else
        {
            return false;
        }
    }

    @Override
    public void deposit(int amount) {
        this.amount+=amount;
    }

    @Override
    public int getBalance() {
        return amount;
    }
   
}



4. Clean and build MyEJB project. Now create a simple web application named MyEJBWebClient and add MyEJB jar.




-- Go to properties of MyEJBWebClient and add MyEJB.jar.



5. Now we will create a servlet which will take parameter amount and call BankRemote interface by JNDI lookup stateless123. And create index.jsp to call servlet.


<html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <form action="./DepositController">
            Enter Amount: <input name="amount" type="text"/> <br/>
            <input type="submit" value="Deposit"/>
            <input type="hidden" name="type" value="deposit"/>
        </form>
        Balance: ${balance}
    </body>
</html>





@WebServlet("/DepositController")
public class BankAction extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            InitialContext ctx = new InitialContext();
            BankRemote b = (BankRemote) ctx.lookup("stateless123");
           
            int amount =  Integer.valueOf(req.getParameter("amount")) ;
           
            b.deposit(amount);
           
            req.getSession().setAttribute("balance", b.getBalance());
           
        } catch (NamingException ex) {
            Logger.getLogger(BankAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        req.getRequestDispatcher("/index.jsp").forward(req, resp);
       
    }
   
}

Deploy and run the MyEJBWebClient project. Here we'll see that balance is increasing after deposit amount. The balance is same in every session.
6.  Now use stateful session bean in servlet

@WebServlet("/DepositController")
public class BankAction extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            InitialContext ctx = new InitialContext();
            BankRemote b = (BankRemote) ctx.lookup("stateful123");
           
            int amount =  Integer.valueOf(req.getParameter("amount")) ;
           
            b.deposit(amount);
           
            req.getSession().setAttribute("balance", b.getBalance());
           
        } catch (NamingException ex) {
            Logger.getLogger(BankAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        req.getRequestDispatcher("/index.jsp").forward(req, resp);
       
    }
   
}
 
Deploy and run the MyEJBWebClient project. Here we'll see that balance is not increasing. It is same as deposit amount for each session i.e. when user press deposit button.






No comments:

Post a Comment