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

article/2025/10/17 22:53:23

先看效果图:

实现代码:

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="/index"/>
</body>
</html>

show.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.shop.GoodsSingle" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%    ArrayList goodslist=(ArrayList)session.getAttribute("goodslist");    %>

<table border="1" width="450" rules="none" cellspacing="0" cellpadding="0">
    <tr height="50"><td colspan="4" align="center">提供商品如下</td></tr>
    <tr align="center" height="30" bgcolor="lightgrey">
        <td>序号</td> 
        <td>名称</td>
        <td>价格(元/斤)</td>
        <td>购买</td>
    </tr>
    <%  if(goodslist==null||goodslist.size()==0){ %>
    <tr height="100"><td colspan="4" align="center">没有商品可显示!</td></tr>
    <% 
        } 
        else{
            for(int i=0;i<goodslist.size();i++){
                GoodsSingle single=(GoodsSingle)goodslist.get(i);
    %>
    <tr height="50" align="center">
        <td><%=single.getName()%></td>
        <td><%=single.getNo()%></td>
        <td><%=single.getPrice()%></td>
        <td><a href="doCar?action=buy&id=<%=i%>">购买</a></td>
    </tr>
    <%
            }
        }
    %>
    <tr height="50">
        <td align="center" colspan="4"><a href="shopcar8.jsp">查看购物车</a></td>
    </tr>
</table>
</body>
</html>

shopcar.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.shop.GoodsSingle" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% 
    //获取存储在session中用来存储用户已购买商品的buylist集合对象
    ArrayList buylist=(ArrayList)session.getAttribute("buylist");
    float total=0;                             //用来存储应付金额
%>
<table border="1" width="450" rules="none" cellspacing="0" cellpadding="0">
    <tr height="50"><td colspan="6" align="center">购买的商品如下</td></tr>
    <tr align="center" height="30" bgcolor="lightgrey">
        <td>序号</td>
        <td>名称</td>
        <td>价格(元/斤)</td>
        <td>数量</td>
        <td>总价(元)</td>
        <td>移除(-1/次)</td>
    </tr>
    <%    if(buylist==null||buylist.size()==0){ %>
    <tr height="100"><td colspan="6" align="center">您的购物车为空!</td></tr>
    <% 
        }
        else{
            for(int i=0;i<buylist.size();i++){
                GoodsSingle single=(GoodsSingle)buylist.get(i);
                String no = single.getNo();
                String name=single.getName();            //获取商品名称
                float price=single.getPrice();            //获取商品价格
                int num=single.getNum();                //获取购买数量
                //计算当前商品总价,并进行四舍五入
                float money=((int)((price*num+0.05f)*10))/10f;
                total+=money;                             //计算应付金额
    %>
    <tr align="center" height="50">
        <td><%=name%></td>
        <td><%=no%></td>
        <td><%=price%></td>
        <td><%=num%></td>
        <td><%=money%></td>
        <td><a href="doCar?action=remove&name=<%=single.getName() %>">移除</a></td>
    </tr>
    <%                            
            }
        }
    %>
    <tr height="50" align="center"><td colspan="6">应付金额:<%=total%></td></tr>
    <tr height="50" align="center">
        <td colspan="3"><a href="show8.jsp">继续购物</a></td>
        <td colspan="4"><a href="doCar?action=clear">清空购物车</a></td>
    </tr>                
</table>
</body>
</html>

BuyServlet.java

package com.shop;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shop.MyTools;
import com.shop.ShopCar;
import com.shop.GoodsSingle;

public class BuyServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action=request.getParameter("action");    //获取action参数值
        if(action==null)
            action="";
        if(action.equals("buy"))                    //触发了“购买”请求
            buy(request,response);                        //调用buy()方法实现商品的购买
        if(action.equals("remove"))                    //触发了“移除”请求
            remove(request,response);                    //调用remove()方法实现商品的移除
        if(action.equals("clear"))                    //触发了“清空购物车”请求
            clear(request,response);                    //调用clear()方法实现购物车的清空
    }
    //实现购买商品的方法
    protected void buy(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession();        
        String strId=request.getParameter("id");        //获取触发“购买”请求时传递的id参数,该参数存储的是商品在goodslist对象中存储的位置    
        int id=MyTools.strToint(strId);
        
        ArrayList goodslist=(ArrayList)session.getAttribute("goodslist");
        GoodsSingle single=(GoodsSingle)goodslist.get(id);
        
        ArrayList buylist=(ArrayList)session.getAttribute("buylist");        //从session范围内获取存储了用户已购买商品的集合对象
        if(buylist==null)
            buylist=new ArrayList();
        
        ShopCar myCar=new ShopCar();
        myCar.setBuylist(buylist);                         //将buylist对象赋值给ShopCar类实例中的属性
        myCar.addItem(single);                            //调用ShopCar类中addItem()方法实现商品添加操作
        
        session.setAttribute("buylist",buylist);        
        response.sendRedirect("show8.jsp");                //将请求重定向到show.jsp页面
    }
    //实现移除商品的方法
    protected void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession();
        ArrayList buylist=(ArrayList)session.getAttribute("buylist");
        
        String name=request.getParameter("name");
        ShopCar myCar=new ShopCar();
        myCar.setBuylist(buylist);                        //将buylist对象赋值给ShopCar类实例中的属性
        myCar.removeItem(MyTools.toChinese(name));        //调用ShopCar类中removeItem ()方法实现商品移除操作
        
        response.sendRedirect("shopcar8.jsp");
    }
    //实现清空购物车的方法
    protected void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession();
        ArrayList buylist=(ArrayList)session.getAttribute("buylist");            //从session范围内获取存储了用户已购买商品的集合对象
        buylist.clear();                                                        //清空buylist集合对象,实现购物车清空的操作
        
        response.sendRedirect("shopcar8.jsp");
    }
}

 

