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;
}
}
建个Serblet
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);
}
}