user478636
user478636

Reputation: 3424

Sessions in JSP

I would like to know the corressponding Java code for the following ASP.net code. I have created a session....in this code I would like to use it in my servlets also.

        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;
        }
    }

Upvotes: 0

Views: 433

Answers (1)

BalusC
BalusC

Reputation: 1108587

Use HttpSession#setAttribute() and #getAttribute().

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

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

// ...

It's accessible in JSP EL by ${cart} as well.


Update as per your comment, you can truly refactor it into a helper method in the ShoppingCart class:

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

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

    return cart;
}

and then use it as follows

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

Upvotes: 2

Related Questions