You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
test/service/cartService.java

89 lines
2.2 KiB

package com.itbaizhan.service;
import javax.servlet.http.HttpSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import com.itbaizhan.util.Cart;
/**
* 购物车服务类 (cartService)
*
* 该类提供了对购物车的操作方法,包括修改商品数量、删除购物车中的商品以及清空购物车等功能。
* 它通过使用 session 来保存和管理用户的购物车信息。
*/
public class cartService {
/**
* 修改购物车中商品的数量
*
* @param goodsId 商品ID
* @param quantity 新的商品数量
* @return 操作结果的字符串 ("yes" 表示成功)
*/
public String modiNum(String goodsId, int quantity) {
String result = ""; // 初始化操作结果为空
// 获取 WebContext 上下文
WebContext ctx = WebContextFactory.get(); // 通过 DWR (Direct Web Remoting) 获取 WebContext
HttpSession session = ctx.getSession(); // 获取当前会话对象
// 获取购物车对象
Cart cart = (Cart) session.getAttribute("cart");
// 更新购物车中的商品数量
cart.updateCart(goodsId, quantity);
// 更新 session 中的购物车对象
session.setAttribute("cart", cart);
// 设置操作结果为 "yes" 表示成功
result = "yes";
return result;
}
/**
* 从购物车中删除指定商品
*
* @param goodsId 商品ID
* @return 操作结果的字符串 ("yes" 表示成功)
*/
public String delGoodsFromCart(String goodsId) {
// 获取 WebContext 上下文
WebContext ctx = WebContextFactory.get(); // 通过 DWR 获取 WebContext
HttpSession session = ctx.getSession(); // 获取当前会话对象
// 获取购物车对象
Cart cart = (Cart) session.getAttribute("cart");
// 从购物车中删除指定商品
cart.delGoods(goodsId);
// 更新 session 中的购物车对象
session.setAttribute("cart", cart);
return "yes"; // 返回成功标志
}
/**
* 清空购物车中的所有商品
*
* @return 操作结果的字符串 ("yes" 表示成功)
*/
public String clearCart() {
// 获取 WebContext 上下文
WebContext ctx = WebContextFactory.get(); // 通过 DWR 获取 WebContext
HttpSession session = ctx.getSession(); // 获取当前会话对象
// 获取购物车对象
Cart cart = (Cart) session.getAttribute("cart");
// 清空购物车中的所有商品
cart.getItems().clear();
// 更新 session 中的购物车对象
session.setAttribute("cart", cart);
return "yes"; // 返回成功标志
}
}