日期:2014-05-16 浏览次数:20351 次
ShoppingServlet代码如下: package servlet.user; import java.io.IOException; import java.util.ArrayList; 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 util.Validate; import bean.Cart; import bean.CartItem; public class ShoppingServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Validate validate = new Validate(); String pathStr = ""; String method = validate.getUnicode(request.getParameter("method")); String bookId = validate.getUnicode(request.getParameter("bookId")); String bookName = validate.getUnicode(request.getParameter("bookName")); String bookQuantityStr = request.getParameter("bookQuantity"); String bookPriceStr = request.getParameter("bookPrice"); int bookQuantity =0; double bookPrice = 0.0d; if(bookQuantityStr!=null) bookQuantity = Integer.parseInt(bookQuantityStr); if(bookPriceStr!=null) bookPrice= Double.parseDouble(bookPriceStr); HttpSession session = request.getSession(); ArrayList login = (ArrayList) session.getAttribute("login"); if(login == null || login.equals("")){ pathStr="/user/error.jsp"; } else { pathStr = "/user/cart.jsp"; CartItem cartItem = new CartItem(); cartItem.setId(bookId); cartItem.setName(bookName); cartItem.setQuantity(bookQuantity); cartItem.setPrice(bookPrice); Cart cart = (Cart)session.getAttribute("cart"); if(cart==null) cart = new Cart(); //添加书籍到购物车 if("add".equals(method)){ cart.addCartItem(cartItem); } //根据id删除书籍 else if("delete".equals(method)){ cart.removeCartItem(bookId); } //修改指定书籍的数量 else if("update".equals(method)){ int updateBookQuantity = Integer.parseInt(request. getParameter("updateBookQuantity"+bookId)); cart.updateCartItem(bookId, updateBookQuantity); } //清空购物车 else if("removeAll".equals(method)){ cart.clearCart(); } session.setAttribute("cart", cart); } RequestDispatcher rd = request.getRequestDispatcher(pathStr); rd.forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }