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

(web练手小项目)

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

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

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

功能实现效果:

购物车为空状态

功能大致目录结构:

前端界面代码:

(1) shopcar.jsp(购物车界面)

shop carth, td {border-bottom: 1px solid green;}th {background-color: #4CAF50;color: white;}table{text-align: center;}

购物车

function judgeDelete(carGoodsName) {if (confirm("是否删除" + carGoodsName)) {window.location.href = "${pageContext.request.contextPath}/deleteCarGoods" /><%--

购物车为空

--%>
商品名称商品描述价格购买数量操作
${CarGoods.carGoodsName}${CarGoods.carGoodsDes}${CarGoods.carGoodsPrice}${CarGoods.buyCount}

目前您购物车的总价格为:${money}元人民币




(2) shoplist.jsp(商品页)

myshopth, td {border-bottom: 1px solid green;}th {background-color: #4CAF50;color: white;}table{text-align: center;}

:)

$(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"}}})})})

商品页

序号商品名称商品描述商品价格(元)库存数量添至购物车${goodStatus.count}${goods.goodsName}${goods.goodsDes}${goods.goodsPrice}${goods.goodsCount}
$(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();}})})

后端servlet代码:

欢迎页(WelcomeServlet.java)

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

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

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

welcome

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

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