JavaWeb购物系统(七)购物系统主页,商品的管理

效果图

未登录状态

登陆状态

商品管理页面
JavaWeb购物系统(七)购物系统主页,商品的管理_第1张图片
商品修改模态框
JavaWeb购物系统(七)购物系统主页,商品的管理_第2张图片

功能

  1. 商品展示
  2. 添加商品到购物车
  3. 查看商品
  4. 商品的信息的修改

正文

index.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page import="com.service.GoodsService" %>
<%@ page import="com.entity.Goods" %>
<%@ page import="java.util.List" %>
<%@ page import="com.myUtil.ProcessUtil" %>
<%@ page import="com.myUtil.JdbcUtil" %>
<%--  Created by IntelliJ IDEA.
  User: huawei
  Date: 2022/9/26
  Time: 17:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登陆成功页面</title>
    <%--阿里项目图标引入--%>
    <link rel="stylesheet" href="//at.alicdn.com/t/c/font_3722667_bquibw4d428.css">
    <!--Bootstrap5 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css">
    <%--icon图标--%>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
    <!--  popper.min.js 用于弹窗、提示、下拉菜单 -->
    <script src="https://cdn.staticfile.org/popper.js/2.9.3/umd/popper.min.js"></script>
    <!-- 最新的 Bootstrap5 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="script/jquery-3.6.0.min.js"></script>
    <style>
        .link-secondary:hover{
            color: orange;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            // 添加商品到购物车
            $("a[id^='purchase_']").click(
                function (e) {
                    $.post(
                        "/MyProject/cartProcessServlet",
                        {
                            goodId: e.target.id,
                            method: "addShopCartItem"
                        },
                        function (data) {
                            if ("success" == data){
                                alert("添加购物车成功!");
                                location.reload(true);
                            }
                            // 拦截未登录用户添加购物车
                            if ("error" == data){
                                window.location.href="/MyProject/login.jsp";
                            }
                        },
                        "json"
                    )
                    return false;
            })

            // 时间显示函数
            function getTime() {
                var date = new Date();
                var year = date.getFullYear(); //获取年份
                var month = date.getMonth() + 1; //获取月份
                var day = date.getDate(); //获取日期
                var hour = date.getHours(); //获取小时
                hour = hour < 10 ? '0' + hour : hour;
                var minute = date.getMinutes(); // 获取分
                minute = minute < 10 ? '0' + minute : minute;
                var seconds = date.getSeconds(); //获取秒
                seconds = seconds < 10 ? '0' + seconds : seconds;
                return year + '年' + month + '月' + day + '日&nbsp;' + hour + ':' + minute + ':' + seconds;
            }
            setInterval(function() {
                document.querySelector('#timeBox').innerHTML = getTime();
            }, 1000)


        })
    </script>
</head>
<body>

<%
    SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date(System.currentTimeMillis());
    String format = formatter.format(date);
    GoodsService goodsService = new GoodsService();
    List<Goods> goods = goodsService.showAllGoods();
    JdbcUtil.commit();
    request.setAttribute("goods",goods);
    String userName = ProcessUtil.getUserNameBySessionId(session);
    session.setAttribute("userName",userName);

