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 {//获取要删除购物项的pidString pid = request.getParameter("pid");//获取购物车对象Cart cart = (Cart) request.getSession().getAttribute("cart");if(cart!=null) {//获取购物车对象中的Map集合cartItemsMap<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 currentPageString pid = request.getParameter("pid");String cid = request.getParameter("cid");String currentPage = request.getParameter("currentPage");//根据pid查询商品Product product = service.findProductByPid(pid);//传到request域 转发到product_info.jsprequest.setAttribute("product", product);//需要currentPage与cid,为了返回上一级功能作必要参数request.setAttribute("cid", cid);request.setAttribute("currentPage", currentPage);//第一次访问,pids的值就是pidString pids = pid;//获取cookiesCookie[] cookies = request.getCookies();if(cookies!=null) {//不为空才执行该搓澡for(Cookie cookie:cookies) {if(cookie.getName().equals("pids")){//获取pids ----- 3-2-1pids = 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中已经存在该pidif(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层,封装pageBeanPageBean<Product> pageBean = service.findPageBean(currentPage,currentCount,cid);//把pageBean传到request域request.setAttribute("pageBean", pageBean);//分页跳转回这个功能的时候需要cidrequest.setAttribute("cid", cid);//历史商品记录显示//从cookies获取pidsCookie[] 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>--hotProductListList<Product> hotProductList = service.findHotProduct();//获取最新商品--list<Product>--newProductListList<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;}}
Shop项目--9. 清空购物车。cart.jsp相关推荐
- 项目-Java Web购物车-JSP实现
文章目录 源码地址 界面演示 目录结构 准备工作 登录注册功能 定义Dao BaseDao ProductDaoImp 定义Entity Product CartItem 商品列表与详情界面 ★购物车 ...
- java清空购物车方法_Javaweb网上商城项目实战(21)删除和清空购物车
删除购物车原理分析 具体实现 在cart.jsp中绑定点击删除事件 在页面中的删除标签里面加一个id 编写删除的方法 在CartServlet中添加删除购物车商品的方法removeCartItem / ...
- Shop项目--12. 显示用户订单列表order_list.jsp
分析: 显示用户订单列表在order_list.jsp页面,要一个功能servlet,把数据传递给前台页面显示.同时要先判断用户是否已经登陆.关键在于数据需要怎么封装,这里涉及多表查询. 1.根据ui ...
- MVC项目功能之加入购物车,清空购物车
一.本期目标 1.加入购物车 2.购物车查询 3.清空购物车 实现购物的三种方式: 第一种:session 保存购物车信息到session 1.点击我的购物车,查询后台的seesion,通过用户 ...
- Easyui项目之添加购物车、清空购物车
添加购物车.清空购物车 添加购物车的三种方式 一:session保存购物车信息到session服务端 1.点击我的购物车查询后台的session,通过用户账号去找2.如果有那就显示,如果没有不显示 3 ...
- EasyUI项目之门户(添加查询购物车与清空购物车)
目标效果: 目标: 1,添加查询购物车 2,清空购物车 一,添加查询购物车 三种实现方法 0.1 session 保存购物车信息到session服务端 0.2 cookie保存购物车到本地(效率更高 ...
- vue项目购物车组件、清空购物车
1.购物车组件 <template><div><div class="shopcart"><div class="content ...
- 【python初学者日记】selenium初体验——“秒杀商品”、“清空购物车”技能养成记(一)
[python初学者日记]selenium初体验--"秒杀商品"."清空购物车"技能养成记(一) 用python解决"清空购物车".&quo ...
- UNIAPP实战项目笔记43 购物车页面修改收货地址和修改默认地址
UNIAPP实战项目笔记43 购物车页面修改收货地址和修改默认地址 实际案例图片 修改收货地址和修改默认地址页面布局和功能 具体内容图片自己替换哈,随便找了个图片的做示例 用到了vuex的状态机,具体 ...
最新文章
- 11.2.0.2 asmcmd lsdg show incorrect diskgroup number
- NYOJ 士兵杀敌(四) 树状数组
- struts.preperties说明
- ubuntu上面svn用merge合并到之前的版本
- Ios 12 linux,苹果发布iOS 12.4.1,以修补越狱漏洞
- matlab对多项式求导,matlab中多项式求导
- django-普通的cookie操作
- 关于有类路由协议和无类路由协议
- 使用pandas 按同一列名称合并,并解决concat() got an unexpected keyword argument ‘join_axes‘报错
- Hibernate建立关系配置(hbm.xml)bag中cascade属性
- azcopy将本地目录上传到blob远端仓库中
- Cocos2d-x windows + vs2010 配置图文详解
- Lodop 打印使用笔记
- 关于软件开发中遇到的问题解决思路
- 【头歌educoder】离散数学实训参考-第二章-关系-part1-关系基础
- 基于Transformer的多变量风电功率预测TF2
- Java实现表单登陆及验证
- linux kernel bridge 数据包流向
- linux系统怎么连接显示器,Ubuntu下外接显示器双屏显示的方法
- GAT(参数中加入batch)
热门文章
- <JVM下篇:性能监控与调优篇>03-JVM监控及诊断工具-GUI篇
- 华为数据之道(3):面向业务的信息架构建设
- 解决IOS微信浏览器底部会出现向前向后返回按钮问题
- 多搜 - 多个网站一起搜 (舆情监控版)
- mysql增加数据 条件,mysql根据条件决定是否插入数据
- Apache启动报错:Apache is running a threaded MPM
- 谷歌与DeepMind的控制权之战,刚刚开始
- java设置excel行间距_java用POI设置Excel的列宽
- 密码套件cipher suite
- prach频域位置_[转载]zz LTE PRACH时频资源及选择