CartServlet 程序:
protected void ajaxAddItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取请求的参数 商品编号
int id = WebUtils.parseInt(req.getParameter("id"), 0);
// 调用bookService.queryBookById(id):Book得到图书的信息
Book book = bookService.queryBookById(id);
// 把图书信息,转换成为CartItem商品项
CartItem cartItem = new CartItem(book.getId(),book.getBookName(),1,book.getPrice(),book.getPrice());
//判断Session域中是否cart属性,没就创建,就获得
Cart cart = (Cart) req.getSession().getAttribute("cart");
if(cart == null){
// 创建一个购物车
cart = new Cart();
req.getSession().setAttribute("cart",cart);
}
// 调用Cart.addItem(CartItem);添加商品项
cart.addItem(cartItem);
// 最后一个添加的商品名称
req.getSession().setAttribute("lastName", cartItem.getName());
//6、返回购物车总的商品数量和最后一个添加的商品名称
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("totalCount",cart.getTotalCount());
resultMap.put("lastName",cartItem.getName());
Gson gson = new Gson();
String resultMapJsonString = gson.toJson(resultMap);
resp.getWriter().write(resultMapJsonString);
}
pages/client/index.jsp 页面
html 代码:
<div style="text-align: center">
<c:if test="${not empty sessionScope.cart.items}">
<%--购物车非空的输出--%>
<%-- <span>您的购物车中${sessionScope.cart.totalCount}件商品</span>--%>
您的购物车中<span id="cartTotalCount" style="color: red">${sessionScope.cart.totalCount}</span>件商品
<div>
<%-- 您刚刚将<span style="color: red">${sessionScope.lastName}</span>加入到了购物车中--%>
您刚刚将<span id="cartLastName" style="color: red">${sessionScope.lastName}</span>加入到了购物车中
</div>
</c:if>
<c:if test="${empty sessionScope.cart.items}">
<%--购物车为空的输出--%>
<div style="color: red">
当前购物车为空,快挑心仪的商品吧!!!!
</div>
</c:if>
javaScript 代码:
$(".addToCart").click(function () {
/**
* 在事件响应的function函数 中,一个this对象,这个this对象,是当前正在响应事件的dom对象
* @type {jQuery}
*/
var $bookId = $(this).attr("bookId");//attr():获取某属性的值
// location.href = "http://localhost:8080/MyBookStore/cartServlet?action=addItem&id=" + $bookId;
$.getJSON("http://localhost:8080/MyBookStore/cartServlet","action=ajaxAddItem&id=" + $bookId,
function (data) {
$("#cartTotalCount").text(data.totalCount);
// alert(data.totalCount);
// alert(data.lastName);
$("#cartLastName").text(data.lastName);
});
});