%>
<div class="container">
    <%--头部导航栏--%>
    <div class="row sticky-top bg-light">
        <header class="d-flex flex-wrap justify-content-center py-3 mb-4 border-bottom ">
            <a href="/MyProject/index.jsp" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-decoration-none">
                <svg class="bi me-2" width="40" height="32"><use xlink:href="#"/></svg>
                <span class="fs-4 bi bi-triangle-half">Simple header</span>
            </a>

            <ul class="nav nav-pills">
                <li class="nav-item"><a href="/MyProject/index.jsp" class="nav-link active bi bi-house" aria-current="page">Home</a></li>
                <li class="nav-item"><a href="/MyProject/order.jsp" class="nav-link iconfont icon-order"> 我的订单</a></li>
                <li class="nav-item position-relative">
                    <a href="/MyProject/shoppingCar.jsp" class="nav-link bi bi-cart"> 购物车</a>
                    <div class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-secondary">
                        ${sessionScope.cart.totalCount}
                    </div>
                </li>
                <li class="nav-item"><a href="/MyProject/comments.jsp" class="nav-link bi bi-chat-square"> 留言板</a></li>
                <c:if test="${sessionScope.user == null}">
                    <li class="nav-item"><a href="/MyProject/login.jsp" class="nav-link">登录</a></li>
                </c:if>
                <c:if test="${sessionScope.user != null}">
                    <div class="btn-group">
                        <button type="button" class="btn btn-primary dropdown-toggle bi bi-gear-fill" data-bs-toggle="dropdown"> 设置</button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/MyProject/userDetailInfo.jsp">修改信息</a></li>
                            <li><a class="dropdown-item" href="/MyProject/goodsManage.jsp">商品管理</a></li>
                            <li><a class="dropdown-item" href="/MyProject/userProcessServlet?method=logout" id="logout">退出登录</a></li>
                        </ul>
                    </div>
                </c:if>
                <li class="nav-item"><a href="#" class="nav-link"></a></li>
            </ul>
         </header>
    </div>
    <div class="row" style="padding-bottom: 30px">
        <div class="row h-50">
            <%--左边分类栏--%>
            <div class="card bg-light text-center m-auto font-monospace" style="max-width: 18rem; height: 388px">
                <div class="card-body">
                    <div class="title">分类</div>
                    <ul class="list-group list-group-flush" style="text-align: left;">
                        <li class="list-group-item iconfont icon-dress " style="border-bottom: none">
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none;"> 女装 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 内衣 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 奢品 </a>
                        </li>
                        <li class="list-group-item iconfont icon-shoes" style="border-bottom: none">
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 女鞋 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 男鞋 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 箱包 </a>
                        </li>
                        <li class="list-group-item iconfont icon-perfume" style="border-bottom: none">
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 美妆 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 饰品 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 洗护 </a>
                        </li>
                        <li class="list-group-item iconfont icon-clothes" style="border-bottom: none">
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 男装 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 运动 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 百货 </a>
                        </li>
                        <li class="list-group-item iconfont icon-phone" style="border-bottom: none">
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 手机 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 数码 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 企业礼品 </a>
                        </li>
                        <li class="list-group-item iconfont icon-SOFTWARE_FURNITURE" style="border-bottom: none">
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 家装 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 电器 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 车品 </a>
                        </li>
                        <li class="list-group-item iconfont icon-cherry" style="border-bottom: none">
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 食品 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 生鲜 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 母婴 </a>
                        </li>
                        <li class="list-group-item iconfont icon-medicinebox" style="border-bottom: none">
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 医药 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 保健 </a>/
                            <a href="#" class="link-secondary font-monospace" style="text-decoration: none"> 进口 </a>
                        </li>
                    </ul>
                </div>
            </div>
            <%--轮播图--%>
            <div id="carouselExampleDark bg-light" class="carousel slide col" data-bs-ride="carousel">
                <div class="carousel-inner">
                    <div class="carousel-item active">
                        <img src="https://img.alicdn.com/imgextra/i4/6000000003872/O1CN01AxHfgt1eTQLmwCFTj_!!6000000003872-2-octopus.png" class="d-block w-100" alt="...">
                    </div>
                    <div class="carousel-item">
                        <img src="https://img.alicdn.com/imgextra/i3/6000000004754/O1CN01G2onsB1kzNg9NfdBH_!!6000000004754-2-octopus.png" class="d-block w-100" alt="...">
                    </div>
                    <div class="carousel-item">
                        <img src="https://img.alicdn.com/imgextra/i3/6000000004754/O1CN01G2onsB1kzNg9NfdBH_!!6000000004754-2-octopus.png" class="d-block w-100" alt="...">
                    </div>
                </div>
            </div>
            <%--右边个人信息栏--%>
            <div class="card text-white text-center " style="width: 18rem;height: 388px">
                <div class="card-body font-monospace">
                    <div class="card-title">个人信息</div>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item">
                            <c:if test="${sessionScope.user == null}">
                                <div class="card-subtitle">
                                    Hi 你好!
                                </div>
                            </c:if>
                            <c:if test="${sessionScope.user != null}">
                                <div class="card-subtitle">
                                Hi ${sessionScope.userName}
                                </div>
                            </c:if>
                        </li>
                        <c:if test="${sessionScope.user == null}">
                            <li class="list-group-item" style="margin-top: 100px">
                                <a href="/MyProject/login.jsp" class="btn btn-primary">请登录</a>
                            </li>
                        </c:if>
                        <c:if test="${sessionScope.user != null}">
                            <li class="list-group-item">
                                    <div class="card-text" style="margin-top: 40px">
                                        <div>
                                            <img style="height: 90px;width: 90px;border-radius: 50%;" src="http://q1.qlogo.cn/g?b=qq&nk=${sessionScope.userName}&s=640" class="img-circle">
                                        </div><span class="badge bg-info text-dark">
                                            ${sessionScope.count}
                                        </span>
                                        次成功登录!</br>
                                        <%
                                            if (session.getAttribute("lastTime") == null){ //首次登陆
                                                session.setAttribute("lastTime",format);
                                            }else {
                                                out.print("第一次登录时间为:" + session.getAttribute("lastTime"));
                                            }
                                        %>
                                    </div>
                            </li>
                        </c:if>
                    </ul>
                </div>
                <%--显示时间--%>
                <div class="card-footer bg-secondary" id="timeBox">
                </div>
            </div>
        </div>
    </div>

    <%--商品栏--%>
    <div class="row row-cols-1 row-cols-md-4 g-4">
        <c:forEach items="${requestScope.goods}" var="good">
                <div class="col px-3 gy-4">
                    <div class="card border-primary">
                        <img src="${good.img}" class="card-img-top" alt="...">
                        <div class="card-body">
                            <h5 class="card-title text-truncate">${good.name}</h5>
                            <p class="card-text text-truncate">${good.describe}</p>
                            <p class="card-text fw-bold text-danger">¥${good.price}</p>
                            <a href="#" class="btn btn-primary" id="purchase_${good.id}">添加到购物车</a>
                        </div>
                    </div>
                </div>
        </c:forEach>
    </div>

    <%--footer--%>
    <div class="row align-items-end">
        <footer class="py-5">
            <div class="row">
                <div class="col-2">
                    <h5>Section</h5>
                    <ul class="nav flex-column">
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
                    </ul>
                </div>

                <div class="col-2">
                    <h5>Section</h5>
                    <ul class="nav flex-column">
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
                    </ul>
                </div>

                <div class="col-2">
                    <h5>Section</h5>
                    <ul class="nav flex-column">
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
                        <li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
                    </ul>
                </div>
            </div>
            <div class="d-flex justify-content-between py-4 my-4 border-top">
                <p>&copy; 2021 Company, Inc. All rights reserved.</p>
                <ul class="list-unstyled d-flex">
                    <li class="ms-3"><a class="link-dark" href="#"><svg class="bi" width="24" height="24"><use xlink:href="#twitter"/></svg></a></li>
                    <li class="ms-3"><a class="link-dark" href="#"><svg class="bi" width="24" height="24"><use xlink:href="#instagram"/></svg></a></li>
                    <li class="ms-3"><a class="link-dark" href="#"><svg class="bi" width="24" height="24"><use xlink:href="#facebook"/></svg></a></li>
                </ul>
            </div>
        </footer>
    </div>
