JavaWeb购物车实现

在这里插入图片描述

package cn.itcast.web.domain;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shkstart
 * @create 2019-12-11-17:11
 * 购物车
 */
public class Cart {
    private Map<String,CartItem> maps;
    //private int size;
    public Cart() {
        maps=new HashMap<>();
    }
    public int getSize() {
        return maps.size();
    }

    public Map<String, CartItem> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, CartItem> maps) {
        this.maps = maps;
    }

    /**
     * 1.添加购物项到购物车中
     * 思路:判断购物车的集合maps中是否存在要添加的商品。
     * 存在:修改购物车中maps集合中此商品的数量
     * 不存在:就将此商品添加到maps集合中
     */
    //1.添加购物项到购物车中
    public void addCartItem(Product product) {
        if(maps.containsKey(product.getPid())){
            CartItem cartItem = maps.get(product.getPid());
            cartItem.setNum(cartItem.getNum()+1);
        }else{
            CartItem carItem=new CartItem();
            carItem.setNum(1);
            carItem.setProduct(product);
            //将次购物项添加到map集合中
            maps.put(product.getPid(),carItem);
        }
    }
    //从购物车中查询购物项
    public CartItem findCartItem(String pid) {
        return maps.get(pid);
    }
    //从购物车中删除此商品
    public void removeCartItem(String pid) {
        maps.remove(pid);
    }
    //清空购物车
    public void clear() {
        for (CartItem cartItem : maps.values()) {
            //得到购物车中的每一件商品
            Product product = cartItem.getProduct();
            //恢复库存量
            product.setQuantity(product.getQuantity()+cartItem.getNum());
        }
        //清空购物车
        maps.clear();
    }
}

package cn.itcast.web.domain;

/**
 * @author shkstart
 * @create 2019-12-11-17:09
 * 购物项
 *
 */
public class CartItem {
    private Product product;
    private int num;
    private double total;

    public CartItem() {
    }

    public CartItem(Product product, int num, double total) {
        this.product = product;
        this.num = num;
        this.total = total;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    @Override
    public String toString() {
        return "CarItem{" +
                "product=" + product +
                ", num=" + num +
                ", total=" + total +
                '}';
    }
}

package cn.itcast.web.domain;

/**
 * Created by WF on 2019/12/10 15:19
 * 功能:商品类
 */
public class Product {
    private String pid;         //商品id
    private String pname;       //商品名称
    private float price;        //商品价格
    private int quantity;       //商品库存

    public Product() {
    }

    public Product(String pid, String pname, float price, int quantity) {
        this.pid = pid;
        this.pname = pname;
        this.price = price;
        this.quantity = quantity;
    }

    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    @Override
    public String toString() {
        return "Product{" +
                "pid='" + pid + '\'' +
                ", pname='" + pname + '\'' +
                ", price=" + price +
                ", quantity=" + quantity +
                '}';
    }
}

package cn.itcast.web.listener;

import cn.itcast.web.domain.Product;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shkstart
 * @create 2019-12-11-17:15
 * application的监听器
 */
@WebListener
public class MyApplicationContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //1.得到application对象
        ServletContext application = sce.getServletContext();
        Product p1 = new Product("1001", "双飞燕鼠标", 98.0f, 100);
        Product p2 = new Product("1002", "联想电脑", 3998.0f, 500);
        Product p3 = new Product("1003", "海尔洗衣机", 1200.0f, 200);
        Product p4 = new Product("1004", "海飞丝洗发水", 45.0f, 80);
        Product p5 = new Product("1005", "IPhone平板", 3000.0f, 300);
        Product p6 = new Product("1006", "洽洽瓜子", 5.0f, 200);
        //2.将商品放到map集合中
        Map<String,Product> products = new HashMap<>();
        products.put(p1.getPid(), p1);
        products.put(p2.getPid(), p2);
        products.put(p3.getPid(), p3);
        products.put(p4.getPid(), p4);
        products.put(p5.getPid(), p5);
        products.put(p6.getPid(), p6);
        //3.将集合放到servletContext这个作用域中
        application.setAttribute("products",products);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}

package cn.itcast.web.selvert;

import cn.itcast.web.domain.Cart;
import cn.itcast.web.domain.CartItem;
import cn.itcast.web.domain.Product;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @author shkstart
 * @create 2019-12-11-17:33
 */
