javaweb实现购物车功能
作者:mmseoamin日期:2023-12-05

本篇文章讲的是如何使用javaweb相关知识模拟购物车功能

(web练手小项目)

使用到的相关知识(部分知识点在文章中简单涉及到):

       html  cs  javascript  jsp  servlet   ajax  jQuery  Mysql  MyBatis(持久层框架,用来连接数据库,这里可以使用jdbc进行数据库的连接)  功能使用MVC设计模式,以及三层架构思想

注: 本篇使用Session对购物车进行存储,具体参考下文WelcomeServlet.java

功能实现效果:

javaweb实现购物车功能,6fa64acb07db475a83fa7976e87c7527.png,第1张

javaweb实现购物车功能,5b166471e3a040da89a271db28a1af3f.png,第2张

javaweb实现购物车功能,044cb41da4ad4b4aa0b1dee10b6aa778.png,第3张

javaweb实现购物车功能,5e0d1203d22744939a4229b7fd4d55c1.png,第4张

javaweb实现购物车功能,49277781ce544930bb5600f26594b7ac.png,第5张

购物车为空状态 

javaweb实现购物车功能,6629d9457ce4476b9dc42fb3d912b696.png,第6张

 功能大致目录结构:
javaweb实现购物车功能,863ced0c16cb4953a79157a993bfc207.png,第7张

javaweb实现购物车功能,06acba73a1d042358926f78a1fa1ffb3.png,第8张

 

前端界面代码:

 (1) shopcar.jsp(购物车界面)

<%@ page import="edu.pdsu.shop.pojo.CarGoods" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    shop car
    
    



购物车

<%--

购物车为空

--%> javaweb实现购物车功能,第9张
商品名称 商品描述 价格 购买数量 操作
${CarGoods.carGoodsName} ${CarGoods.carGoodsDes} ${CarGoods.carGoodsPrice} ${CarGoods.buyCount}

目前您购物车的总价格为:${money}元人民币




 

 (2) shoplist.jsp(商品页)

<%@ page contentType="text/html;charset=utf-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    myshop
    
    



:)

商品页

序号 商品名称 商品描述 商品价格(元) 库存数量 添至购物车
${goodStatus.count} ${goods.goodsName} ${goods.goodsDes} ${goods.goodsPrice} ${goods.goodsCount}

    

后端servlet代码:

 

欢迎页(WelcomeServlet.java)

欢迎页介绍:当把购物车初始化在ShopServlet.java或者其他servlet中刷新浏览器页面session中的购物车状态会出现异常,因此我的想法是在欢迎页中创建购物车对象并存储到Session中

写此欢迎页代码前需要在web.xml配置文件中配置一下代码

 配置后会默认以/welcome为项目默认路径进行访问(需要注意这里不需要 /)


    
        welcome
    

WelcomeServlet.java 

 

package edu.pdsu.shop.servlet;
import edu.pdsu.shop.pojo.CarGoods;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
/**
 * 使用Session mybatis jsp servlet EL JSTL  AJAX JQuery模拟购物车功能的实现
 * 欢迎页(欢迎页中创建购物车对象存储到session中)
 */
@WebServlet("/welcome")
public class WelComeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //将购物车写到这里是为了防止进入到shoplist中用户刷新,购物车置空的情况
        //当下面的这段构建购物车的代码写到showlist->对应的servlet中,如果刷新页面,那么showlist->servlet会在次执行,重新创建List集合,购物车会置空
        List carGoodsList = new ArrayList<>();
        //将购物车所有的实体商品存入Session中,
        HttpSession session = request.getSession();
        session.setAttribute("carGoodsList",carGoodsList);
        //重定向
        response.sendRedirect(request.getContextPath() + "/showlist");
    }
}

ShopServlet.java(负责获取所有商品的数据并传到前端进行数据展示)

package edu.pdsu.shop.servlet;
import edu.pdsu.shop.pojo.CarGoods;
import edu.pdsu.shop.pojo.goods;
import edu.pdsu.shop.service.ShopService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
 * 展示商品页servlet
 */
@WebServlet("/showlist")
public class ShopServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //创建service对象
        ShopService service = new ShopService();
        //调用服务
        List goodss = service.showShopListService();
        //转发
        request.setAttribute("goodss",goodss);
        request.getRequestDispatcher("/shoplist.jsp").forward(request,response);
    }
}

BeforeCarServlet.java(在跳转到购物车界面前需要进行的操作 , 同时将数据传入前端进行展示)

package edu.pdsu.shop.servlet;
import edu.pdsu.shop.exception.UpdateErrorException;
import edu.pdsu.shop.pojo.CarGoods;
import edu.pdsu.shop.pojo.goods;
import edu.pdsu.shop.service.ShopService;
import edu.pdsu.shop.util.SqlSessionUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.session.SqlSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * 在展示购物车(shopcar.jsp)之前需要进行判断
 *      如果购物车中包含某类商品,则此类商品购买数量加一
 *      否则购物车中新增此商品的记录
 */
