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

先看效果图:

实现代码:

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集合对象中移除该商品
                }
            }
        }
    }
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

欲戴王冠♛必承其重

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值