问题
I have a ShoppingCart class, that contains CartItems (in an ArrayList). What I want is that whenever a session exists (when user has added items to a cart), it should request for the previous session and display it on the ViewCart jsp page.
the existing code i have is giving me a lot of trouble, so i want a clear concept of how it should be done. being a c# coder, i think my logic is wrong in java. this was my c# code
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"];
}
}}
As im no expert in java or jsp, I'm having trouble figuring this out. What should i do?
回答1:
Just store it as an attribute of the session and check on every request if it is there.
HttpSession session = request.getSession();
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
cart.add(item);
// ...
You normally do this in a Servlet class. JSP should be used for presentation only.
来源:https://stackoverflow.com/questions/5443036/sessions-in-java