javaweb实现购物车功能

article/2025/10/17 18:23:58

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

(web练手小项目)

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

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

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

功能实现效果:

6fa64acb07db475a83fa7976e87c7527.png

5b166471e3a040da89a271db28a1af3f.png

044cb41da4ad4b4aa0b1dee10b6aa778.png

5e0d1203d22744939a4229b7fd4d55c1.png

49277781ce544930bb5600f26594b7ac.png

购物车为空状态 

6629d9457ce4476b9dc42fb3d912b696.png

 功能大致目录结构:
863ced0c16cb4953a79157a993bfc207.png

06acba73a1d042358926f78a1fa1ffb3.png

 

前端界面代码:

 (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("购物车为空");}}
}

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

 

 


http://chatgpt.dhexx.cn/article/GGn4uNFy.shtml

相关文章

js实现简单的购物车 有图有代码

用JavaScript实现静态购物车功能 要求&#xff1a; 点击号数量增加&#xff0c;点击-号数量递减&#xff1b; 实现全选、反选和删除功能&#xff1b; 求出小计、总数量和总价&#xff1b; 看效果图 CSS样式 <style>table{width: 900px;border-collapse: collapse;ma…

Servlet+jsp实现简单购物车

功能&#xff1a;BuyBook.jsp上输入所购书名&#xff0c;然后在下面就显示输入的书名&#xff0c;书名后有删除的链接&#xff0c;点删除就从购物车中删除。不涉及数据库。 文件&#xff1a;BuyBook.jsp 、BuyServlet.java ,Servletjsp是我的站点名&#xff0c;架构如下 (在My…

javaweb简单实现购物车的功能

功能简述 本例采用jspservletmysqljdbcc3p0ajax简单实现一个购物车的功能。 项目结构 service那层可以忽略&#xff0c;就不实现登录的功能了&#xff0c;还得加过滤器&#xff0c;主要就实现购物车就行了 JQ jar包 链接&#xff1a;https://pan.baidu.com/s/1KN8EvSlraH_…

jsp购物车简单实现思想(一)

目录 学习目标&#xff1a; 1.通过超链接a传参将所点击购买的商品id传到处理页面doShopCart.jsp进行处理 2.接收超链接a所传productid并进行处理 3.接收处理后的存储多个id的ArrayList aList购物车列表&#xff0c;通过ProItemDaoImp类的getProItemByIds(aList)方法从数据库…

servlet+jsp实现小小购物车功能

这个小小购物车功能是接上个实现浏览记录保存功能的,首先是建立连接池,然后就创建一个购物车实体类,购物车实体类需要有items商品与商品的数量,成员变量如下 //购物车商品的集合private HashMap<Items, Integer> goods; //购物车的总金额private double totalPrice; 然后…

Servlet/Jsp实现购物车

(1)用servlet实现简单的购物车系统&#xff0c;项目结构如下&#xff1a;&#xff08;新建web Project项目 只需要AddItemServlet &#xff0c; ListItemServlet&#xff0c;exam403.jsp三个文件即可&#xff0c;其他的不用管&#xff09; &#xff08;2&#xff09;exam403.j…

jsp实现简单购物车页面

壹 我们今天所设计的购物车页面所实现的功能是点击商品所对应的购买按钮即可在另一页面显示所购买的商品。 贰 &#xff08;1&#xff09;我们想象一下购物的整个过程&#xff0c;当我们进入超市后&#xff0c;会首先拿一个购物推车或者购物篮&#xff0c; &#xff08;2&#…

jsp设计简单的购物车应用案例

