In ASP.net, I have the following code. I’m making a website in JSP and using Java classes. Basically I want to incorporate the same functionality of this constructor.
What is Java code for the following 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"];
}
}
}
In Java, you will have to play with
HttpServletRequestorHttpSession(which is most preferred) since you’re storing aShoppingCartinto a session.I would not create a ShoppingCart class to store instance of it in a Session, since ShoppingCart can exists outside of Web context. A Simple way to do what you requested is to create a utility class to store / retrieve a shopping cart in/from the session.