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();
}
}
}
In your code, you are creating new
Counterevery time a request comes in and then saving the newCounterinto 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
Counterbefore giving him a new one. It would be something as following:Besides, in the name of this Topic, you mentioned
Stateful session bean. However, the way you inject a newCounterdoes not look like you are injecting a Stateful bean. It looks like a normal Java object to me.