[英]Sessions in JSP
我想知道以下ASP.net代码的相应Java代码。 我已经创建了一个会话....在这段代码中我也想在我的servlet中使用它。
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;
}
}
使用HttpSession#setAttribute()
和#getAttribute()
。
HttpSession session = request.getSession();
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("cart", cart);
}
// ...
它也可以通过${cart}
在JSP EL中访问。
根据您的评论更新 ,您可以真正将其重构为ShoppingCart
类中的帮助方法:
public static ShoppingCart getInstance(HttpSession session) {
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("cart", cart);
}
return cart;
}
然后按如下方式使用它
ShoppingCart cart = ShoppingCart.getInstance(request.getSession());
// ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.