Shop项目--9. 清空购物车。cart.jsp

分析:


入口在cart.jsp页面的清空购物车a标签所有位置,单击触发事件,加上友好提示confirm ,确定删除后执行功能代码。

清空购物车,最直观,即把购物车cart对象,从session域中去除。而不能把session清掉,因为,session还有其他存放的信息。


准备:


步骤:

cart.jsp

1.在 清空购物车a标签位置,加入单击事件。

2.编写单击事件函数,该该函数加入confirm判断,函数跳到后台清空购物车代码。

ProductServlet

1.获取session域

2,清空session域中的cart对象

3,跳回cart.jsp页面


cart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>    
<!DOCTYPE html>
<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>黑马商城购物车</title>
		<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
		<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
		<script src="js/bootstrap.min.js" type="text/javascript"></script>
		<script type="text/javascript">
			function delProFromCart(pid){
				if(confirm("您是否确定删除该商品")){
					location.href="${pageContext.request.contextPath}/product?method=delProFromCart&pid="+pid;
				}
			}
			
			function clearCart(){
				if(confirm("您是否确定清空购物车")){
					location.href="${pageContext.request.contextPath}/product?method=clearCart";
				}
			}
		</script>
		<!-- 引入自定义css文件 style.css -->
		<link rel="stylesheet" href="css/style.css" type="text/css" />
		<style>
			body {
				margin-top: 20px;
				margin: 0 auto;
			}
			
			.carousel-inner .item img {
				width: 100%;
				height: 300px;
			}
			
			font {
				color: #3164af;
				font-size: 18px;
				font-weight: normal;
				padding: 0 10px;
			}
		</style>
	</head>

	<body>
		<!-- 引入header.jsp -->
		<jsp:include page="/header.jsp"></jsp:include>

		<div class="container">
			<div class="row">

				<!-- 判断购物车内的购物项是否为空 -->
				<c:if test="${!empty cart.cartItems }">
					<div style="margin:0 auto; margin-top:10px;width:950px;">
						<strong style="font-size:16px;margin:5px 0;">订单详情</strong>
						<table class="table table-bordered">
							<tbody>
								<tr class="warning">
									<th>图片</th>
									<th>商品</th>
									<th>价格</th>
									<th>数量</th>
									<th>小计</th>
									<th>操作</th>
								</tr>
								<!-- 动态显示购物项 -->
								<c:forEach items="${cart.cartItems }" var="entry">
									<tr class="active">
										<td width="60" width="40%">
											<input type="hidden" name="id" value="22">
											<img src="${entry.value.product.pimage }" width="70" height="60">
										</td>
										<td width="30%">
											<a target="_blank">${entry.value.product.pname }</a>
										</td>
										<td width="20%">
											¥${entry.value.product.shop_price }
										</td>
										<td width="10%">
											<input type="text" name="quantity" value="${entry.value.buyNum }" maxlength="4" size="10">
										</td>
										<td width="15%">
											<span class="subtotal">${entry.value.subtotal }</span>
										</td>
										<td>
											<a href="javascript:;" class="delete" οnclick="delProFromCart('${entry.key}')">删除</a>
										</td>
									</tr>
								</c:forEach>
							</tbody>
						</table>
					</div>
				
				</c:if>
				<!-- 购物车为空 -->
				<c:if test="${empty cart.cartItems }">
					<img  src="${pageContext.request.contextPath }/images/cart-empty.png">
				</c:if>
			</div>

			<div style="margin-right:130px;">
				<div style="text-align:right;">
					<em style="color:#ff6600;">
				登录后确认是否享有优惠  
			</em> 赠送积分: <em style="color:#ff6600;">${cart.total }</em>  商品金额: <strong style="color:#ff6600;">¥${cart.total }元</strong>
				</div>
				<div style="text-align:right;margin-top:10px;margin-bottom:10px;">
					<a href="javascript:;" οnclick="clearCart()" id="clear" class="clear">清空购物车</a>
					<a href="order_info.htm">
						<input type="submit" width="100" value="提交订单" name="submit" border="0" style="background: url('./images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
						height:35px;width:100px;color:white;">
					</a>
				</div>
			</div>

		</div>

		<!-- 引入footer.jsp -->
		<jsp:include page="/footer.jsp"></jsp:include>

	</body>

