javaweb实现购物车功能

这篇具有很好参考价值的文章主要介绍了javaweb实现购物车功能。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

(web练手小项目)

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

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

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

功能实现效果:

javaweb实现购物车功能

javaweb实现购物车功能

javaweb实现购物车功能

javaweb实现购物车功能

javaweb实现购物车功能

购物车为空状态 

javaweb实现购物车功能

 功能大致目录结构:
javaweb实现购物车功能

javaweb实现购物车功能

 文章来源地址https://www.toymoban.com/news/detail-420096.html

前端界面代码:

 (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" %>
<html>
<head>
    <title>shop car</title>
    <link rel="stylesheet" href="css/shoplist.css" type="text/css">
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.6.1.min.js"></script>
</head>
<style type="text/css">
    th, td {
        border-bottom: 1px solid green;
    }
    th {
        background-color: #4CAF50;
        color: white;
    }
    table{
        text-align: center;
    }
</style>
<body style="background-color: #ffffe0" background="img/11.webp">
<h1 style="color: white;margin-left: 600px;margin-top: 50px">购物车</h1>
<table border="1px" cellspacing="0" style="border-color: #d7ffff ; margin-top: 5px ; margin-left: 340px">
    <script type="text/javascript">
        function judgeDelete(carGoodsName) {
            if (confirm("是否删除" + carGoodsName)) {
                window.location.href = "${pageContext.request.contextPath}/deleteCarGoods?carGoodsName=" + carGoodsName
            } else {
                alert("取消删除成功")
            }
        }
    </script>

    <c:if test="${empty carGoodsList}">
        <%--<h1 style="margin-left: 580px;margin-top: 170px">购物车为空</h1>--%>
        <div style="margin-left: 500px;margin-top: 56px">
            <img src="img/carnull.jpg" width="300px" height="200px">
        </div>
    </c:if>

    <c:if test="${not empty carGoodsList}">
        <tr>
            <th>商品名称</th>
            <th>商品描述</th>
            <th>价格</th>
            <th>购买数量</th>
            <th>操作</th>
        </tr>
    </c:if>
    <c:if test="${not empty carGoodsList}">

        <c:forEach items="${carGoodsList}" var="CarGoods">
            <tr>
                <td>${CarGoods.carGoodsName}</td>
                <td>${CarGoods.carGoodsDes}</td>
                <td>${CarGoods.carGoodsPrice}</td>
                <td>${CarGoods.buyCount}</td>
                <td>
                    <input id="deleteCarGoods" type="button" style="text-decoration: none"
                           onclick="judgeDelete('${CarGoods.carGoodsName}')" value="删除"/>
                </td>
            </tr>

        </c:forEach>
    </c:if>
</table>

<c:if test="${not empty carGoodsList}">
    <h3 style="margin-left: 340px;color: white">目前您购物车的总价格为:${money}元人民币</h3>
</c:if>

<br>
<br>
<br>
<input class="backshowlist" type="button" value="返回商品显示页"
       onclick="window.location.href='${pageContext.request.contextPath}/showlist'">
</body>
</html>

 

 (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" %>
<!DOCTYPE html>
<head>
    <title>myshop</title>
    <link rel="stylesheet" href="css/shoplist.css" type="text/css">
    <script type="text/javascript" src="js/jquery-3.6.1.min.js"></script>
</head>
<style type="text/css">
    th, td {
        border-bottom: 1px solid green;
    }
    th {
        background-color: #4CAF50;
        color: white;
    }
    table{
        text-align: center;
    }
</style>

<body style="background-color: #ffffe0" background="img/11.webp">
<h2 style="color: skyblue">:)</h2>

<script type="text/javascript">
    $(function () {
        $("#showbtn").click(function () {
            $.ajax({
                type: "GET",
                url: "${pageContext.request.contextPath}/judgecar",
                async: true,
                success: function (j) {
                    if (j == "购物车为空") {
                        alert("购物车为空")
                    } else {
                        window.location.href = "${pageContext.request.contextPath}/shopcar.jsp"
                    }
                }
            })
        })
    })
</script>
<h1 style="color: white;margin-left: 600px">商品页</h1>
<button id="showbtn" class="showcarbtn">查看购物车</button>
<form action="${pageContext.request.contextPath}/beforeCar" method="post" id="form_">
    <table  cellspacing="0" style="  margin-top: 5px ; margin-left: 270px ;border-color: #8bff73">
        <tr>
            <th>序号</th>
            <th>商品名称</th>
            <th>商品描述</th>
            <th>商品价格(元)</th>
            <th>库存数量</th>
            <th>添至购物车</th>
        </tr>

        <c:forEach items="${goodss}" var="goods" varStatus="goodStatus">
            <tr>
                <td>${goodStatus.count}</td>
                <td>${goods.goodsName}</td>
                <td>${goods.goodsDes}</td>
                <td>${goods.goodsPrice}</td>
                <td>${goods.goodsCount}</td>
                <td>
                    <input type="checkbox" name="buy" value="${goods.goodsName}" style="margin-left: 30px">
                </td>
            </tr>
        </c:forEach>
    </table>
    <br>

    <input type="button" value="确定" id="btn" class="ensure">
    &nbsp;&nbsp;&nbsp;&nbsp;
    <input type="reset" value="重置" class="reset">

</form>

<script type="text/javascript">
    $(function () {
        $("#btn").click(function () {
            var flag = false;
            var $checkbox = $(":checkbox");
            /*for (var i = 0; i < $checkbox.length; i++) {
                if($checkbox[i].checked){
                    flag = true;
                }
            }*/
            //使用jQuery循环jQuery对象,其实jQuery对象就是一个dom数组
            /*$checkbox.each(function (i , n) {
                if(n.checked){
                    flag = true
                }
            })*/
            $.each($checkbox,function (i,n) {
                if(n.checked){
                    flag = true;
                }
            })
            if (flag == false) {
                alert("未选择商品")
            } else {
                var $formElement = $("#form_")[0];
                $formElement.submit();
            }
        })
    })
</script>
</body>
</html>

后端servlet代码:

 

欢迎页(WelcomeServlet.java)

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

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

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

<!--配置欢迎页-->
    <welcome-file-list>
        <welcome-file>welcome</welcome-file>
    </welcome-file-list>

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<CarGoods> 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<goods> 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<CarGoods> carGoodsList = (List<CarGoods>) 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<CarGoods> carGoodsList = (List<CarGoods>) 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<CarGoods> carGoodsList = (List<CarGoods>)session.getAttribute("carGoodsList");
        if(carGoodsList.isEmpty()){
            out.print("购物车为空");
        }
    }
}

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

 

 

