在构建基于MVC架构的Web数据库应用时,设计一个购物车功能是常见的需求。首先,我们需要定义一个购物车项的实体类。例如:
public class CartItemBean {
private FoodBean food; // 餐品
private int quantity; // 餐品数量
public CartItemBean(FoodBean foodToAdd, int number) {
food = foodToAdd;
quantity = number;
}
public FoodBean getFood() {
return food;
}
public void setFood(FoodBean food) {
this.food = food;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
接下来,我们需要实现一个Servlet来处理将餐品添加到购物车的操作。以下是一个示例:
public class AddFoodToCart extends HttpServlet {
/**
* 购物车操作 Servlet 实现思路
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=GBK");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false); // 获得 session
// 定义转发器
RequestDispatcher dispatcher;
// 从 session 中取出购物车放入 Map 对象 cart 中
Map cart = (Map) session.getAttribute("cart");
// 从 session 中取出当前要添加到购物车中的餐品,放入 FoodBean 对象 food1 中
FoodBean food1 = (FoodBean) session.getAttribute("foodToAdd");
if(cart == null) {
// 如果购物车不存在,则创建购物车
cart = new HashMap();
session.setAttribute("cart", cart); // 将购物车放入 session 中
}
// 判断购物车是否在购物车中
CartItemBean cartItem = (CartItemBean) cart.get(food1.getFoodID());
if(cartItem != null) {
// 如果餐品在购物车中,则更新其数量
cartItem.setQuantity(cartItem.getQuantity()+1);
} else {
// 否则,创建一个条目到 Map 中
cart.put(food1.getFoodID(), new CartItemBean(food1,1));
// 转向 viewCart.jsp 显示购物车
dispatcher = request.getRequestDispatcher("/ch05/shopCart.jsp");
dispatcher.forward(request, response);
}
if(session == null) {
dispatcher = request.getRequestDispatcher("/ch05/show.jsp");
dispatcher.forward(request, response);
}
out.flush();
out.close();
}
/**
* The doPost method of the servlet.
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
这段代码实现了将餐品添加到购物车的功能,并处理了购物车中已存在相同餐品的情况。通过这种方式,我们可以逐步构建一个完整的购物车系统。