use*_*636 0 java session shopping-cart jsp servlets
我有一个ShoppingCart类,它包含CartItems(在ArrayList中).我想要的是每当会话存在时(当用户将项目添加到购物车时),它应该请求上一个会话并将其显示在ViewCart jsp页面上.
我现有的代码给了我很多麻烦,所以我想要一个清晰的概念来说明应该如何完成.作为ac #code,我认为我的逻辑在java中是错误的.这是我的c#代码
public class ShoppingCart
{
#region ListCart
public List<CartItem> Items { get; private set; }
#endregion
#region CartSession
public static readonly ShoppingCart Instance;
static ShoppingCart()
{
if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
{
Instance = new ShoppingCart();
Instance.Items = new List<CartItem>();
HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;
}
else
{
Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
}
}}
Run Code Online (Sandbox Code Playgroud)
由于我不是java或jsp的专家,我很难搞清楚这一点.我该怎么办?
只需将其存储为会话的属性,并检查每个请求是否存在.
HttpSession session = request.getSession();
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
cart.add(item);
// ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
661 次 |
| 最近记录: |