本篇文章讲的是如何使用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">&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 {@Overrideprotected 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 {@Overrideprotected 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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request,response);}@Overrideprotected 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)) {//购物车中有用户想要购买的商品,将购物车中的商品数量加1carGoodsList.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的值为falseflag = 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 {@Overrideprotected 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存储域中的购物车ListHttpSession 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 {@Overrideprotected 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实现购物车功能相关推荐

  1. javaweb mysql购物车_java web开发之实现购物车功能

    为了方便自己以后复习,所以写的比较仔细,记录下自己的成长. 既然是做购物车,那么前提条件是首先需要一系列商品,也就是要建一个实体,这里建了一个商品表. 通过查询在浏览器上显示 基本显示已经做好了,现在 ...

  2. 微信小程序之购物车功能

    前言 以往的购物车,基本都是通过大量的 DOM 操作来实现.微信小程序其实跟 vue.js 的用法非常像,接下来就看看小程序可以怎样实现购物车功能. 需求 先来弄清楚购物车的需求. 单选.全选和取消, ...

  3. php商城的购物车功能,PHP实现添加购物车功能

    关于php实现添加购物车功能,具体代码如下所示: 无标题文档 商品列表 水果代号 水果名称 水果价格 水果产地 水果库存 操作 session_start(); include("../fe ...

  4. 小程序判断数组的index是否为空_微信小程序之购物车功能(仅学习)

    购物车,基本都是通过大量的 DOM 操作来实现.微信小程序其实跟 vue.js 的用法非常像,接下来就看看小程序可以怎样实现购物车功能. 需求 先来弄清楚购物车的需求. 单选.全选和取消,而且会随着选 ...

  5. 用python做一个购物车编程_利用python实现简单的循环购物车功能示例代码

    本文主要给大家介绍了关于python实现循环购物车功能的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍: 示例代码 # -*- coding: utf-8 -*- __author__ = ...

  6. vue实战记录(二)- vue实现购物车功能之创建vue实例

    vue实战,一步步实现vue购物车功能的过程记录,课程与素材来自慕课网,自己搭建了express本地服务器来请求数据 作者:狐狸家的鱼 本文链接:vue实战-实现购物车功能(二) GitHub:sue ...

  7. python制作购物网站_Python实现的购物车功能示例

    本文实例讲述了Python实现的购物车功能.分享给大家供大家参考,具体如下: 这里尝试用python实现简单的购物车程序... 基本要求: 用户输入工资,然后打印购物菜单 用户可以不断的购买商品,直到 ...

  8. php实现商品购物车添加功能,PHP实现添加购物车功能

    关于php实现添加购物车功能,具体代码如下所示: 无标题文档 商品列表 水果代号 水果名称 水果价格 水果产地 水果库存 操作 session_start(); include("../fe ...

  9. java代码实现购物车小程序_使用Taro实现小程序商城的购物车功能模块的实例代码...

    Taro 是一套遵循 React 语法规范的 多端开发 解决方案. 现如今市面上端的形态多种多样,Web.React-Native.微信小程序等各种端大行其道,当业务要求同时在不同的端都要求有所表现的 ...

最新文章

  1. UA MATH564 概率论 依概率收敛的一个例题
  2. 2021-10-11 二叉树中查找值为key的结点
  3. 将有序数组转为二叉搜索树
  4. 前端工程师必须要知道的SEO技巧(2):制作比设计还要漂亮的代码(内容和语义化代码)上...
  5. 响应式API的设计、实现和应用
  6. Hyperledger Fabric、Corda和以太坊对比
  7. mybatis问题。foreach循环遍历数组报错情况,及其解决方法
  8. 对shell的简单认识
  9. turtle库绘图:绘制QQ所有表情
  10. 色彩设计原理(里面有配色方案,也有配色网站)
  11. 填坑---override、overload、overwrite
  12. C++中的setw()函数
  13. Intent跳转地图应用(百度地图、高德地图)
  14. 【实操】python opencv将图片合成视频,并插入音频
  15. 【Python】Pandas Excel file format cannot be determined, you must specify an engine manually.报错【已解决】
  16. UBER司机奖励政策
  17. JavaScript深入浅出第2课:函数是一等公民是什么意思呢?
  18. Mac Dropbox 点击“首选项”无反应 没反应怎么办?
  19. web3创业合伙人招募!!!
  20. 医院信息系统网络安全等级保护2.0标准解读

热门文章

  1. 第三方API接口对接-电子合同的实现逻辑
  2. 【Data Analysis 01】Airbnb_new_user_booking_DataExploration(爱彼迎新用户订房数据探索)
  3. Linux查看实时网速的Shell
  4. 微信怎么屏蔽他人的朋友圈?图文教学,1分钟学会
  5. 考研数学 之 汤家凤老师来校讲座摘记 (拉格朗日定理等干货 )
  6. U转串口时,鼠标乱动,解决办法
  7. java删除修改的代码怎么写_Java代码增删查改完整流程
  8. 微信小程序之PHP后端服务器数据库的连接处理
  9. java图片改变分辨率并保存
  10. 缓动动画_核心动画概念:缓入缓出