</html>

ProductServlet

package com.itheima.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.itheima.domain.Cart;
import com.itheima.domain.CartItem;
import com.itheima.domain.Category;
import com.itheima.domain.PageBean;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
import com.itheima.utils.JedisPoolUtils;

import redis.clients.jedis.Jedis;

public class ProductServlet extends BaseServlet {
	
	//清空购物车功能
	public void  clearCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取session域
		HttpSession session = request.getSession();
		//清除session域中的cart对象
		session.removeAttribute("cart");
		//跳回cart.jsp页面
		response.sendRedirect(request.getContextPath()+"/cart.jsp");
	}
	
	//在购物车中删除某一个购物项
	public void delProFromCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取要删除购物项的pid
		String pid = request.getParameter("pid");
		//获取购物车对象
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		if(cart!=null) {
			//获取购物车对象中的Map集合cartItems
			Map<String, CartItem> cartItems = cart.getCartItems();
			//修改总价
			cart.setTotal(cart.getTotal()-cartItems.get(pid).getSubtotal());
			//根据pid删除购物项
			cartItems.remove(pid);
		}
		//跳转会购物车页面
		response.sendRedirect(request.getContextPath()+"/cart.jsp");
	}
	
	//把商品加入购车功能
	public void addProductToCart(HttpServletRequest request,HttpServletResponse response) throws IOException {
		ProductService service = new ProductService();
		HttpSession session = request.getSession();
		//获取商品pid,根据pid获去加入购物车的商品
		String pid = request.getParameter("pid");
		Product product = service.findProductByPid(pid);
		int buyNum = Integer.parseInt( request.getParameter("buyNum"));
		//计算这次加入购物车的小计
		double newSubtotal = (buyNum * product.getShop_price());
		//判断之前是否已存在该购物项
		//获取购物车对象,第一次没有就创建一个,购物车对象放在session里
		Cart cart = (Cart) session.getAttribute("cart");
		if(cart==null) {
			cart = new Cart();
		}
		//定义购物车里购物项的小计,如果购物车里没有该购物项,则小计为这个加入购物车的小计
		double subtotal = newSubtotal;
		//获取购物车里的购物项集合,并判断,如果不存在直接封装购物项
		Map<String, CartItem> cartItems = cart.getCartItems();
		if(cartItems.containsKey(pid)) {
			//如果购物项已经存在,修改购物数量,还有小计,
			buyNum += cartItems.get(pid).getBuyNum();
			subtotal = newSubtotal + cartItems.get(pid).getSubtotal();
		}
		//封装购物项
		CartItem cartItem = new CartItem();
		cartItem.setBuyNum(buyNum);
		cartItem.setProduct(product);
		cartItem.setSubtotal(subtotal);
		//重新封装购物车
		cartItems.put(pid, cartItem);
		cart.setCartItems(cartItems);
		//重新更新商品总计
		double total =  cart.getTotal() + newSubtotal;
		cart.setTotal(total);
		//把购物车项重新放回session域
		session.setAttribute("cart", cart);
		//重定向到购物车页面
		response.sendRedirect(request.getContextPath()+"/cart.jsp");
		
	}
	
	//显示商品详细信息product_info.jsp 功能
	public void productInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ProductService service= new ProductService();
		//获取商品pid cid currentPage
		String pid = request.getParameter("pid");
		String cid = request.getParameter("cid");
		String currentPage = request.getParameter("currentPage");
		//根据pid查询商品
		Product product = service.findProductByPid(pid);
		//传到request域 转发到product_info.jsp
		request.setAttribute("product", product);
		//需要currentPage与cid,为了返回上一级功能作必要参数
		request.setAttribute("cid", cid);
		request.setAttribute("currentPage", currentPage);
		
		//第一次访问,pids的值就是pid
		String pids = pid;
		//获取cookies
		Cookie[] cookies = request.getCookies();
		if(cookies!=null) {
			//不为空才执行该搓澡
			for(Cookie cookie:cookies) {
				if(cookie.getName().equals("pids")){
					//获取pids   ----- 3-2-1
					pids = cookie.getValue();
					//把“-”去除
					String[] split = pids.split("-");//[3,2,1]
					//翻到LinkedList方便之后的修改pids操作
					List<String> asList = Arrays.asList(split);
					LinkedList<String> list = new LinkedList<String>(asList);
					//判断cookie pids中已经存在该pid
					if(list.contains(pid)) {
						//已经存在,删除后再添加到头
						list.remove(pid);
						list.addFirst(pid);
					}else {
						//不存在,直接添加到头
						list.addFirst(pid);
					}
					//从新变回3-2-1模式 限制显示数量为7个
					StringBuffer sb = new StringBuffer();
					for(int i=0; i<list.size(); i++) {
						sb.append(list.get(i));
						sb.append("-");
					}
					pids=sb.substring(0, sb.length()-1);
				}
			}
		}
		//把pids存到cookies中
		Cookie cookie_pids = new Cookie("pids", pids);
		response.addCookie(cookie_pids);
		
		request.getRequestDispatcher("/product_info.jsp").forward(request, response);
	}

	//根据商品分类cid查找商品,并显示在商品列表product_list.jsp功能
	public void productListByCid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		ProductService service= new ProductService();
		//设置当前显示条数当前页,为null默认为第一页,
		String currentPageStr = request.getParameter("currentPage");
		if(currentPageStr==null) {
			currentPageStr="1";
		}
		int currentPage = Integer.parseInt(currentPageStr);
		int currentCount = 12;
		//获取cid,并根据cid获取商品列表
		String cid = request.getParameter("cid");
		//传递数据到service层,封装pageBean
		PageBean<Product> pageBean = service.findPageBean(currentPage,currentCount,cid);
		//把pageBean传到request域
		request.setAttribute("pageBean", pageBean);
		//分页跳转回这个功能的时候需要cid
		request.setAttribute("cid", cid);
		
		//历史商品记录显示
		//从cookies获取pids
		Cookie[] cookies = request.getCookies();
		List<Product> historyProductList = new ArrayList<Product>();
		if(cookies!=null) {
			for(Cookie cookie :cookies) {
				if(cookie.getName().equals("pids")) {
					String pids = cookie.getValue();
					String[] split = pids.split("-");
					//根据数组中的每个pid 进行遍历获取商品,限制数量为7个
					for(int i=0; i<split.length&&i<7;i++) {
						Product  product = service.findProductByPid(split[i]);
						historyProductList.add(product);
					}
				}
			}
		}
		//把历史商品集合传到request域
		request.setAttribute("historyProductList", historyProductList);
		request.getRequestDispatcher("/product_list.jsp").forward(request, response);
	
	}
	
	
	//查找所有商品分类
	public void findAllCategory(HttpServletRequest request, HttpServletResponse response) throws IOException {
//		ProductService service = new ProductService();
//		//从redis获取,并判断是否已存在categoryListJson
//		Jedis jedis = JedisPoolUtils.getJedis();
//		String categoryListJson = jedis.get("categoryListJson");
//		if(categoryListJson==null) {
//			//如果不存在,从数据库查找,并存在redis中
//			List<Category> categoryList = service.findAllCategory();
//			Gson gson = new Gson();
//			categoryListJson = gson.toJson(categoryList);
//			jedis.set("categoryListJson", categoryListJson);
//		}
//		response.setContentType("text/html;charset=UTF-8");
//		response.getWriter().write(categoryListJson);
		
		//从数据库查找所有商品分类
		ProductService service = new ProductService();
		List<Category> categoryList = service.findAllCategory();
		//把categoryList变为json格式
		Gson gson = new Gson();
		String categoryListJson = gson.toJson(categoryList);
		//把jason传回ajax
		//有中文解决乱码问题
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(categoryListJson);
		
	}
	
	//首页index显示热门商品与最新商品功能
	public void index (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ProductService service = new ProductService();
		//获取热门商品---list<Product>--hotProductList
		List<Product> hotProductList = service.findHotProduct();
		//获取最新商品--list<Product>--newProductList
		List<Product> newProductList = service.findNewProduct();
		//传到request域
		request.setAttribute("hotProductList", hotProductList);
		request.setAttribute("newProductList", newProductList);
		//转发
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
}

