Sessions in Java

徘徊边缘 提交于 2021-02-05 09:32:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!