Question

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();
       }
   }

}
Was it helpful?

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.

OTHER TIPS

It looks like in your servlet you are not trying to remember which SFSB the first request was serviced with. So the next time a request comes in, you create a new SFSB, which does not have the state.

Basically what you need to do is (pseudo code)

Session x = httpRequest.getSession
if (!mapOfSfsb.contains(x) {
   Sfsb s = new Sfsb();
   mapOfSfsb.put(x,s);
}

Sfsb s = mapOfSfsb.get(x);

s.invokeMethods();

That is: get the http request and see if a session is attached. If so, check if there is already a SFSB for this session present and use it. Otherwise create a new SFSB and stick it into the session.

You will also need to add some code to clean out old not longer used SFSBs.

This is not an EJB issue. Your are creating a POJO not an EJB. Calling the new function initiate a new objet every time. It is not a Bean injection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top