Sessions in Java

后端 未结 1 603
醉话见心
醉话见心 2021-01-28 21:16

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 fo

相关标签:
1条回答
  • 2021-01-28 21:33

    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.

    0 讨论(0)
提交回复
热议问题