这篇来做一个练习,就是图书详情页面,点击购买按钮,这本书添加到购物中。购物车中主要思想就是采用HashMap来存储数据。
1.需求场景
浏览器打开http://localhost:8080/BookManagement/pageServlet?currentPage=1
显示图书列表,例如点击第一本进入该书的详情页。
点击购买,这本书被添加到购物中。
2.大致实现思路
这里来想一下大致实现的思路,就是product_info.jsp页面点击购买按钮,这个跳转到一个addCartServlet中,把book.id传过来,然后根据id去查询这本书,然后放入购物车页面,大致就是这么一个过程。
3.给购买按钮添加链接跳转
这里跳转到一个addCartServlet,关键是id需要传过来,找到product_info.jsp,找到添加这个元素位置,代码变动如下(红圈位置是代码变动)。
具体代码如下
<div style="text-align:center; margin-top:25px">
<a href="${pageContext.request.contextPath}/addCartServlet?id=${book.id}"> <img src="images/buybutton.gif" border="0" />
</a>
</div>
4.创建AddCartServlet.java
这里先创建一个空的servlet文件
5.Dao/Service层代码
看看Dao层代码,由于这里我们根据id来查找图书,这个方法我们之前写过了,所以本次练习不需要更改Dao和Service层代码。
6.Servlet文件代码
package com.anthony.web.servlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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 com.anthony.domain.Book;
import com.anthony.service.BookService;
import com.anthony.service.BookServiceImpl;
public class AddCartServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
//根据id去查找book
BookService bs = new BookServiceImpl();
Book book = bs.findBookById(id);
//从session中购物车取出来
HttpSession session = request.getSession();
Map<Book, String> cart = (Map<Book, String>) session.getAttribute("cart");
int num = 1;
if(cart == null) {
cart = new HashMap<Book, String>();
}
// 如果购物车中包含这本书,num就要加1
if(cart.containsKey(book)) {
num = Integer.parseInt(cart.get(book)) + 1;
}
// 把图书放入购物车
cart.put(book, num+"");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
但是上面有一个问题,在这行代码cart.containsKey(book)
Book是一个高级对象,这个引用对象比较,虽然查找出来的book 和session中的book值一样,但是地址不一样,hashmap是根据hashcode去比较,这里我们来Book.java类重写下hashCode和equal方法。
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
继续写Servlet代码,添加一个打印内容,可以点击继续购物或者点击查看购物车
package com.anthony.web.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
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 com.anthony.domain.Book;
import com.anthony.service.BookService;
import com.anthony.service.BookServiceImpl;
public class AddCartServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String id = request.getParameter("id");
//根据id去查找book
BookService bs = new BookServiceImpl();
Book book = bs.findBookById(id);
//从session中购物车取出来
HttpSession session = request.getSession();
Map<Book, String> cart = (Map<Book, String>) session.getAttribute("cart");
int num = 1;
if(cart == null) {
cart = new HashMap<Book, String>();
}
// 如果购物车中包含这本书,num就要加1
if(cart.containsKey(book)) {
num = Integer.parseInt(cart.get(book)) + 1;
}
// 把图书放入购物车
cart.put(book, num+"");
// 把cart对象放回session作用域中
session.setAttribute("cart", cart);
out.print("<a href='"+request.getContextPath()+"/pageServlet'>继续购物</a>, <a href='"+request.getContextPath()+"/cart.jsp'>查看购物车</a>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
上面就添加了字符集设置和最后一行out输出,里面链接跳转。
下面来在cart.jsp页面中写一个循环,因为购物车列表存在多条数据的情况,下面代码主要看49-73行
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>电子书城</title>
<link rel="stylesheet" href="css/main.css" type="text/css" />
</head>
<body class="main">
<jsp:include page="head.jsp" />
<jsp:include page="menu_search.jsp" />
<div id="divpagecontent">
<table width="100%" border="0" cellspacing="0">
<tr>
<td><div style="text-align:right; margin:5px 10px 5px 0px">
<a href="index.html">首页</a> > 购物车
</div>
<table cellspacing="0" class="infocontent">
<tr>
<td><img src="ad/page_ad.jpg" width="666" height="89" />
<table width="100%" border="0" cellspacing="0">
<tr>
<td><img src="images/buy1.gif" width="635" height="38" />
</td>
</tr>
<tr>
<td>
<table cellspacing="1" class="carttable">
<tr>
<td width="10%">序号</td>
<td width="30%">商品名称</td>
<td width="10%">价格</td>
<td width="20%"> 数量</td>
<td width="10%">库存</td>
<td width="10%">小计</td>
<td width="10%">取消</td>
</tr>
</table>
<c:forEach items="${cart}" var="entry" varStatus="vs">
<table width="100%" border="0" cellspacing="0">
<tr>
<td width="10%">${vs.count}</td>
<td width="30%">${entry.key.name }</td>
<td width="10%">${entry.key.price }</td>
<td width="20%"><input type="button" value='-'
style="width:20px"
onclick="">
<input name="text" type="text" value="${entry.value}"
style="width:40px;text-align:center" /> <input
type="button" value='+' style="width:20px"
onclick="">
</td>
<td width="10%">${entry.key.pnum}</td>
<td width="10%">${entry.key.price*entry.value}</td>
<td width="10%"><a href="${pageContext.request.contextPath}/changeCart?id=${entry.key.id}&count=0"
style="color:#FF0000; font-weight:bold">X</a></td>
</tr>
</table>
</c:forEach>
<table cellspacing="1" class="carttable">
<tr>
<td style="text-align:right; padding-right:40px;"><font
style="color:#FF6600; font-weight:bold">合计: ${total}元</font>
</td>
</tr>
</table>
<div style="text-align:right; margin-top:10px">
<a
href="${pageContext.request.contextPath}/showProductByPage"><img
src="images/gwc_jx.gif" border="0" /> </a>
<a
href="${pageContext.request.contextPath}/order.jsp"><img
src="images/gwc_buy.gif" border="0" /> </a>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table></td>
</tr>
</table>
</div>
<jsp:include page="foot.jsp" />
</body>
</html>
保存代码,接下来进行部署测试
7.部署测试
保存代码,部署重启Tomcat服务器,然后来点击购买和查看购物车操作。
点击购买之后,跳转页面输出如下内容。
这里点击继续购物,再买一本。然后点击查看购物车。