Reputation: 3424
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"];
}
}
}
Upvotes: 0
Views: 2226
Reputation: 89189
In Java, you will have to play with HttpServletRequest
or HttpSession
(which is most preferred) since you're storing a ShoppingCart
into 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.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class ShoppingCartUtil {
public static ShoppingCart getShoppingCart(HttpServletRequest request, String sessionName) {
return getShoppingCart(request.getSession(), sessionName);
}
public static ShoppingCart getShoppingCart(HttpSession session, String sessionName) {
return (ShoppingCart)session.getAttribute(sessionName);
}
public static void addShoppingCartToSession(HttpServletRequest request, String sessionName, ShoppingCart cart) {
addShoppingCartToSession(request.getSession(), sessionName, cart);
}
public static void addShoppingCartToSession(HttpSession session, String sessionName, ShoppingCart cart) {
session.removeAttribute(sessionName);
session.setAttribute(sessionName, cart);
}
}
Upvotes: 1