一. 实体类设计
图书实体类
public class Book { private String id;
private String name;
private String author;
private double price;
private String description; // 省略getter setter
}
购物项实体类
public class CartItem { private Book book;
private int quantity;
private double price; /**
* 重构getPrice方法
* @return 购物项总价格
*/
public double getPrice() {
return book.getPrice() * this.quantity;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setPrice(double price) {
this.price = price;
}
}
购物车实体类
public class Cart { private Map<String, CartItem> map = new LinkedHashMap();
private double price; /**
* 向购物车中添加图书
* @param book
*/
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);
}
}
/**
* 重构getPrice方法
* @return
*/
public double getPrice() { // 购物车总价格
double totalprice = 0;
// 迭代购物车中所有购物项, 相加获取购物车总价
for(Map.Entry<String, CartItem> me : map.entrySet()) {
CartItem item = me.getValue();
totalprice += item.getPrice();
}
return totalprice;
}
public Map<String, CartItem> getMap() {
return map;
}
public void setMap(Map<String, CartItem> map) {
this.map = map;
}
public void setPrice(double price) {
this.price = price;
}
}
二. 业务层设计
操作购物车实际上就是操作cart对象中的map集合
购物车四个主要功能:
1. 添加商品到购物车
2. 删除购物车商品
3. 清空购物车
4. 修改购物车中购物项数量
public class CartService { BookDao bdao = new BookDao(); /**
* 将图书添加到购物车中
* @param bookid
* @param cart
*/
public void buybook(String bookid, Cart cart) {
// 根据bookid获取图书对象
Book book = bdao.find(bookid);
cart.add(book);
} /**
* 删除购物车中指定bookid的图书
* @param bookid
* @param cart
* @throws CartNotFoundException
*/
public void deleteBook(String bookid, Cart cart) throws CartNotFoundException { //如果用户直接访问DeleteServlet,那么当运行到这里时,因为cart对象为空,
//程序会抛出空指针异常。所以这里应该判断购物车是否为空。
if(cart == null) {
throw new CartNotFoundException("查找不到购物车!!!");
} //String,CartItem
Map map = cart.getMap();
//删除key为bookid的购物项
map.remove(bookid);
} /**
* 清空购物车中所有购物项
* @param cart
* @throws CartNotFoundException
*/
public void clearcart(Cart cart) throws CartNotFoundException { if(cart == null) {
throw new CartNotFoundException("查找不到购物车!!!");
} cart.getMap().clear();
} /**
* 更新购物项数量
* @param cart
* @param bookid
* @param quantity
* @throws CartNotFoundException
*/
public void updateCart(Cart cart, String bookid, int quantity) throws CartNotFoundException { if(cart == null) {
throw new CartNotFoundException("查找不到购物车!!!");
} CartItem item = cart.getMap().get(bookid);
item.setQuantity(quantity);
}
}
注意: 获取到web层传递过来的cart对象时, 记得检查NPE
三. web层设计
1. 添加商品到购物车
public class CartAddServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String bookid = request.getParameter("bookid");
// 从session中获取购物车
Cart cart = (Cart) request.getSession().getAttribute("cart");
if (cart == null) {
//用户第一次添加商品时
cart = new Cart();
request.getSession().setAttribute("cart", cart);
}
CartService cartService = new CartService();
cartService.buybook(bookid, cart);
request.getRequestDispatcher("/listcart.jsp").forward(request, response);
return;
} catch (Exception e) {
request.setAttribute("message", "操作失败!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
}
}
2. 删除购物车商品
public class CartDeleteServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String bookid = request.getParameter("bookid");
Cart cart = (Cart) request.getSession().getAttribute("cart");
// 获取业务层, 删除目标购物项
CartService cartService = new CartService();
cartService.deleteBook(bookid, cart);
// 刷新页面
request.getRequestDispatcher("/listcart.jsp").forward(request, response);
} catch (CartNotFoundException e) {
request.setAttribute("message", "操作出错!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
}
3. 清空购物车
public class ClearCartServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Cart cart = (Cart) request.getSession().getAttribute("cart");
CartService cartService = new CartService();
cartService.clearcart(cart);
request.getRequestDispatcher("/listcart.jsp").forward(request, response);
} catch (CartNotFoundException e) {
request.setAttribute("message", "操作出错!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
}
4. 修改购物车中购物项数量
public class UpdateCartServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//获取操作的图书对象
String bookid = request.getParameter("bookid");
//获取改变的数量
int quantity = Integer.parseInt(request.getParameter("quantity"));
//获取购物车
Cart cart = (Cart) request.getSession().getAttribute("cart");
CartService cartService = new CartService();
cartService.updateCart(cart, bookid, quantity);
request.getRequestDispatcher("/listcart.jsp").forward(request, response);
} catch (Exception e) {
request.setAttribute("message", "操作出错!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
}
5. 获取所有商品
public class ListBookServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
BookService bookService = new BookService();
Map map = bookService.getAllBook();
request.setAttribute("map", map);
request.getRequestDispatcher("/listbook.jsp").forward(request, response);
return;
} catch (Exception e) {
request.setAttribute("message", "请求失败!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
}
}
四. 前台页面设计
listbook.jsp 获取所有商品
<%@ 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>My JSP 'listbook.jsp' starting page</title>
</head>
<body>
<table border="1px" cellspacing="0" align="center">
<tr>
<td>图书ID</td>
<td>图书名称</td>
<td>图书作者</td>
<td>图书价格</td>
<td>图书描述</td>
<td>操作</td>
</tr>
<c:forEach var="me" items="${map }">
<tr>
<td>${me.key }</td>
<td>${me.value.name }</td>
<td>${me.value.author }</td>
<td>${me.value.price }</td>
<td>${me.value.description }</td>
<td>
<a href="${pageContext.request.contextPath }/servlet/BuyServlet?bookid=${me.key }">购买</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
listcart.jsp 查看购物车页面
<%@ 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>My JSP 'listcart.jsp' starting page</title>
<script type="text/javascript">
//删除商品
function clearcartitem(bookid) {
var result = window.confirm("您确定要删除该商品么?");
if(result) {
window.location.href = "${pageContext.request.contextPath }/servlet/DeleteServlet?bookid="+bookid;
}
}
//清空购物车
function clearcart() {
var result = window.confirm("您确定要清空购物车么?");
if(result) {
window.location.href = "${pageContext.request.contextPath }/servlet/ClearCartServlet";
}
}
//改变购物项数量
function updateCart(input,id,oldvalue) {
var quantity = input.value;
//验证非零的正整数:^\+?[1-9][0-9]*$
var reg= /^\+?[1-9][0-9]*$/;
var result = window.confirm("请确认改为:" + quantity);
//判断输入是否为正整数
if(!reg.test(quantity)) {
alert("参数不合法!");
input.value = oldvalue;
return;
} if(result) {
window.location.href="${pageContext.request.contextPath}/servlet/UpdateCartServlet?bookid="+id + "&quantity=" + quantity;
} else {
input.value = oldvalue;
}
}
</script>
</head> <body>
<c:if test="${!empty(cart.map) }">
<table border="1px" cellspacing="0" align="center">
<tr>
<td>图书名称</td>
<td>图书作者</td>
<td>单价</td>
<td>数量</td>
<td>小计</td>
<td>操作</td>
</tr>
<c:forEach var="me" items="${cart.map }">
<tr>
<td>${me.value.book.name }</td>
<td>${me.value.book.author }</td>
<td>${me.value.book.price }</td>
<td>
<input type="text" name="quantity" value="${me.value.quantity }" style="width: 30px" onchange="updateCart(this,${me.value.book.id },${me.value.quantity })">
</td>
<td>${me.value.price }</td>
<td>
<a href="javascript:clearcartitem(${me.value.book.id })">删除</a>
</td>
</tr>
</c:forEach>
<tr>
<td colspan="2">
<a href="javascript:clearcart()">清空购物车</a>
</td>
<td colspan="2">合计</td>
<td colspan="2">${cart.price }</td>
</tr>
</table>
</c:if> <c:if test="${empty(cart.map) }">
对不起,您还没有购买任何商品!
</c:if>
</body>
</html>
附: 数据库表
create database cart_cheatsheep; use cart_cheatsheep; create table t_book(
id varchar(40) primary key,
name varchar(100) not null unique,
author varchar(100) not null unique,
price double not null,
description varchar(255)
);