package com.accp.shop.servlet;
/**
* 处理购物的功能
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.accp.shop.dao.BookDao;
import com.accp.shop.domain.Book;
import com.accp.shop.impl.BookDaoImpl;
public class ShoppingServlet extends HttpServlet {
//创建购物车
MyCart cart;
BookDao bookDao = new BookDaoImpl();
//通过用户来保存他的购物车
Map<String,MyCart> userMap = new HashMap<String, MyCart>();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String path = "shopping.jsp";
System.out.println("购物的sertvlet被执行了......");
//获得index.jsp页面你选择的复选框
String[] bookId = req.getParameterValues("bookId");
//获得操作的参数
String operate = req.getParameter("operate");
//1、2、3
//获得登录的用户名
String userName =(String)req.getSession().getAttribute("userName");
//通过用户名绑定一个购物车
getUserCart(userName);
if(bookId!=null){
for (int i = 0; i < bookId.length; i++) {
//把字符串的id转为int类型的id.
int id = Integer.parseInt(bookId[i]);
//通过ID来查询指定的图书
Book book = bookDao.getIdBook(id);
//把选中的书,存入起来.(通过map集合进行保存)
cart.addBook(id, book);
}
}
if("del".equals(operate)){
//如果operate值是del,则进行删除
int id = Integer.parseInt(req.getParameter("id"));
//通过id,删除指定的图书
cart.delBook(id);
}else if("all".equals(operate)){
//清空购物车
cart.clearCart();
}else if("update".equals(operate)){
//修改
//获得页面中传递过来的ID
int id = Integer.parseInt(req.getParameter("id"));
//获得页面中传递过来的num
int num = Integer.parseInt(req.getParameter("num"));
cart.updateNumber(id, num);
}
//获得map集合
Map<Integer,Book> bookMap = cart.getMap();
//通过session保存map集合.
req.getSession().setAttribute("bookMap", bookMap);
//通过session保存人对应的购物车的集合.
req.getSession().setAttribute("userMap", userMap);
//获得总价格
double totalPrice = cart.getTotalPrice();
//保存总价格
req.getSession().setAttribute("totalPrice", totalPrice);
//跳转到购物车的页面
resp.sendRedirect(path);
}
//通过用户名绑定一个购物车
public void getUserCart(String userName) {
if(userMap.containsKey(userName)){
cart = userMap.get(userName);
}else{
//为此人分配一个购物
cart = new MyCart();
//把人与购物车绑定到一块,放到userMap集合
userMap.put(userName, cart);
}
}
}