需求综述:
列出网站商品(以图书为例),当用户点击“购买”时出现购物车页面,并能够依次列出用户购买的商品、修改所购买商品的数量、计算总体价格,当用户点击“删除”和“清空”时做出相应的响应。
分析实现:
利用MVC的开发框架思想,地解耦web请求过程中的数据、业务逻辑和信息展示,分层如下图所示:
其中实体类在domain包中,核心web的servlet在controller包中,service包中的类为业务类,统一对web层提供所有服务。
BookDao类:
package ssc.dao;
import java.util.Map;
import ssc.DB.DB;
import ssc.domain.Book;
public class BookDao
{
public Map getAll()
{
return DB.getAll();
}
public Book find(String id)
{
return (Book) DB.getAll().get(id);
}
}
模拟数据库类DB为:
package ssc.DB;
import java.util.LinkedHashMap;
import java.util.Map;
import ssc.domain.Book;
public class DB
{
private static Map map = new LinkedHashMap();
static
{
map.put("1",new Book("1","Java开发","赵钱",16,"好书啊。"));
map.put("2",new Book("2","JavaWeb开发","孙李",26,"好书啊。"));
map.put("3",new Book("3","Jdbc开发","周武",36,"好书啊。"));
map.put("4",new Book("4","Spring开发","郑王",46,"好书啊。"));
map.put("5",new Book("5","Android开发","马六",56,"好书啊。"));
map.put("6",new Book("6","C++开发","马六",66,"好书啊。"));
}
public static Map getAll()
{
return map;
}
}
实体类Book为:
package ssc.domain;
public class Book
{
private String id;
private String name;
private String author;
private double price;
private String description;
public Book()
{
super();
}
public Book(String id, String name, String author, double price, String description)
{
super();
this.id = id;
this.name = name;
this.author = author;
this.price = price;
this.description = description;
}
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 String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
}
购物车Cart类:
package ssc.domain;
import java.util.LinkedHashMap;
import java.util.Map;
public class Cart
{
private Map<String, CartItem> map = new LinkedHashMap();
//购物车所有商品的价格
private double price;
public Map<String, CartItem> getMap()
{
return map;
}
public void setMap(Map<String, CartItem> map)
{
this.map = map;
}
public double getPrice()
{
double totalPrice = 0;
for(Map.Entry<String, CartItem> entry : map.entrySet())
{
CartItem item = entry.getValue();
totalPrice = totalPrice + item.getPrice();
}
this.price = totalPrice;
return price;
}
public void setPrice(double price)
{
this.price = 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);
}
}
}
购物项CartItem类:
package ssc.domain;
public class CartItem
{
private Book book;
private int quantity;
private double price;
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;
this.price = this.quantity * this.book.getPrice();
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
}
服务层业务类BusinessService为:
package ssc.service;
import java.util.Map;
import ssc.dao.BookDao;
import ssc.domain.Book;
import ssc.domain.Cart;
import ssc.domain.CartItem;
//业务类,统一对web层提供所有服务
public class BusinessService
{
private BookDao dao = new BookDao();
public Map getAllBook()
{
return dao.getAll();
}
public Book findBook(String id)
{
return dao.find(id);
}
//删除购物车中的购物项
public void deleteCartItem(String id, Cart cart)
{
cart.getMap().remove(id);
}
//清除购物车
public void clearCart(Cart cart)
{
cart.getMap().clear();
}
public void changeItemQuantity(String id, String quantity, Cart cart)
{
CartItem item = cart.getMap().get(id);
item.setQuantity(Integer.parseInt(quantity));
}
}
核心控制层BuyServlet为:
package ssc.web.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ssc.domain.Book;
import ssc.domain.Cart;
import ssc.service.BusinessService;
//完成书籍购买
public class BuyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String id = request.getParameter("id");
BusinessService service = new BusinessService();
Book book = service.findBook(id);
//添加用户的购物车
Cart cart = (Cart) request.getSession().getAttribute("cart");
if (cart==null)
{
cart = new Cart();
request.getSession().setAttribute("cart", cart);
}
//把书加入到购物车,完成购买
cart.add(book);
request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
ChangeQuantityServlet为:
package ssc.web.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ssc.domain.Cart;
import ssc.service.BusinessService;
//把购物车中的书修改为指定数量
public class ChangeQuantityServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String id = request.getParameter("id");
String quantity = request.getParameter("quantity");
Cart cart = (Cart) request.getSession().getAttribute("cart");
BusinessService service = new BusinessService();
service.changeItemQuantity(id,quantity,cart);
request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
ClearCartServlet为:
package ssc.web.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ssc.domain.Cart;
import ssc.service.BusinessService;
public class ClearCartServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Cart cart = (Cart) request.getSession().getAttribute("cart");
BusinessService service = new BusinessService();
service.clearCart(cart);
request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
DeleteItemServlet为:
package ssc.web.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ssc.domain.Cart;
import ssc.service.BusinessService;
//完成删除指定的购物项
public class DeleteItemServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String id = request.getParameter("id");
Cart cart = (Cart) request.getSession().getAttribute("cart");
BusinessService service = new BusinessService();
service.deleteCartItem(id,cart);
//删除成功,跳转页面
request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
ListBookServlet为:
package ssc.web.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ssc.service.BusinessService;
//获取所有图书
public class ListBookServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
BusinessService service = new BusinessService();
Map map = service.getAllBook();
request.setAttribute("map", map);
request.getRequestDispatcher("/WEB-INF/jsp/listbook.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
工程显示首页为index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<a href="${pageContext.request.contextPath}/servlet/ListBookServlet">浏览书籍</a>
</body>
</html>
书籍列表页面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>书籍列表页面</title>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body style="text-align:center">
<h1>书籍列表</h1>
<table width="70%" border="1">
<tr>
<td>书名</td>
<td>作者</td>
<td>售价</td>
<td>描述</td>
<td>操作</td>
</tr>
<c:forEach var="entry" items="${map}" >
<tr>
<td>${entry.value.name}</td>
<td>${entry.value.author}</td>
<td>${entry.value.price}</td>
<td>${entry.value.description}</td>
<td>
<a href="${pageContext.request.contextPath }/servlet/BuyServlet?id=${entry.value.id}" target="_blank">购买</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>购物车列表</title>
<script type="text/javascript">
function deleteitem(id)
{
var b = window.confirm("您确认删除吗?");
if(b)
{
window.location.href="${pageContext.request.contextPath }/servlet/DeleteItemServlet?id="+id;
}
}
function clearcart()
{
var b=window.confirm("真的清空吗?");
if(b)
{
window.location.href="${pageContext.request.contextPath }/servlet/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 }/servlet/ChangeQuantityServlet?id=" + id +"&quantity=" + quantity;
}
}
</script>
</head>
<body style="text-align:center">
<h1>购物车列表</h1>
<c:if test="${empty(cart.map) }">
您没有购买任何商品。
</c:if>
<c:if test="${!empty(cart.map) }">
<table width="70%" border="1">
<tr>
<td>书名</td>
<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.author }</td>
<td>${entry.value.book.price }</td>
<td>
<input type="text" name="quantity" value="${entry.value.quantity }" style="width:30px" οnchange="changeQuantity(this,${entry.key },${entry.value.quantity })">
</td>
<td>${entry.value.price }</td>
<td>
<!-- 去掉超链接默认行为 -->
<a href="javascript:void(0)" οnclick="deleteitem(${entry.key})">删除</a>
</td>
</tr>
</c:forEach>
<tr>
<td colspan="3">总价</td>
<td colspan="2">${cart.price }元</td>
<td colspan="1">
<a href="javascript:void(0)" οnclick="clearcart()">清空购物车</a>
</td>
</tr>
</table>
</c:if>
</body>
</html>
在浏览器中访问该项目:
点击“浏览书籍”后进入商品(此处为图书)列表
点击“购买”后,显示购物车列表
可修改商品数量
确定修改后“总价”和“小计”随即改变
点击“删除”,删除所对应的商品
点击“清空”,可清空购物车
可修改”数量“