ProductService

package com.itheima.service;

import java.sql.SQLException;
import java.util.List;

import com.itheima.dao.ProductDao;
import com.itheima.domain.Category;
import com.itheima.domain.PageBean;
import com.itheima.domain.Product;

public class ProductService {

	//获取热门商品
	public List<Product> findHotProduct() {
		ProductDao dao = new ProductDao();
		List<Product> hotProductList=null;
		try {
			hotProductList = dao.findHotProduct();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return hotProductList;
	}

	//获取最新商品
	public List<Product> findNewProduct() {
		ProductDao dao = new ProductDao();
		List<Product> newProductList=null;
		try {
			newProductList =  dao.findNewProduct();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return newProductList;
	}

	//查找商品所有分类
	public List<Category> findAllCategory() {
		ProductDao dao = new ProductDao();
		List<Category> categoryList =null;
		try {
			categoryList = dao.findAllCategory();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return categoryList;
	}


	//封装PageBean对象
	public PageBean<Product> findPageBean(int currentPage, int currentCount, String cid) {
		ProductDao dao = new ProductDao();
		//创建PageBean对象
		PageBean<Product> pageBean = new PageBean<Product>();
		//封装当前页
		pageBean.setCurrentPage(currentPage);
		//封装当前显示条数
		pageBean.setCurrentCount(currentCount);
		//封装总共条数
		int totalCount =0;
		try {
			totalCount = dao.findTotalCount(cid).intValue();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		pageBean.setTotalCount(totalCount);
		
		//封装总共页数
		int totalPage = (int) Math.ceil((1.0*totalCount/currentCount));
		pageBean.setTotalPage(totalPage);
		
		//封装商品列表
		int index = (currentPage-1)*currentCount;
		List<Product> productList =null;
		try {
			productList =  dao.findProductByCid(cid,index,currentCount);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		pageBean.setList(productList);
		
		return pageBean;
	}

	//根据pid查询商品
	public Product findProductByPid(String pid) {
		ProductDao dao = new ProductDao();
		Product product =null;
		try {
			product = dao.findProductByPid(pid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return product;
	}


}


ProductDao

package com.itheima.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.itheima.domain.Category;
import com.itheima.domain.Product;
import com.itheima.utils.DataSourceUtils;

public class ProductDao {

	//获取热门商品
	public List<Product> findHotProduct() throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from product where is_hot=? limit ?,?";
		return runner.query(sql, new BeanListHandler<Product>(Product.class), 1,0,9);
	}

	//获取最新商品
	public List<Product> findNewProduct() throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from product order by pdate desc limit ?,?";
		return runner.query(sql, new BeanListHandler<Product>(Product.class), 0,9);
	}

	//查找商品所有分类
	public List<Category> findAllCategory() throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from category";
		return runner.query(sql, new BeanListHandler<Category>(Category.class));
	}

	// 根据cid查询还有起始索引获得指定数量的商品集合
	public List<Product> findProductByCid(String cid, int index, int currentCount) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from product where cid=? limit ?,?";
		return runner.query(sql, new BeanListHandler<Product>(Product.class), cid,index,currentCount);
	}

	//根据cid查询所有商品的总数
	public Long findTotalCount(String cid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select count(*) from product where cid=?";
		Long query = (Long) runner.query(sql, new ScalarHandler(), cid);
		return query;
		
	}

	//根据pid查询商品
	public Product findProductByPid(String pid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from product where pid=?";
		Product query = runner.query(sql, new BeanHandler<Product>(Product.class), pid);
		return query;
	}

}




  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值