购物车的servlet:
// 添加条目
public String add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cart cart = (Cart) request.getSession().getAttribute("cart");// 得到购物车
String bid = request.getParameter("bid");// 得到书的bid
Book book = new BookService().load(bid);// 通过bid得到书的信息
int count = Integer.parseInt(request.getParameter("count"));// 得到数量
CartItem cartItem = new CartItem();// 创建一个条目对象
cartItem.setBook(book);// 设置书
cartItem.setCount(count);// 设置总数
if (cart == null) {
return "f:/jsps/cart/list.jsp";
}
cart.add(cartItem);// 将条目添加到车中
return "f:/jsps/cart/list.jsp";
}
// 删除条目
public String clear(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cart cart = (Cart) request.getSession().getAttribute("cart");// 得到购物车
cart.clear();// 清空购物车
return "f:/jsps/cart/list.jsp";
}
// 安照所给的bid删除条目
public String delete(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Cart cart = (Cart) request.getSession().getAttribute("cart");// 得到购物车
String bid = request.getParameter("bid");// 得到书的bid
cart.delete(bid);// 根据bid删除条目
return "f:/jsps/cart/list.jsp";
}
购物车的jsp:
<h1>购物车</h1>
<c:choose>
<c:when test="${empty sessionScope.cart or fn:length(sessionScope.cart.cartItems) eq 0 }">
<img src="<c:url value='/images/cart.png'/>" width="250"/>
</c:when>
<c:otherwise>
<table border="1" width="100%" cellspacing="0" background="black">
<tr>
<td colspan="7" align="right" style="font-size: 15pt; font-weight: 900">
<a href="<c:url value="/CartServlet?method=clear"/>">清空购物车</a>
</td>
</tr>
<tr>
<th>图片</th>
<th>书名</th>
<th>作者</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
<c:forEach items="${sessionScope.cart.cartItems }" var="cartItem">
<tr>
<td><div><img src="<c:url value='/${cartItem.book.image }'/>"/></div></td>
<td>${cartItem.book.bname }</td>
<td>${cartItem.book.author }</td>
<td>${cartItem.book.price }元</td>
<td>${cartItem.count }</td>
<td>${cartItem.tatal }元</td>
<td><a href="<c:url value="/CartServlet?method=delete&bid=${cartItem.book.bid }"/>">删除</a></td>
</tr>
</c:forEach>
<tr>
<td colspan="7" align="right" style="font-size: 15pt; font-weight: 900">
合计:${sessionScope.cart.total }元
</td>
</tr>
<tr>
<td colspan="7" align="right" style="font-size: 15pt; font-weight: 900">
<a id="buy" href="<c:url value='/jsps/order/desc.jsp'/>"></a>
</td>
</tr>
</table>
</c:otherwise>
</c:choose>