package cn.edu.cg.controller; import java.io.IOException; 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 cn.edu.cg.dao.BookDaoImpl; import cn.edu.cg.domain.Book; import cn.edu.cg.domain.Cart; @WebServlet("/BuyServlet") public class BuyServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); String id=request.getParameter("id"); BookDaoImpl dao=new BookDaoImpl(); Book book = dao.find(id); Cart cart = (Cart) request.getSession().getAttribute("cart"); if(cart==null){ cart = new Cart(); request.getSession().setAttribute("cart", cart); } cart.add(book); request.getRequestDispatcher("/listcart.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package cn.edu.cg.controller; import java.io.IOException; 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 cn.edu.cg.domain.Cart; import cn.edu.cg.domain.CartItem; @WebServlet("/ChangeQuantityServlet") public class ChangeQuantityServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); String id=request.getParameter("id"); String quantity=request.getParameter("quantity"); Cart cart=(Cart) request.getSession().getAttribute("cart"); CartItem item = cart.getMap().get(id); item.setQuantity(Double.parseDouble(quantity));//int 转化时不能带小数点 request.getRequestDispatcher("/listcart.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package cn.edu.cg.controller; import java.io.IOException; 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 cn.edu.cg.domain.Cart; @WebServlet("/ClearCartServlet") public class ClearCartServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); Cart cart= (Cart) request.getSession().getAttribute("cart"); cart.getMap().clear(); request.getRequestDispatcher("/listcart.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package cn.edu.cg.controller; import java.io.IOException; 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 cn.edu.cg.domain.Cart; @WebServlet("/DeleteItemServlet") public class DeleteItemServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); String id=request.getParameter("id"); Cart cart = (Cart) request.getSession().getAttribute("cart"); cart.getMap().remove(id); System.out.println("len:"+cart.getMap().size()); request.getRequestDispatcher("/listcart.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package cn.edu.cg.controller; import java.io.IOException; import java.util.List; 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 cn.edu.cg.dao.BookDaoImpl; import cn.edu.cg.domain.Book; @WebServlet("/index.do") public class ListBookServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); BookDaoImpl bookDao=new BookDaoImpl(); Listbooks = bookDao.getAll(); request.setAttribute("books", books); request.getRequestDispatcher("/index.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package cn.edu.cg.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import cn.edu.cg.domain.Book; import cn.edu.cg.utils.JdbcUtils; public class BookDaoImpl { public Book find(String id) { Book book=null; Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; try { conn=JdbcUtils.getConn(); String FINDBYID = "SELECT * FROM book WHERE id=?"; ps=conn.prepareStatement(FINDBYID); ps.setString(1, id); rs = ps.executeQuery(); book=new Book(); if(rs.next()) { book.setId(rs.getString("id")); book.setName(rs.getString("name")); book.setPrice(rs.getDouble("price")); } return book; } catch (Exception e) { throw new RuntimeException(e); }finally { JdbcUtils.closeAll(ps, rs, conn); } } public ListgetAll() { Book book=null; Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn=JdbcUtils.getConn(); String sql="select * from book"; pstmt=conn.prepareStatement(sql); rs = pstmt.executeQuery(); List books=new ArrayList<>(); while(rs.next()) { book=new Book(); book.setId(rs.getString("id")); book.setName(rs.getString("name")); book.setPrice(rs.getDouble("price")); books.add(book); book=null; } return books; } catch (Exception e) { throw new RuntimeException(e); }finally { JdbcUtils.closeAll(pstmt, rs, conn); } } }
package cn.edu.cg.domain; public class Book { private String id; private String name; private double price; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
package cn.edu.cg.domain; import java.util.LinkedHashMap; import java.util.Map; public class Cart { private Mapmap = new LinkedHashMap<>(); private double price; public void add(Book book) { CartItem item=map.get(book.getId()); if(item==null) { item=new CartItem(); item.setBook(book); item.setQuantity(1); map.put(book.getId(), item); }else { item.setQuantity(item.getQuantity()+1); } } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } public double getPrice() { double totalPrice = 0; for (Map.Entry entry : map.entrySet()) { totalPrice += entry.getValue().getPrice(); } this.price = totalPrice; return price; } }
package cn.edu.cg.domain; public class CartItem { private Book book; private double quantity; private double price; public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public double getQuantity() { return quantity; } public void setQuantity(double quantity) { this.quantity = quantity; this.price=this.quantity*book.getPrice(); } public double getPrice() { return price; } @Override public String toString() { return "CartItem [book=" + book + ", quantity=" + quantity + ", price=" + price + "]"; } }
package cn.edu.cg.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JdbcUtils { public static Connection getConn() { Connection conn=null; try { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/cart?useUnicode=true&characterEncoding=UTF-8"; conn = DriverManager.getConnection(url, "root", "root"); return conn; } catch (Exception e) { throw new ExceptionInInitializerError("连接错误"); } } public static void closeAll(PreparedStatement pstmt,ResultSet rs,Connection conn) { if(pstmt!=null) { try { pstmt.close(); } catch (Exception e) { e.printStackTrace(); } pstmt=null; } if(rs!=null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } rs=null; } if(conn!=null) { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } conn=null; } } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>选书title> head> <body> <table frame="border" border="2px" cellpadding="0" cellspacing="0" width="90%" align="center"> <caption><h2>图书信息h2>caption> <tr align="center"> <td>书名td> <td>价格td> <td>操作td> tr> <c:forEach var="book" items="${books}" > <tr align="center"> <td>${book.name}td> <td>${book.price}td> <td> <a href="${pageContext.request.contextPath}/BuyServlet?id=${book.id}" target="_blank">购买a> td> tr> c:forEach> table> body> html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>购物车列表title> <script type="text/javascript" > function deleteitem(id){ var b = window.confirm("您确认删除吗??"); if(b){ window.location.href="${pageContext.request.contextPath }/DeleteItemServlet?id="+id; } } function clearcart(){ var b = window.confirm("您确认清空吗??"); if(b){ window.location.href="${pageContext.request.contextPath}/ClearCartServlet"; } } function changeQuantity(input,id,oldvalue){ var quantity = input.value; if(quantity<0 || quantity!=parseInt(quantity)){ alert("请输入正整数!!"); input.value = oldvalue; return; } var b = window.confirm("您确认把书的数量修改为:" + quantity); if(b){ window.location.href="${pageContext.request.contextPath}/ChangeQuantityServlet?id=" + id + "&quantity=" + quantity; } } script> head> <body style="text-align: center"> <h1>购物车列表h1><a href="${pageContext.request.contextPath}/index.do">继续购买a> <c:if test="${empty(cart.map)}"> 您没有购买任何商品!!! c:if> <c:if test="${!empty(cart.map)}"> <table width="70%" border="1" align="center"> <tr> <td>书名td> <td>单价td> <td>数量 td> <td>小计td> <td>操作td> tr> <c:forEach var="entry" items="${cart.map}"> <tr> <td>${entry.value.book.name}td> <td>${entry.value.book.price}td> <td> <input type="text" name="quantity" value="${entry.value.quantity }" style="width:35px" onchange="changeQuantity(this,${entry.key},${entry.value.quantity})"> td> <td>${entry.value.price }td> <td> <a href="javascript:void(0)" onclick="deleteitem(${entry.key})">删除a> td> tr> c:forEach> <tr> <td colspan="3">总价td> <td colspan="2">${cart.price}元td> tr> table> <a href="javascript:void(0)" onclick="clearcart()">清空购物车a> c:if> body> html>