</div>
</body>
</html>

右边个人信息栏-用户显示

登录成功之后,在信息栏顶部显示用户的用户名。并且显示上次的登录时间。
用户名是直接从数据库读取,存储到session域,然后在jsp页面显示。

右边个人信息栏-上次登录时间

上次登录时间的思路是,判断session域中是否有 “lastTime” ,如果没有就证明是第一次登录,就在session 域中设置 lastTime-当前时间 。反之,如果存有第一次登录时间,就直接取出来显示。相关的代码:

<%
if (session.getAttribute("lastTime") == null){ //首次登陆
    session.setAttribute("lastTime",format);
}else {
    out.print("第一次登录时间为:" + session.getAttribute("lastTime"));                                   }
%>

右边信息栏-记录登录次数

我们的登陆次数是在UserProcessServlet处理的。从sesison域中获取 “count” ,如果没有就是第一次登录,就设置值为 1 。有的话就在原有的值上 +1 。
相关的代码:

// 记录登录次数
 protected void recordCount(HttpServletRequest request){
     HttpSession session = request.getSession();
     if (session.getAttribute("count") == null){
         int count = 1;
         session.setAttribute("count",count);
     }else {
         Integer count = (Integer)session.getAttribute("count");
         count++;
         session.setAttribute("count",count);
     }
 }