到了这里,关于javaweb实现购物车功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Vue项目商品购物车前端本地缓存逻辑(适用H5/ipad/PC端)——前端实现购物车删除商品、购物车增减数量,清空购物车功能

    Vue3 + Vite + Ts开源后台管理系统模板 基于ElementUi或AntdUI再次封装基础组件文档 基于Element-plus再次封装基础组件文档(vue3+ts)

    2024年02月12日
    浏览(15)
  • JavaWeb购物车项目

    目录 项目前提 数据库的创建 用户表 商品表 eclipse进行创建包和类: 主要实现功能 1、购物车用户登录 2、商品显示 3、购物车添加商品总数和价格的计算 1、购物车并不是一直放数据库 2、选择使用的技术: session:(购物车项目使用session) 好处:快(放在内存当中),存对象的

    2024年02月05日
    浏览(14)
  • JavaWeb 购物车项目

    今天是基于我们所学的服务器存储端和三层架构来完善该项目,今天先完善一部分的功能。   1.登录 先创建一个用户表,表中有id,name,pwd三个属性首。 需要具备一个登录页面,一个处理登录数据的页面,在该页面进行判断,当该用户存在,我们跳转到商城,用户不存在回到登

    2024年02月07日
    浏览(11)
  • JavaWeb 购物车项目(一)

    今天的学习主要是完成一个购物车项目,该项目中使用servlet完成,对于不知道servlet不知道如何使用的去看 servlet的使用 该篇文章,该文章中有教大家如何使用servlet。 目录 一.项目所需表  二.购物车项目实操  1.登录操作 2.首页操作 购物车数据操作 :CarServlet, 我们在点击首

    2024年02月04日
    浏览(16)
  • 实现蛋糕商城购物车功能代码实现实验报告

    一、实验目的 1、熟悉HttpSession接口中常用方法 2、熟悉Session 对象的生命周期 3、熟悉两种方法返回与当前请求相关的HttpSession对象。 4、学会如何使用Session 技术模拟用户登录的功能 二、实验内容 实现购物车 1、在chapler05 项目下新建一个名称为 cn.itcast.session.entity 的包,在该

    2024年02月09日
    浏览(10)
  • 购物车功能实现(小兔鲜儿)【Vue3】

    购物车业务逻辑梳理拆解 整个购物车的实现分为两个大分支, 本地购物车操作和接口购物车操作 由于购物车数据的特殊性, 采取Pinia管理购物车列表数据并添加持久化缓存 本地购物车 - 加入购物车实现 添加购物车 基础思想:如果已经添加过相同的商品,就在其数量count上加一

    2024年02月15日
    浏览(11)
  • Vue2 实现购物车功能(可直接使用)

    vue2.0实例简单购物车 页面展示效果如下:​ 该购物车实现了自动计算小计、总价。 代码实现 js代码 欢迎大家有问题指出

    2024年02月12日
    浏览(12)
  • JavaWeb购物车项目 思路&拓展&综合提升

    目录  一、实现思路 二、JSP 页面实现(临时性购物车项目)         第一部分:images(图片)         第二部分:SQL代码         第三部分:代码                  实体层(entity):                         1.entity 包 (package com.zking.goods.entity;)   

    2024年02月09日
    浏览(9)
  • 苍穹外卖day07——缓存菜品套餐+购物车功能实现

    用户访问量过大带来的一个直接效果就是响应速度慢,使用体验下降。 使用redis缓存菜品数据,减少数据库查询操作。  页面展示上基本就是同一个分类在同一页,所以key-value结构可以使用不同的分类来做key。 在小程序每一次点击不同的分类,后端哪里都会刷刷刷的连接数据

    2024年02月14日
    浏览(16)
  • JavaWeb(10)——前端综合案例4(购物车示例)

           购物车需要展示一个已加入购物车的商品列表,包含商品名称、商品单价、购买数量和操作 等信息,还需要实时显示购买的总价。其中购买数量可以增加或减少,每类商品还可以从购物车中移除。最终实现的效果大致如图所示。 基础版 plus版              先在

    2024年02月05日
    浏览(13)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包