@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.根据请求参数调用不同的方法
        String cmd = req.getParameter("cmd");
        //2.判断根据参数内容调用哪个方法
        if(cmd!=null&&!"".equals(cmd)){
            if("add".equals(cmd)){
                add(req,resp);
            }else if("remove".equals(cmd)){
                remove(req,resp);
            }else if("clear".equals(cmd)){
                clear(req,resp);
            }
        }
    }




    //添加商品到购物车
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //得到商品pid
        String pid = req.getParameter("pid");
        //从原始servletContext中拿到商品集合查询此商品
        //得到servletContext对象
        ServletContext servletContext = req.getServletContext();
        //从对象中拿到集合
        Map<String, Product> maps =(Map<String, Product>) servletContext.getAttribute("products");
        //在此集合中根据商品id查询出此商品
       if(maps.containsKey(pid)) {
           Product product = maps.get(pid);
           //从session中得到购物车对象
           HttpSession session = req.getSession();
           Cart cart = (Cart) session.getAttribute("cart");
           //判断此购物车是否存在
           if (cart==null){
               cart=new Cart();
           }
           cart.addCartItem(product);
           //修改库存量
           product.setQuantity(product.getQuantity()-1);
           //将此购物车添加到session中
           session.setAttribute("cart",cart);
           //跳转到购物车列表
           resp.sendRedirect(req.getContextPath()+"/cart.jsp");


       }
    }
    //移除购物车中的商品
    private void remove(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //得到商品id
        String pid = req.getParameter("pid");
        // 从session中的购物车查询指定的商品
        //得到session对象
        HttpSession session = req.getSession();
        //得到session中的购物车对象
        Cart cart = (Cart) session.getAttribute("cart");
        //从购物车中查询出此商品
        CartItem cartItem = cart.findCartItem(pid);
        //修改库存量(第一件事情)
        //得到购物项的商品
        Product product = cartItem.getProduct();
        //修改商品的库存
        product.setQuantity(product.getQuantity() + cartItem.getNum());
        //从session中的购物车移除此商品
        cart.removeCartItem(pid);
        //将cart对象重新放回到购物车中
        session.setAttribute("cart",cart);
        //跳转到购物车列表
        resp.sendRedirect(req.getContextPath() + "/cart.jsp");

    }
    //清空购物车
    private void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //从session中拿到购物车
        //得到session
        HttpSession session = req.getSession();
        Cart cart = (Cart)session.getAttribute("cart");
        cart.clear();
        resp.sendRedirect(req.getContextPath()+"/cart.jsp");
    }
}

package cn.itcast.web.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by WF on 2019/12/6 14:11
 */
public class JdbcUtils {
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
    //1.得到数据原
    public static DataSource getDataSource(){
        return dataSource;
    }
    //2.得到连接
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}

base.jsp

<%--1.导入bootstrap--%>
<link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap-3.3.7/css/bootstrap.min.css">
<script src="${pageContext.request.contextPath}/bootstrap-3.3.7/js/jquery.min.js"></script>
<script src="${pageContext.request.contextPath}/bootstrap-3.3.7/js/bootstrap.min.js"></script>

cart.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ include file="/base.jsp" %>
<html>
  <head>
    <title>列表购物车</title>
    <style>
      .container{
        margin-top:20px;
      }
      .table{
        text-align:center;
      }
    </style>
  </head>
  <body>
  <div class="container">

    <div class="panel panel-primary">
      <div class='panel-heading'>
        <div class="h4">购物车列表</div>
      </div>
      <table class="table table-striped table-hover table-bordered">
        <tr>
          <td>商品id</td>
          <td>商品名称</td>
          <td>商品单价</td>
          <td>购买数量</td>
          <td>操作</td>
        </tr>
        <c:forEach items="${cart.maps}" var="p">
        <tr>
          <td>${p.value.product.pid}</td>
          <td>${p.value.product.pname}</td>
          <td>${p.value.product.price}</td>
          <td>${p.value.num}</td>
          <td>
            <a  class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/cart?cmd=remove&pid=${p.value.product.pid}">删除</a>
          </td>
        </tr>
        </c:forEach>
        <c:if test="${cart.size == 0}">
          <tr>
            <td colspan="5">购物车中没有商品!</td>
          </tr>
        </c:if>
      </table>
      <div class="panel-footer text-right">
        <a href="${pageContext.request.contextPath }/cart?cmd=clear" class="btn btn-danger btn-sm">清空购物车</a>
        <a href="${pageContext.request.contextPath }/index.jsp" class="btn btn-primary btn-sm">返回继续购物</a>
      </div>
    </div>
  </div>

  </body>
</html>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@include file="/base.jsp"%>
<html>
  <head>
    <title>列表所有商品</title>
    <style>
      .container{
        margin-top:20px;
      }
      .table{
        text-align:center;
      }
    </style>
  </head>
  <body>
  <div class="container">

    <div class="panel panel-primary">
      <div class='panel-heading'>
        <div class="h4">商品列表</div>
      </div>
      <table class="table table-striped table-hover table-bordered">
        <tr>
          <td>商品id</td>
          <td>商品名称</td>
          <td>商品单价</td>
          <td>商品库存</td>
          <td>是否挑选</td>
        </tr>
        <c:forEach items="${products}" var="p">
          <tr>
            <td>${p.value.pid}</td>
            <td>${p.value.pname}</td>
            <td>${p.value.price}</td>
            <td>${p.value.quantity}</td>
            <td>
              <a  class="btn btn-success btn-sm" href="${pageContext.request.contextPath}/cart?cmd=add&pid=${p.value.pid}">挑选</a>
            </td>
          </tr>
        </c:forEach>
      </table>
      <div class="panel-footer text-right">
        <a href="${pageContext.request.contextPath }/cart.jsp" class="btn btn-primary">查看购物车</a>
      </div>
    </div>
  </div>
  </body>
</html>

在这里插入图片描述
在这里插入图片描述

  • 12
    点赞
  • 138
    收藏
    觉得还不错? 一键收藏
  • 17
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值