2012-01-03 65 views
1

我有一個servlet代碼,它調用一個有狀態的會話bean代碼並增加它的一個int值。但是,當我調用這個servlet並且它下一次是相應的bean時,這個bean就會失去它的狀態,並且從開始遞增開始。任何人都可以幫助我解決這個問題。我的代碼如下:有狀態會話Bean - Stateloss問題

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

} 
+2

你可以顯示Counter的定義嗎?如果它確實是一個EJB,那麼你不能用新的來創建它。否則,提到這個問題的EJB是沒有意義的。 – 2012-01-03 11:40:16

回答

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對象。

0

它看起來像在你的servlet中,你沒有試圖記住哪個SFSB的第一個請求被服務。因此,下一次請求進入時,您將創建一個新的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。

0

這不是一個EJB問題。你正在創建一個POJO而不是EJB。調用新函數每次都會啓動一個新對象。它不是一個Bean注入。