代码解释 <%request.setCharacterEncoding("UTF-8");if (request.getParameter("c1")!null)session.setAttribute("s1",request.getParameter("c1"));if (request.getParameter("c2")!null)session.setAttribute("…

jsp实现简易购物车

实现要求: &#xff08;a&#xff09;输入要购买的商品 &#xff08;b&#xff09;点击提交按钮后 &#xff08;c&#xff09;结账页面将所选择的商品全部列出 代码实现: b9_shopping.jsp <% page language"java" contentType"text/html; charsetUTF-8…

JSP-购物类网站(购物车功能,翻页功能,文件下载功能,文末有代码及数据库备份)

目录 网站功能框架 网站架构图 网站项目树 网站首页 注册登录页面 用户个人中心页面 商家个人中心页面 搜索结果页面 商品详细信息页面 手机端页面(部署后) 之前在校内参加过网站设计大赛&#xff0c;贡献全部代码&#xff0c;供jsp小白学习。 这是一个购物类网站,后…

基于Java、Jsp实现购物车的功能

先看效果图&#xff1a; 实现代码&#xff1a; index.jsp <% page language"java" contentType"text/html; charsetUTF-8" pageEncoding"UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset"UTF-8&qu…

JSP——购物车

JSP—购物车 主页面&#xff08;buy.jsp&#xff09; <% page language"java" contentType"text/html; charsetUTF-8"pageEncoding"UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset"UTF-8"> &l…

HTML代码实现简易购物车

网上关于购物车实现的代码非常多&#xff0c;本次的这篇文章主要是和大家分享了HTML代码实现简易购物车&#xff0c;有需要的小伙伴可以看一下&#xff0c;接下来讲解一下具体的实现。 1、用html实现内容&#xff1b; 2、用css修饰外观&#xff1b; 3、用js(jq)设计动效。 …

用jsp实现一个简单的购物车web应用系统。实现的添加购物商品,删除购物商品并且显示购物车信息。

用jsp实现一个简单的购物车web应用系统。实现的添加购物商品&#xff0c;删除购物商品并且显示购物车信息。 1. 在自己建立的WEB工程中,建立包shopcart.dto,在相应的包中添加类Product.java ,ShopCart.java /*类Product */package shopcart.dto;import java.io.Serializable;pu…

JSP | 简易购物车的实现

本程序共包含四部分文件&#xff0c;只包含jsp文件&#xff0c;将java代码嵌入到jsp文件中实现&#xff1a; loginID.jsp、shop.jsp、food.jsp、count.jsp&#xff0c;分别实现的功能是输入ID页面、超链接功能选择页面、购物页面和购物车页面。 login.jsp文件代码如下&#x…

Javaweb-购物商城实现展示商品,实现购物车购物,结算(Servlet+mysql+jsp+tomcat)

演示视频: 购物网站 代码: https://github.com/wu1369955/shopping 购物网站首页 首先说明:这个是花几天搭建出来玩的,从github上拉到找好看的框架组合的,效果还不错,主要是学习作用.源码之类的也会分享出来,希望一起进步,最好动手实践,可以参照逻辑做的更好, 简易购物商城设…

javascript购物车实现详细代码讲解

我们肯定都很熟悉商品购物车这一功能&#xff0c;每当我们在某宝某东上购买商品的时候&#xff0c;看中了哪件商品&#xff0c;就会加入购物车中&#xff0c;最后结算。购物车这一功能&#xff0c;方便消费者对商品进行管理&#xff0c;可以添加商品&#xff0c;删除商品&#…

JSP(6)简单购物车实现

两个jsp页面之间跳转需要通过Servlet控制器实现 1 创建数据库表 -- 创建一个序列&#xff0c;使book的id自增长 create sequence book_seq start with 1 increment by 1 minvalue 1 maxvalue 99999999999999 nocycle nocache -- 创建一个序列&#xff0c;使orders的id自增长…

用JSP实现的商城购物车模块

这两天&#xff0c;在学习JSP&#xff0c;正好找个小模块来练练手&#xff1a; 以下就是实现购物车模块的页面效果截图&#xff1a; 图1. 产品显示页面 通过此页面进行产品选择&#xff0c;加入到购物车 图2 .购物车页面 图3 . 商品数量设置 好了&#xff0c;先不贴图了&#x…

项目-Java Web购物车-JSP实现

文章目录 源码地址界面演示目录结构准备工作登录注册功能定义DaoBaseDaoProductDaoImp 定义EntityProductCartItem 商品列表与详情界面★购物车页面更多 源码地址 点击文章底部打赏后私信发送源码地址 界面演示 介绍(旧) 浏览器打开http://localhost:8080/ShopCart/login.j…