package y2javaee.sg.ch03;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.RequestDispatcher;
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 com.sun.org.apache.bcel.internal.generic.NEW;
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 {
this.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(false);
//如果session不存在,则转向index.jsp
if(session==null){
response.sendRedirect("index.jsp");
}else{
String selectNum=request.getParameter("selectNum");
Map cartMap=(Map)session.getAttribute("cartMap");
if(cartMap==null){
cartMap=new HashMap();
}
//取出选择的书籍
BookBean bookBean=(BookBean)session.getAttribute("bookbeanToAdd");
//根据当前书籍的编号-键, 取出值-购物车
CartItemBean cartItemBean=(CartItemBean)cartMap.get(bookBean.getISBNString());
if(cartItemBean==null){
cartItemBean=new CartItemBean(bookBean,Integer.parseInt(selectNum));
}else {
//根据购物车对象取出书籍的数量
int num=cartItemBean.getQuantity()+Integer.parseInt(selectNum);
cartItemBean.setQuantity(num);
}
//放入Map中
cartMap.put(bookBean.getISBNString(), cartItemBean);
session.setAttribute("cartMap", cartMap);
response.sendRedirect("viewCart.jsp");
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
评论0
最新资源