1

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

}
yatskevich
  • 2,085
  • 16
  • 25
alessandro
  • 1,681
  • 10
  • 33
  • 54
  • 2
    Can you show the definition of Counter? If it's really an EJB, you can't create it with new. Otherwise, mentioning EJB for this question makes no sense. – Arjan Tijms Jan 03 '12 at 11:40

3 Answers3

4

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.

Mr.J4mes
  • 9,168
  • 9
  • 48
  • 90
0

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.

Heiko Rupp
  • 30,426
  • 13
  • 82
  • 119
0

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.

Forty
  • 420
  • 1
  • 5
  • 10