1

我有一个 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();
       }
   }

}
4

3 回答 3

4

在您的代码中,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。在我看来,它就像一个普通的 Java 对象。

于 2012-01-03T08:47:20.707 回答
0

看起来在您的 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。

于 2012-01-03T07:58:02.883 回答
0

这不是 EJB 问题。您正在创建 POJO 而不是 EJB。每次调用新函数都会启动一个新对象。它不是 Bean 注入。

于 2012-01-05T21:17:16.317 回答