我有一个servlet代码,它调用有状态会话bean代码并增加它的int值。但是,当我下一次调用servlet及其对应的bean时,bean会丢失它的状态,并再次从增量开始。有人能帮我解决这个问题吗?我的代码如下:
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();
}
}
}
在您的代码中,您在每次请求进入时创建新的Counter
,然后将新的Counter
保存到客户端的会话中。因此,计数器总是从头开始递增。
你应该检查客户是否已经有一个Counter
之前给他一个新的。它可能是如下内容:
HttpSession clientSession = request.getSession();
Counter counter = (Counter) clientSession.getAttribute("counter");
if (counter == null) {
counter = new Counter();
clientSession.setAttribute("counter", counter);
}
counter.increment();
此外,在这个主题中,你提到了Stateful session bean
。然而,注入一个新的Counter
的方式看起来并不像注入一个有状态bean。
看起来在您的servlet中,您并没有尝试记住第一个请求使用的是哪个SFSB。因此,下一次请求进来时,您将创建一个新的SFSB,它没有状态。
基本上你需要做的是(伪代码)Session x = httpRequest.getSession
if (!mapOfSfsb.contains(x) {
Sfsb s = new Sfsb();
mapOfSfsb.put(x,s);
}
Sfsb s = mapOfSfsb.get(x);
s.invokeMethods();
即:获取http请求并查看是否附加了会话。如果是,检查是否已经有这个会话的SFSB,并使用它。否则,创建一个新的SFSB并将其粘贴到会话中。
您还需要添加一些代码来清除旧的不再使用的sfsb。
这不是EJB问题。您正在创建POJO,而不是EJB。每次调用new函数都会初始化一个新对象。