右边信息栏-头像的获取

看过JavaWeb购物系统(二)购物登陆、注册这一章节的可以知道,我们的用户表并没有存储用户头像,那这里的头像是从哪里来的呢?
我这里用的是QQ的一个头像接口,即:如果用户名是QQ号的话,这里就可以获取到QQ头像。哈哈哈哈
下面是相关代码:

<div>
    <img style="height: 90px;width: 90px;border-radius: 50%;" src="http://q1.qlogo.cn/g?b=qq&nk=${sessionScope.userName}&s=640" class="img-circle">
div>

接口地址是:http://q1.qlogo.cn/gb=qq&nk=自己的QQ号&s=640

右边信息栏-底部当前时间的显示

这里直接用的js代码。

// 时间显示函数
function getTime() {
        var date = new Date();
        var year = date.getFullYear(); //获取年份
        var month = date.getMonth() + 1; //获取月份
        var day = date.getDate(); //获取日期
        var hour = date.getHours(); //获取小时
        hour = hour < 10 ? '0' + hour : hour;
        var minute = date.getMinutes(); // 获取分
        minute = minute < 10 ? '0' + minute : minute;
        var seconds = date.getSeconds(); //获取秒
        seconds = seconds < 10 ? '0' + seconds : seconds;
        return year + '年' + month + '月' + day + '日 ' + hour + ':' + minute + ':' + seconds;
    }
    setInterval(function() {
        document.querySelector('#timeBox').innerHTML = getTime();
    }, 1000)

商品的展示

商品的展示,就是通过GoodService对象来调用相关方法来获取商品集合。最后通过jsp的for_Each来渲染到页面上。相关代码:

 GoodsService goodsService = new GoodsService();
 List<Goods> goods = goodsService.showAllGoods();
 JdbcUtil.commit();
 request.setAttribute("goods",goods);

首页商品添加到购物车

在JavaWeb购物系统(五)购物车模块的实现
这一章节中说过,因为添加商品在主页,所以我们在这一节讲。
相关代码:
添加商品到购物车的前端js代码

  // 添加商品到购物车
$("a[id^='purchase_']").click(
       function (e) {
           $.post(
               "/MyProject/cartProcessServlet",
               {
                   goodId: e.target.id,
                   method: "addShopCartItem"
               },
               function (data) {
                   if ("success" == data){
                       alert("添加购物车成功!");
                       location.reload(true);
                   }
                   // 拦截未登录用户添加购物车
                   if ("error" == data){
                       window.location.href="/MyProject/login.jsp";
                   }
               },
               "json"
           )
           return false;
   })

添加商品到购物车的后端代码

 // 添加购物车
