17_购物车删除商品与清空购物车
购物车删除商品与清空购物车
- 步骤分析
1)步骤分析
从购物车中删除商品
- 在购物车页面上,点击删除:${path}/cart/remove?pid=xxx
- 在CartServlet处理删除路径
先获取商品pid
获取购物车
删除购物车项 - 重定向到/jsp/cart.jsp
清空购物车
- 在购物车页面上,有一个清空购物车的连接:${path}/cart/clear
- 在CartServlet中处理清空
先获取购物车
调用清空方法
重定向 - 在cart.jsp上判断购物车是否为空
若为空:提示购物车空空如也
若不为空:展示购物车
2)代码实现
购物车中删除商品
① 在cart.jsp上给删除添加点击事件
<script type="text/javascript">
//从购物车中删除商品
function removeFromCart(pid){
if(confirm("您确认狠心要丢弃我吗?")){
location.href="${pageContext.request.contextPath}/cart/remove?pid="+pid;
}
}
</script>
② 在CartServlet中处理删除路径
/**
* 从购物车中移除购物项
* @param request
* @param response
* @throws IOException
*/
private void remove(HttpServletRequest request, HttpServletResponse response) throws IOException {
//1、获取商品的pid
String pid=request.getParameter("pid");
//2、调用购物车的remove的方法
getCart(request).removeFromCart(pid);
//3、重定向
response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
}
清空钩购物车
① 在cart.jsp上给清空购物车添加一个连接
<a href="${path }/cart/clear" id="clear" class="clear">清空购物车</a>
② 在CartServlet中处理该路径
/**
* 清空购物车
* @param request
* @param response
* @throws IOException
*/
private void clear(HttpServletRequest request, HttpServletResponse response) throws IOException {
//先获取购物车清空
getCart(request).clearCart();
//重定向
response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
}
③ 在cart.jsp上判断购物车是否为空
<!-- 判断购物车是否为空 -->
<c:if test="${empty cart.map }">
<h1>购物车空空如也~~去逛逛吧</h1>
</c:if>
<c:if test="${not empty cart.map }">
...
</c:if>