本篇文章讲的是如何使用javaweb相关知识模拟购物车功能
(web练手小项目)
使用到的相关知识(部分知识点在文章中简单涉及到):
html cs javascript jsp servlet ajax jQuery Mysql MyBatis(持久层框架,用来连接数据库,这里可以使用jdbc进行数据库的连接) 功能使用MVC设计模式,以及三层架构思想
注: 本篇使用Session对购物车进行存储,具体参考下文WelcomeServlet.java
功能实现效果:
购物车为空状态
功能大致目录结构:
前端界面代码:
(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"> <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("购物车为空"); } }}
以上大致为项目主要的内容,感谢阅读,希望能帮到大家