protected void addShopCartItem(HttpServletRequest request,HttpServletResponse response){
    // 得到商品id
    String goodId = request.getParameter("goodId").split("_")[1];
    // 得到商品信息
    Goods good = goodsService.getGoodById(goodId);
    // 将商品信息写入购物项
    ShopCarItem item =
            new ShopCarItem(Integer.parseInt(goodId),good.getImg(),good.getName(),good.getPrice(),1,good.getPrice());
    // 从session中获取购物车
    HttpSession session = request.getSession();
    Cart cart = (Cart)session.getAttribute("cart");
    if (cart == null){ // 还未创建购物车
        cart = new Cart();
        session.setAttribute("cart",cart);
    }
    cart.addShopCartItem(item);
    try {
        response.getWriter().write(new Gson().toJson("success"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  1. 我们通过点击 添加到购物车 按钮来向后端发送Ajax请求,将请求发送到购物车相关的Controller层。
  2. 后端处理请求,,在Controller层首先根据添加的商品创建购物项。之后我们会将购物项加入购物车。
  3. 但我们并不会直接创建Cart对象,因为我们不知道是否存在购物车对象。
  4. 所以我们需要先从session域中获取购物车对象Cart,如果没有,即:获取到的值为NULL,就说明没有购物车,这时我们会创建一个购物车对象Cart
  5. 然后将我们的购物项添加到购物车中去。
  6. 后端根据处理结果,返回json字符串,用于前端的后续处理。
  7. 如果前端收到后端添加成功的信息,就显示添加购物车成功

回显提示效果图

购物车右上角显示商品数量

我们是通过获取session域中的Cart购物车对象,手机用EL表达式获取到购物车中商品的总数量。最后显示在jsp页面。
JavaWeb购物系统(七)购物系统主页,商品的管理_第3张图片

相关代码:

<li class="nav-item position-relative">
	<a href="/MyProject/shoppingCar.jsp" class="nav-link bi bi-cart"> 购物车a>
	<div class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-secondary">
		${sessionScope.cart.totalCount}
	div>
li>

因为我们需要的是实时的商品数量,所以我们在上边添加商品成功之后,Ajax回调函数中刷新了页面

goodsManage.jsp(商品管理页面)

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page import="com.service.GoodsService" %>
<%@ page import="com.entity.Goods" %>
<%@ page import="java.util.List" %>
<%@ page import="com.myUtil.JdbcUtil" %><%--
  Created by IntelliJ IDEA.
  User: huawei
  Date: 2022/10/29
  Time: 20:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>商品管理</title>
    <!--Bootstrap5 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css">
    <%--icon图标--%>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
    <!--  popper.min.js 用于弹窗、提示、下拉菜单 -->
    <script src="https://cdn.staticfile.org/popper.js/2.9.3/umd/popper.min.js"></script>
    <!-- 最新的 Bootstrap5 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="script/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(function () {
            // 删除商品
            $("button[id^='delete_']").click(
                function (e) {
                    var del = confirm("确认删除");
                    if (del){ // 删除
                        $.post(
                            "/MyProject/goodsProcessServlet",
                            {
                                method: "deleteGoods",
                                goodId: e.target.id
                            },
                            function (data) {
                                alert(data);
                                location.reload(true);
                            },
                            "json"
                        )
                    }else { // 取消
                        return false;
                    }
                }
            )

            // 修改商品
            $("button[id^='update_']").click(
                function (e) {
                    // 获取修改列表信息
                    var name = $("#name").val();
                    var inventory = $("#inventory").val();
                    var price = $("#price").val();
                    var describe = $("#describe").val();
                    if (name.trim()=="" ||
                    inventory.trim()=="" ||
                    price.trim()==""||
                    describe.trim()==""){
                        alert("内容不能为空")
                        return false;
                    }
                    var upd = confirm("确认修改");
                    if (upd==true){ // 修改
                        $.post(
                            "/MyProject/goodsProcessServlet",
                            {
                                method: "updateGoods",
                                goodId: e.target.id,
                                name: name,
                                inventory: inventory,
                                price: price,
                                describe: describe
                            },
                            function (data) {
                                alert(data);
                                location.reload(true);
                            },
                            "json"
                        )
                    }else { // 取消
                        return false;
                    }
                }
            )
        })
    </script>
</head>
<body>
<%
    int pageNum = 1;
    GoodsService goodsService = new GoodsService();
    List<Goods> goods = goodsService.showAllGoods();
    JdbcUtil.commit();
    if (goods!=null){
        session.setAttribute("AllGoods",goods);
    }
    // 当前页码
    String page1 = request.getParameter("goods_page");
    if (page1!=null){
        pageNum = Integer.parseInt(page1);
    }
    List<Goods> pagesGoods = goodsService.showPagesGoods(pageNum);
    JdbcUtil.commit();
    // 当前页码所对应的商品
    request.setAttribute("pagesGoods",pagesGoods);
%>
<%--头部导航栏--%>
<nav class="navbar-expand-lg navbar navbar-dark bg-primary">
    <div class="container-fluid ">
        <a class="navbar-brand" href="#">商品管理</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavDropdown">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link active" aria-current="page" href="/MyProject/index.jsp">Home</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div class="container">
    <div class="card">
        <c:if test="${!empty sessionScope.AllGoods}">
            <table class="table table-striped">
                <tr>
                    <td>商品名称</td>
                    <td>库存</td>
                    <td>价格</td>
                    <td>简介</td>
                    <td>删除</td>
                    <td>修改</td>
                </tr>
                <c:forEach items="${requestScope.pagesGoods}" var="goods">
                    <tr>
                        <td style="width: 20%">${goods.name}</td>
                        <td style="width: 20%">${goods.inventory}</td>
                        <td style="width: 20%">${goods.price}</td>
                        <td style="width: 20%">
                            <div class="col-1 text-truncate m-auto" style="width:200px" >
                                    ${goods.describe}
                            </div>
                        </td>
                        <td style="width: 10%">
                            <button type="submit" class="btn btn-danger" id="delete_${goods.id}">删除</button></td>
                        <td style="width: 10%">
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#model_${goods.id}">
                                修改
                            </button>
                        </td>
                    </tr>
                    <%--修改模态框窗体部分--%>
                    <div class="modal" id="model_${goods.id}">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content">
                                <!-- 模态框头部 -->
                                <div class="modal-header">
                                    <h4 class="modal-title">${goods.name}</h4>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>

                                <!-- 模态框内容 -->
                                <div class="modal-body">
                                    <form>
                                        <div class="mb-3">
                                            <label for="name" class="col-form-label">商品名称:</label>
                                            <input type="text" class="form-control" id="name" value="${goods.name}">
                                        </div>
                                        <div class="mb-3">
                                            <label for="inventory" class="col-form-label">商品库存:</label>
                                            <input type="text" class="form-control" id="inventory" value="${goods.inventory}">
                                        </div>
                                        <div class="mb-3">
                                            <label for="price" class="col-form-label">商品价格:</label>
                                            <input type="text" class="form-control" id="price" value="${goods.price}">
                                        </div>
                                        <div class="mb-3">
                                            <label for="describe" class="col-form-label">商品描述</label>
                                            <textarea class="form-control overflow-hidden" id="describe" >${goods.describe}</textarea>
                                        </div>
                                    </form>
                                </div>

                                <!-- 模态框底部 -->
                                <div class="modal-footer">
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                                        <button type="button" class="btn btn-primary" id="update_${goods.id}">提交</button>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </c:forEach>
                <c:set scope="request" var="goodPage_count" value="${fn:length(sessionScope.AllGoods)}"/>
            </table>
            <nav aria-label="...">
                <ul class="pagination justify-content-center" style="margin:20px 0">
                    <%--获得商品总数--%>
                    <%-- 向上取整--%>
                    <c:forEach begin="1" end="${(goodPage_count + 5-1)/5}" var="i">
                        <li class="page-item"><a class="page-link" href="/MyProject/goodsProcessServlet?method=showPagesGoods&goods_page=${i}">${i}</a></li>
                    </c:forEach>
                </ul>
            </nav>
        </c:if>
    </div>
</div>
</body>
</html>

商品的展示

思路和留言板的留言展示都差不多,使用相应的方法取出商品列表,放入session域,最后使用for-Each将列表数据渲染到jsp页面。

商品的删除

通过Ajax请求,携带商品的唯一ID,删除数据库中的商品数据。

商品修改

点击修改按钮,模态框中的内容,是通过渲染jsp商品展示页面的时候,同时将相应的商品信息添加到模态框的。

商品分页

兄弟们,可以参考留言的分页

商品这一部分的很多逻辑都是和留言板部分很多都是一样的。
JavaWeb购物系统(四)留言板的实现.

GoodsProcessServlet

package com.controller;

import com.entity.Goods;
import com.google.gson.Gson;
import com.myUtil.JdbcUtil;
import com.service.GoodsService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;

public class GoodsProcessServlet extends BasicServlet {
    private GoodsService goodsService = new GoodsService();
    // 删除商品
    protected void deleteGoods(HttpServletRequest request, HttpServletResponse response){
        String goodId = request.getParameter("goodId").split("_")[1];
        Gson gson = new Gson();
        response.setContentType("text/html;charset=utf-8");
        if (goodId!=null){
            try {
                PrintWriter writer = response.getWriter();
                goodsService.deleteGoods(goodId);
                JdbcUtil.commit();
                writer.write(gson.toJson("删除商品成功"));
            } catch (Exception e) {
                JdbcUtil.rollback();
                try {
                    response.getWriter().write(gson.toJson("删除商品失败"));
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                e.printStackTrace();
            }
        }

    }
    // 修改商品
    protected void updateGoods(HttpServletRequest request, HttpServletResponse response){
        String goodId = request.getParameter("goodId").split("_")[1];
        String name = request.getParameter("name");
        String inventory = request.getParameter("inventory");
        String price = request.getParameter("price");
        String describe = request.getParameter("describe");
        Goods goods = new Goods(Integer.parseInt(goodId), null, name, describe, new BigDecimal(Integer.parseInt(price)), Integer.parseInt(inventory));
        Gson gson = new Gson();
        response.setContentType("text/html;charset=utf-8");
        try {
            goodsService.updateGood(goods);
            JdbcUtil.commit();
            PrintWriter writer = response.getWriter();
            writer.write(gson.toJson("修改成功"));
        } catch (Exception e) {
            JdbcUtil.rollback();
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.write(gson.toJson("修改失败"));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
        }
    }
    // 分页显示商品
    protected void showPagesGoods(HttpServletRequest request, HttpServletResponse response){
        String page = request.getParameter("goods_page");
        if (page!=null){
            int parseInt = Integer.parseInt(page);
            List<Goods> goods = null;
            try {
                goods = goodsService.showPagesGoods(parseInt);
                JdbcUtil.commit();
            } catch (Exception e) {
                JdbcUtil.rollback();
                e.printStackTrace();
            }
            request.setAttribute("pagesGoods",goods);
            try {
                request.getRequestDispatcher("/goodsManage.jsp").forward(request,response);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

GoodsService

package com.service;
import com.dao.GoodsDao;
import com.entity.Goods;

import java.util.List;

public class GoodsService {
    private GoodsDao goodsDao = new GoodsDao();

    // 显示所有商品
    public List<Goods> showAllGoods() {
        return goodsDao.showAllData();
    }

    // 分页显示商品
    public List<Goods> showPagesGoods(int page){
        List<Goods> goods = goodsDao.showAllData();
        if (goods!=null){
            // 超过页数,回显第一个数据
            if (page > (Math.ceil(goods.size()/5.0))){
                page = 1;
            }
            if (goods!=null && goods.size()!=0){
                int start = (page-1) * 5;
                int end = (page-1) * 5 + 5;
                if(start<goods.size()){
                    if ((goods.size()-start) < 5){
                        goods = goods.subList(start,goods.size());
                    }else {
                        goods = goods.subList(start,end);
                    }
                }
                return goods;
            }
        }
        return null;
    }

    // 根据商品Id来查询商品
    public Goods getGoodById(String goodId) {
        return goodsDao.showDataById(goodId);
    }

    // 添加商品
    public Boolean addGoods(Goods goods) {
        return goodsDao.addData(goods);
    }

    // 删除商品
    public Boolean deleteGoods(String goodId){
        return goodsDao.deleteData(goodId);
    }

    // 更新商品
    public Boolean updateGood(Goods goods){
        return goodsDao.updateData(goods);
    }
}

GoodsDao

package com.dao;

import com.entity.Goods;

import java.util.List;

public class GoodsDao extends BasicDao<Goods>{
    // 查询所有数据
    public List<Goods> showAllData(){
        String sql = "SELECT * FROM `goods`";
        return queryMulti(sql, Goods.class);
    }
    // 根据id查询数据
    public Goods showDataById(String goodId){
        String sql = "SELECT * FROM `goods` WHERE `id`=" + goodId;
        return querySingle(sql, Goods.class);
    }
    // 更新库存
    public Boolean updateStock(Goods goods){
        String sql = "UPDATE `goods` SET `inventory`= "+ goods.getInventory() +" WHERE `id`=" + goods.getId();
        return dmlData(sql);
    }

    // 更新整条数据
    public Boolean updateData(Goods goods){
        String sql = "UPDATE `goods` SET `name`= '"+ goods.getName() +"',`describe`='"+ goods.getDescribe() +"',`price`="+ goods.getPrice() +",`inventory`="+ goods.getInventory() +" WHERE `id`=" + goods.getId();
        return dmlData(sql);
    }

    // 添加数据
    public Boolean addData(Goods goods){
        String sql = "INSERT INTO `goods` VALUES(NULL,'"+ goods.getImg() +"','"+ goods.getName() +"','"+ goods.getDescribe() +"',"+ goods.getPrice() +","+ goods.getInventory() +")";
        return dmlData(sql);
    }

    // 删除数据
    public Boolean deleteData(String goodId){
        String sql = "DELETE FROM `goods` WHERE `id`=" + goodId;
        return dmlData(sql);
    }

}

Goods(商品实体类)

package com.entity;

import java.math.BigDecimal;

public class Goods {
    private Integer id;
    private String img;
    private String name;
    private String describe;
    private BigDecimal price;
    private Integer inventory;
    public Goods() {
    }

    @Override
    public String toString() {
        return "Goods{" +
                "id=" + id +
                ", img='" + img + '\'' +
                ", name='" + name + '\'' +
                ", describe='" + describe + '\'' +
                ", price=" + price +
                ", inventory=" + inventory +
                '}';
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public Goods(Integer id, String img, String name, String describe, BigDecimal price, Integer inventory) {
        this.id = id;
        this.img = img;
        this.name = name;
        this.describe = describe;
        this.price = price;
        this.inventory = inventory;
    }

    public String getDescribe() {
        return describe;
    }

    public void setDescribe(String describe) {
        this.describe = describe;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getPrice() {
        return price;
    }

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

    public Integer getInventory() {
        return inventory;
    }

    public void setInventory(Integer inventory) {
        this.inventory = inventory;
    }

}

Goods表的设计

列名 数据类型 长度 主键? 非空? 自增? 解释说明
id int 商品的自增ID,唯一标识每个商品
img varchar 500 商品图片
name varchar 500 商品名称
describe varchar 500 商品描述
price decimal 10,0 商品价格
inventory int 32 商品库存

你可能感兴趣的:(JavaWeb购物系统,服务器,前端,servlet)