package control;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import entity.BookBean;
import entity.CartItemBean;
public class AddBookToCart extends HttpServlet {
/**
* Constructor of the object.
*/
public AddBookToCart() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
//获取刚刚放入购物车的book
BookBean books=(BookBean)session.getAttribute("bookToAdd");
//取出购物车 cart
Map cart=(Map)session.getAttribute("cart");
if(cart==null)
{
cart=new HashMap();
//将购物车放入session中
session.setAttribute("cart",cart);
}
//判断此书籍是否在购物车中
CartItemBean cartItem=(CartItemBean)cart.get(books.getIsbn());
//如果书籍在购物车中,则更新数量
if(cartItem!=null)
{
cartItem.setQuantity(cartItem.getQuantity()+1);
//否则,创建一个新条目到Map中 且设置数量为1
}else{
cart.put(books.getIsbn(),new CartItemBean(books,1));
}
request.getRequestDispatcher("viewCart.jsp").forward(request,response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}