需要gson-2.2.4.jar
BookServlet.java
package com.aff.bookstore.servlet; import java.io.IOException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.aff.bookstore.domain.Book; import com.aff.bookstore.domain.ShoppingCart; import com.aff.bookstore.service.BookService; import com.aff.bookstore.web.BookStoreWebUtils; import com.aff.bookstore.web.CriteriaBook; import com.aff.bookstore.web.Page; import com.google.gson.Gson; @WebServlet("/bookServlet") public class BookServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } private BookService bookService = new BookService(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String methodName = request.getParameter("method"); try { Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); method.setAccessible(true); method.invoke(this, request, response); } catch (Exception e) { e.printStackTrace(); } } protected void updateItemQuantity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 4.在updateItemQuantity 方法中,获取quantity,id,在获取购物车对象,调用service 的方法 做修改 String idStr = request.getParameter("id"); String quantityStr = request.getParameter("quantity"); ShoppingCart sc = BookStoreWebUtils.getShopingCart(request); int id = -1; int quantity = -1; try { id = Integer.parseInt(idStr); quantity = Integer.parseInt(quantityStr); } catch (Exception e) { } if (id > 0 && quantity > 0) { bookService.updateItemQuantity(sc, id, quantity); } // 5.传回JSON 数据:bookNumber:xx, totalMoney Map<String, Integer> result = new HashMap<String, Integer>(); result.put("bookNumber", sc.getBookNumber()); result.put("totalMoney", (int) sc.getTotalMoney()); Gson gson = new Gson(); String jsonStr = gson.toJson(result); response.setContentType("text/javascript"); response.getWriter().print(jsonStr); } protected void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ShoppingCart sc = BookStoreWebUtils.getShopingCart(request); bookService.clearShoppingCart(sc); request.getRequestDispatcher("/WEB-INF/pages/empty.jsp").forward(request, response); } // 删除商品 protected void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String idStr = request.getParameter("id"); int id = -1; try { id = Integer.parseInt(idStr); } catch (Exception e) { } ShoppingCart sc = BookStoreWebUtils.getShopingCart(request); bookService.removeItemFromShoppingCart(sc, id); if (sc.isEmpty()) { request.getRequestDispatcher("/WEB-INF/pages/empty.jsp").forward(request, response); } // 删除完再转发为回来 request.getRequestDispatcher("/WEB-INF/pages/cart.jsp").forward(request, response); } protected void toCartPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/pages/cart.jsp").forward(request, response); } protected void addToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.获取商品的id String idStr = request.getParameter("id"); int id = -1; boolean flag = false; try { id = Integer.parseInt(idStr); } catch (Exception e) { } if (id > 0) { // 2.获取购物差对象 ShoppingCart sc = BookStoreWebUtils.getShopingCart(request); // 3.调用 BookService 的addToCart() 方法 把商品放到购物车中 flag = bookService.addToCart(id, sc); } if (flag) { // 4.直接调用 getBooks()方法 getBooks(request, response); return; } response.sendRedirect(request.getContextPath() + "/errror-1.jsp"); } protected void getBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String idStr = request.getParameter("id"); int id = -1; Book book = null; try { id = Integer.parseInt(idStr); } catch (NumberFormatException e) { } if (id > 0) { book = bookService.getBook(id); if (book == null) { response.sendRedirect(request.getContextPath() + "/errror-1.jsp"); return; } } request.setAttribute("book", book); request.getRequestDispatcher("/WEB-INF/pages/book.jsp").forward(request, response); } protected void getBooks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pageNoStr = request.getParameter("pageNo"); String minPriceStr = request.getParameter("minPrice"); String maxPriceStr = request.getParameter("maxPrice"); int pageNo = 1; int minPrice = 0; int maxPrice = Integer.MAX_VALUE; try { pageNo = Integer.parseInt(pageNoStr); } catch (Exception e) { } try { minPrice = Integer.parseInt(minPriceStr); } catch (Exception e) { } try { maxPrice = Integer.parseInt(maxPriceStr); } catch (Exception e) { } CriteriaBook criteriaBook = new CriteriaBook(minPrice, maxPrice, pageNo); Page<Book> page = bookService.getPage(criteriaBook); request.setAttribute("bookpage", page); request.getRequestDispatcher("/WEB-INF/pages/books.jsp").forward(request, response); } }
cart.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="script/jquery-1.12.3.js"></script> <%@include file="/commons/queryCondition.jsp" %> <script type="text/javascript"> $(function(){ $(".delete").click(function(){ var $tr = $(this).parent().parent(); var title =$.trim($tr.find("td:first").text()); var flag = confirm("确定要删除"+title+"的信息吗"); if (flag) { return true; } return false; }); //ajax 修改单个商品的数量 // 1.获取页面中的所有的text,并为其添加 onchange 响应函数,弹出确认对话框 $(":text").change(function(){ var quantityVal = $.trim(this.value); var flag = false; var reg = /^d+$/g; var quantity = -1; if (reg.test(quantityVal)) { quantity = parseInt(quantityVal); if (quantity>=0) { flag = true; } } if (!flag ) { alert("输入数量不合法") $(this).val($(this).attr("class")); return; } var $tr = $(this).parent().parent(); var title =$.trim($tr.find("td:first").text()); if (quantity ==0) { var flag2 = confirm("确定要删除"+title+"吗"); if (flag2) { //找到这个删除的a超链接 //<td><a href="bookServlet?method=remove&pageNo=${param.pageNo }&id=${item.book.id}" class="delete">删除</a></td> var $a = $tr.find("td:last").find("a"); //保证查询的条件不丢 //执行a 节点的 onclick 响应函数 /* var serializeVal = $(":hidden").serialize(); href = href+"&"+serializeVal; window.location.href = href; */ $a[0].onclick(); return; } } var flag = confirm("确定要修改"+title+"的数量吗"); if (!flag) $(this).val($(this).attr("class")); return; // 2.请求地址为: bookServlet var url = "bookServlet"; // 3.请求参数为method:updateItemQuantity, id:name属性值,quantity:val,time:new Date() var idVal = $.trim(this.name); var args = {"method":"updateItemQuantity","id":idVal,"quantity":quantityVal,"time":new Date()} // 4.在updateItemQuantity 方法中,获取quantity,id,再获取购物车对象,调用service 的方法 做修改 // 5.传回JSON 数据:bookNumber:xx, totalMoney // 6.更新当前页面的 bookNumber 和totalMoney $.post(url,args,function(data){ var bookNumber = data.bookNumber; var totalMoney = data.totalMoney /* alert(bookNumber); alert(totalMoney); */ $("#bookNumber").text("您的购物差中共有"+ bookNumber+"本书"); $("#totalMoney").text("总金额:¥"+totalMoney); },"JSON"); }); }); </script> </head> <body> <center> <br><br> <div id="bookNumber">您的购物差中共有 ${sessionScope.ShoppingCart.bookNumber} 本书</div> <table cellpadding="10"> <tr> <td>Title</td> <td>Quantity</td> <td>Price</td> <td> </td> </tr> <c:forEach items="${sessionScope.ShoppingCart.items }" var="item"> <tr> <td>${item.book.title }</td> <td> <input class="${item.quantity }" type="text" size="1" name="${item.book.id }" value="${item.quantity }"/> </td> <td>${item.book.price }</td> <td><a href="bookServlet?method=remove&pageNo=${param.pageNo }&id=${item.book.id}" class="delete">删除</a></td> </tr> </c:forEach> <tr> <td colspan="4" id="totalMoney"> 总金额:¥${sessionScope.ShoppingCart.totalMoney}</td> </tr> <tr> <td colspan="4"> <a href="bookServlet?method=getBooks&pageNo=${param.pageNo }">继续购物</a> <a href="bookServlet?method=clear" >清空购物车</a> <a href="">结账</a> </td> </tr> </table> </center> <br><br> </body> </html>
queryCondition.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <script type="text/javascript"> $(function(){ $("a").each(function(){ this.onclick = function(){ var serializeVal = $(":hidden").serialize(); var href = this.href+"&"+serializeVal; window.location.href = href; return false; }; }); }); </script> <input type="hidden" name="minPrice" value="${param.minPrice}"/> <input type="hidden" name="maxPrice" value="${param.maxPrice}"/>
运行效果如下