2011-04-23 66 views
0

我想知道下面的ASP.net代碼的corressponding Java代碼。我已經創建了一個會話....在這個代碼中,我想在我的servlets中也使用它。JSP中的會話

 public static ShoppingCart Current 
    { 
     get 
     { 
      var cart = HttpContext.Current.Session["Cart"] as ShoppingCart; 
      if (null == cart) 
      { 
       cart = new ShoppingCart(); 
       cart.Items = new List<CartItem>(); 

       if (mySession.Current._isCustomer==true) 
       cart.Items = ShoppingCart.loadCart(mySession.Current._loginId); 

       HttpContext.Current.Session["Cart"] = cart; 
      } 
      return cart; 
     } 
    } 

回答

2

使用HttpSession#setAttribute()#getAttribute()

HttpSession session = request.getSession(); 
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); 

if (cart == null) { 
    cart = new ShoppingCart(); 
    session.setAttribute("cart", cart); 
} 

// ... 

它也可以在JSP EL中通過${cart}訪問。


更新按你的意見,你才能真正重構它變成一個輔助方法在ShoppingCart類:

public static ShoppingCart getInstance(HttpSession session) { 
    ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); 

    if (cart == null) { 
     cart = new ShoppingCart(); 
     session.setAttribute("cart", cart); 
    } 

    return cart; 
} 

然後如下

ShoppingCart cart = ShoppingCart.getInstance(request.getSession()); 
// ... 
+0

因爲我用它會有很多頁面...我想要在任何頁面上創建會話...所以我必須將此代碼複製到每個servlet? – user478636 2011-04-23 12:00:18

+0

查看答案更新。但是,您也可以改爲使用MVC框架。 – BalusC 2011-04-23 12:04:02