GoodsSingle.java

package com.shop;

public class GoodsSingle {
    private String no;
    public String getNo() {
        return no;
    }
    public void setNo(String no) {
        this.no = no;
    }
    private String name;                        //保存商品名称
    private float price;                        //保存商品价格
    private int num;                            //保存商品购买数量
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }    
}

IndexServlet.java

package com.shop;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.shop.GoodsSingle;

public class IndexServlet extends HttpServlet {
    private static ArrayList goodslist=new ArrayList();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession();        
        session.setAttribute("goodslist",goodslist);
        response.sendRedirect("show8.jsp");
    }
    static{                                        //静态代码块
        String[] no={"苹果","香蕉","梨","橘子"};
        String[] names={"A","B","C","D"};
        float[] prices={2.8f,3.1f,2.5f,2.3f};        
        for(int i=0;i<4;i++){
            GoodsSingle single=new GoodsSingle();
            single.setNo(no[i]);
            single.setName(names[i]);
            single.setPrice(prices[i]);
            single.setNum(1);
            goodslist.add(single);
        }
    }
}

 

MyTools.java

package com.shop;

import java.io.UnsupportedEncodingException;

public class MyTools {
    public static int strToint(String str){            //将String型数据转换为int型数据的方法
        if(str==null||str.equals(""))
            str="0";
        int i=0;
        try{
            i=Integer.parseInt(str);
        }catch(NumberFormatException e){
            i=0;
            e.printStackTrace();
        }
        return i;        
    }
    public static String toChinese(String str){        //进行转码操作的方法
        if(str==null)
            str="";
        try {
            str=new String(str.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            str="";
            e.printStackTrace();
        }
        return str;
    }
}

 

ShopCar.java

package com.shop;

import java.util.ArrayList;
import com.shop.GoodsSingle;

public class ShopCar {
    private ArrayList buylist=new ArrayList();                                    //用来存储购买的商品
    public void setBuylist(ArrayList buylist) {
        this.buylist = buylist;
    }
    /**
     * @功能 向购物车中添加商品
     * @参数 single为GoodsSingle类对象,封装了要添加的商品信息
     */
    public void addItem(GoodsSingle single){
        if(single!=null){
            if(buylist.size()==0){                                                //如果buylist中不存在任何商品
                GoodsSingle temp=new GoodsSingle();
                temp.setNo(single.getNo());
                temp.setName(single.getName());
                temp.setPrice(single.getPrice());
                temp.setNum(single.getNum());
                buylist.add(temp);                                                //存储商品
            }
            else{                                                                //如果buylist中存在商品    
                int i=0;                
                for(;i<buylist.size();i++){                                        //遍历buylist集合对象,判断该集合中是否已经存在当前要添加的商品        
                    GoodsSingle temp=(GoodsSingle)buylist.get(i);                //获取buylist集合中当前元素        
                    if(temp.getName().equals(single.getName())){                //判断从buylist集合中获取的当前商品的名称是否与要添加的商品的名称相同
                        //如果相同,说明已经购买了该商品,只需要将商品的购买数量加1
                        temp.setNum(temp.getNum()+1);                            //将商品购买数量加1
                        break;                                                    //结束for循环
                    }
                }
                if(i>=buylist.size()){                                            //说明buylist中不存在要添加的商品
                    GoodsSingle temp=new GoodsSingle();
                    temp.setNo(single.getNo());
                    temp.setName(single.getName());
                    temp.setPrice(single.getPrice());
                    temp.setNum(single.getNum());
                    buylist.add(temp);                                            //存储商品
                }
            }
        }            
    }
    /**
     * @功能 从购物车中移除指定名称的商品
     * @参数 name表示商品名称
     */
    public void removeItem(String name){
        for(int i=0;i<buylist.size();i++){                            //遍历buylist集合,查找指定名称的商品
            GoodsSingle temp=(GoodsSingle)buylist.get(i);           //获取集合中当前位置的商品
            if(temp.getName().equals(name)){                        //如果商品的名称为name参数指定的名称    
                if(temp.getNum()>1){                                //如果商品的购买数量大于1
                    temp.setNum(temp.getNum()-1);                    //则将购买数量减1
                    break;                                             //结束for循环
                }
                else if(temp.getNum()==1){                            //如果商品的购买数量为1
                    buylist.remove(i);                                //从buylist集合对象中移除该商品
                }
            }
        }
    }
}


http://chatgpt.dhexx.cn/article/23vTON5P.shtml

相关文章

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…

jsp购物车(session版)

目录 一、要用到的 js 和 css 文件 二、数据库表实体类Dao类 1、数据库表 2、实体类 3、Dao类方法(GoodsDao) 四、商品主页面&#xff08;index.jsp&#xff09; 1、代码分析 2、完整代码 五、购物车页面&#xff08;spcar.jsp&#xff09; 1、代码分析 2、完整代码 3、删除…

jsp实现购物车

文章目录 一、案例演示二、实现步骤1.info.jsp2.UserServlet3.cart.jsp4.UserServlet 一、案例演示 点击购买进入到购物车页面&#xff0c;增加减少数量都会对小计&#xff0c;总计产生影响&#xff0c;点击继续购买&#xff0c;回到挑选页面product_list.jsp 二、实现步骤 …

图像识别技术

图像识别算法实现收藏 <script type"text/javascript"></script> <script></script> 以往的图像处理函数实现&#xff0c;多是针对图像句柄。算法实现 需要操作复杂的图像文件。 但是&#xff0c;这种方式算法实现和调试的周期比较长。为了加…

神经网络图像识别算法,神经网络提取特征值

哪些神经网络可以用在图像特征提取上 BP神经网络、离散Hopfield网络、LVQ神经网络等等都可以。 1.BP&#xff08;BackPropagation&#xff09;神经网络是1986年由Rumelhart和McCelland为首的科学家小组提出&#xff0c;是一种按误差逆传播算法训练的多层前馈网络&#xff0c;…

基于神经网络的图像识别

一、目的 1. 了解深度学习的基本原理&#xff1b; 2. 能够使用 PaddleHub 深度学习开源工具进行图像识别&#xff1b; 3. 能够使用 PaddlePaddle 训练神经网络模型&#xff1b; 4. 能够使用 Paddle 完成手写实验. 5. 能够使用 keras 训练神经网络模型。 二、环境配置&#xff1…

机器学习决策树算法解决图像识别

算法介绍 什么是决策树算法 决策树又称判定树&#xff0c;是一个类似于流程图的树结构&#xff1a;其中&#xff0c;每个内部结点表示在一个属性上的测试&#xff0c;每个分支代表一个属性输出&#xff0c;而每个树叶结点代表类或类分布。树的最顶层是根结点。 构造决策树的基…

opencv 图像识别

opencv的目标是使计算机可以快速准确地从数字图像中提取和分析特征。它使用了许多新的算法和技术&#xff0c;例如改进的模板匹配、基于统计的特征分析以及深度学习等。opencv支持多种平台&#xff0c;包括 Windows、 MacOS、 Linux和 Android&#xff0c;开发者可以使用 OpenC…

图像识别算法(二)

一、线性分类器 线性分类器&#xff08;Linear Classification&#xff09;是比KNN分类器更有效的一种分类器。这个方法有两个重要的部分&#xff1a;分数函数&#xff08;score function&#xff09;和损失函数&#xff08;loss function&#xff09;。分数函数是江原始数据匹…

基于KNN算法的图像识别

你需要完成一个图像识别的任务&#xff0c;主要使用的模型是KNN算法。使用的数据集是cifar-10&#xff0c;是图像识别领域最为经典的数据及之一。具体的数据可以从以下的链接下载&#xff1a; https://www.cs.toronto.edu/~kriz/cifar.html&#xff0c; 下载之后把是数据集解压…

opencv图像算法

图像的对比度增强 一&#xff1a; 绘制直方图 就是把各个像素值所含有的个数统计出来&#xff0c;然后画图表示。 可以看到在当前图像中&#xff0c;哪个像素值的个数最多。 同时&#xff0c;可以看当前图像总体的像素值大小在哪些范围。。靠近0的话&#xff0c;说明图像偏暗…

图像识别中的深度学习

图像识别中的深度学习 来源&#xff1a;《中国计算机学会通讯》第8期《专题》 作者&#xff1a;王晓刚 深度学习发展历史 深度学习是近十年来人工智能领域取得的重要突破。它在语音识别、自然语言处理、计算机视觉、图像与视频分析、多媒体等诸多领域的应用取得了巨大成功。现有…