@WebServlet("/beforeCar")
public class BeforeCarServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //创建service方法
        ShopService service = new ShopService();
        //拿到前端传来的数据
        String[] buys = request.getParameterValues("buy");
        //获取购物车信息
        HttpSession session = request.getSession();
        List carGoodsList = (List) session.getAttribute("carGoodsList");
        if (buys != null ) {
            boolean flag = false;
            for (String buy : buys) {
                if (carGoodsList.isEmpty()) {
                    goods goods = service.selectByGoodsNameService(buy);
                    CarGoods carGoods2 = new CarGoods();
                    carGoods2.setCarGoodsName(goods.getGoodsName());
                    carGoods2.setCarGoodsDes(goods.getGoodsDes());
                    carGoods2.setBuyCount(1);
                    try {
                        //更新商品库存服务
                        service.updateGoodsCountservice(buy);
                        //设置购物车中商品的价格
                        carGoods2.setCarGoodsPrice(goods.getGoodsPrice());
                        carGoodsList.add(carGoods2);
                    } catch (UpdateErrorException e) {
                        out.print(e.getMessage());
                    }
                } else {
                    for (int i = 0; i < carGoodsList.size(); i++) {
                        if (carGoodsList.get(i).getCarGoodsName().equals(buy)) {
                            //购物车中有用户想要购买的商品,将购物车中的商品数量加1
                            carGoodsList.get(i).setBuyCount(carGoodsList.get(i).getBuyCount() + 1);
                            //更新商品的库存
                            try {
                                service.updateGoodsCountservice(buy);
                            } catch (UpdateErrorException e) {
                                e.printStackTrace();
                            }
                            flag = true;
                        }
                    }
                    if (flag == false) {
                        //购物车中没有此商品,将购物车中加入此商品
                        goods goods = service.selectByGoodsNameService(buy);
                        CarGoods carGoods = new CarGoods();
                        carGoods.setCarGoodsName(goods.getGoodsName());
                        carGoods.setCarGoodsDes(goods.getGoodsDes());
                        carGoods.setBuyCount(1);
                        try {
                            //更新数据库中的数据信息
                            service.updateGoodsCountservice(buy);
                            carGoods.setCarGoodsPrice(goods.getGoodsPrice());
                            carGoodsList.add(carGoods);
                        } catch (UpdateErrorException e) {
                            e.printStackTrace();
                        }
                    }
                    //重新设置flag的值为false
                    flag = false;
                }
            }
            //更新购物车的信息
            double money = 0;
            for (int i = 0; i < carGoodsList.size(); i++) {
                double carGoodsPrice = carGoodsList.get(i).getCarGoodsPrice();
                int buyCount = carGoodsList.get(i).getBuyCount();
                money += carGoodsPrice * buyCount;
            }
            HttpSession session1 = request.getSession();
            session1.setAttribute("money", money);
            request.setAttribute("carGoodsList", carGoodsList);
            //转发到购物车界面
            request.getRequestDispatcher("/shopcar.jsp").forward(request, response);
        } else {
            //更新购物车的信息
            request.setAttribute("carGoodsList", carGoodsList);
            //转发到购物车界面
            request.getRequestDispatcher("/shopcar.jsp").forward(request, response);
        }
    }
}

CarServlet.java(购物车删除功能实现)

package edu.pdsu.shop.servlet;
import edu.pdsu.shop.exception.UpdateErrorException;
import edu.pdsu.shop.pojo.CarGoods;
import edu.pdsu.shop.pojo.goods;
import edu.pdsu.shop.service.ShopService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
/**
 * 购物车小程序
 *      购物车删除功能的实现
 */
@WebServlet("/deleteCarGoods")
public class CarServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ShopService service = new ShopService();
        //获取前端传来的参数
        String carGoodsName = request.getParameter("carGoodsName");
        //获取session存储域中的购物车List
        HttpSession session = request.getSession();
        List carGoodsList = (List) session.getAttribute("carGoodsList");
        //遍历CarGoods集合
        Iterator it = carGoodsList.iterator();
        while(it.hasNext()){
            CarGoods carGoods = (CarGoods) it.next();
            if(carGoods.getCarGoodsName().equals(carGoodsName)){
                //在集合中找到要删除的商品,删除商品
                it.remove();
                //删除后还需要更新数据库中的商品库存数量
                int buyCount = carGoods.getBuyCount();
                goods good = service.selectByGoodsNameService(carGoodsName);
                good.setGoodsCount(good.getGoodsCount() + buyCount);
                try {
                    service.AddGoodsCountService(good);
                } catch (UpdateErrorException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
        //更新购物车的信息
        //删除购物车中的商品的时候,商品的总价格是需要改变的
        double money = 0;
        for (int i = 0; i < carGoodsList.size(); i++) {
            double carGoodsPrice = carGoodsList.get(i).getCarGoodsPrice();
            int buyCount = carGoodsList.get(i).getBuyCount();
            money += carGoodsPrice * buyCount;
        }
        request.setAttribute("money",money);
        request.getRequestDispatcher("/shopcar.jsp").forward(request,response);
    }
}

JudgeCarServlet.java(此处主要用于AJAX异步请求判断购物车状态,具体实现可以参考shoplist.jsp)

package edu.pdsu.shop.servlet;
import edu.pdsu.shop.pojo.CarGoods;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
 * 使用Ajax请求判断购物车是否为空
 *      如果为空想前端响应为空的信息(“购物车为空”)
 */
@WebServlet("/judgecar")
public class JudgeCarServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        List carGoodsList = (List)session.getAttribute("carGoodsList");
        if(carGoodsList.isEmpty()){
            out.print("购物车为空");
        }
    }
}

以上大致为项目主要的内容,感谢阅读,希望能帮到大家