Search code examples
jakarta-eeservletsejbejb-3.0stateful-session-bean

Stateful Session Bean - Stateloss Issue


I have a servlet code which invokes a stateful session bean code and increment an int value of it. But, when I am invoking the servlet and it's corresponding bean for the next time , the bean losses it's state and again starts from begining of incrementing. Can anybody help me how to solve this issue. My code is below:

public class CounterServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       response.setContentType("text/html;charset=UTF-8");
       PrintWriter out = response.getWriter();

       try {
           Counter counter = new Counter() ;
           HttpSession clientSession = request.getSession(true);
           clientSession.setAttribute("myStatefulBean", counter);

           counter.increment() ;

           // go to a jsp page

       } catch (Exception e) {
           out.close();
       }
   }

}

Solution

  • In your code, you are creating new Counter every time a request comes in and then saving the new Counter into the client's session. As a result, your counter always start incrementing from the beginning.

    You should check if a client has already had a Counter before giving him a new one. It would be something as following:

    HttpSession clientSession = request.getSession();
    Counter counter = (Counter) clientSession.getAttribute("counter");
    
    if (counter == null) {
        counter = new Counter();
        clientSession.setAttribute("counter", counter);
    }
    
    counter.increment();
    

    Besides, in the name of this Topic, you mentioned Stateful session bean. However, the way you inject a new Counter does not look like you are injecting a Stateful bean. It looks like a normal Java object to me.