Java实现购物车基本功能

总体框架

1.buy.jsp(将物品加入到购物车)

<%@ page language="java" import="java.util.*,shopping.cart.*,java.sql.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'buy.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <%
    String id=request.getParameter("id");
    Class.forName("com.mysql.jdbc.Driver");  
    Connection  con=DriverManager.getConnection("jdbc:mysql://localhost/shop","root","123456");  
    Statement stmt= con.createStatement();
    ResultSet  rs=stmt.executeQuery("select * from goods where id='"+id+"'"); 
    ArrayList <Product> list =(ArrayList)session.getAttribute("list");
     int n=0;
     rs.next();
     if (list==null)
    {     Product p=new Product();
          list=new ArrayList<Product>();
          p.setId(rs.getString("id"));
          p.setName(rs.getString("name"));
          p.setDescription(rs.getString("description"));
          p.setPrice(rs.getDouble("price"));
          p.setPic(rs.getString("pic"));
          p.setNumber(1);
          list.add(p);
     }
    else
    {
       Product p1=new Product();
       for(int i=0;i<list.size();i++ )
       { 
       p1=(Product)list.get(i);
       if (p1.getId().equals(id))
       {
       
       p1.setNumber(p1.getNumber()+1);
       n++;
       list.set(i,p1);
       break;
       }  
      }
      if(n==0) 
      {  
    	  Product p2=new Product();
          p2.setId(rs.getString("id"));
          p2.setName(rs.getString("name"));
          p2.setDescription(rs.getString("description"));
          p2.setPrice(rs.getDouble("price"));
          p2.setPic(rs.getString("pic"));
          p2.setNumber(1);
          list.add(p2);                       
      }  
  
    }
     session.setAttribute("list",list);     
     response.sendRedirect("show.jsp");
     %>
  </body>
</html>

2.del.jsp(删除购物车)

<%@ page language="java" import="java.util.*,shopping.cart.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'buy.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <%
   
     String id=request.getParameter("id");
     ArrayList <Product> list =(ArrayList)session.getAttribute("list");
     for(int i=0;i<list.size();i++)
     {
     if (list.get(i).getId().equals(id))
     {
     list.remove(i);
     break;
     }
     }    	    
     session.setAttribute("list",list);     
     response.sendRedirect("look.jsp");
     %>
  </body>
</html>

3.show.jsp(展示购物车)

<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'show.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

<style type="text/css">
        table
        {
            border-collapse: collapse;
            margin: 0 auto;
            text-align: center;
        }
        table td, table th
        {
            border: 1px solid #cad9ea;
            color: #666;
            height: 30px;
        }
        table thead th
        {
            background-color: #CCE8EB;
            width: 100px;
        }
        table tr:nth-child(odd)
        {
            background-color:#eeffee;
        }
        table tr:nth-child(even)
        {
           background: #fff; 
        }
         table thead th
        {
            background-color: #CCE8EB;
            width: 100px;
        }
    tr:hover td, tr:hover th { /*tr也有hover样式*/
     background-color: #B3DE94;
     color:#fff;
}
table caption {
    caption-side: top;
    padding: .2em;
    height:30px;
    font-size: 24px;
    border-bottom: 2px solid #B3DE94;
    border-top: 2px solid #B3DE94;
}
img:hover {
    transform: scale(1.5);
}
 a{
 text-decoration:none;
  color: #666;
 }
    </style>
  </head>
  
  <body>
   <table>
   <caption>购买商品列表</caption>
   <tr align="center"  height="40px">
   <td>商品图片</td>
   <td>商品名称</td>
   <td>商品描述</td>
   <td>商品价格</td>
   <td>购买商品</td>  
   <td>查看购物车</td> 
   </tr>
   <%
   Class.forName("com.mysql.jdbc.Driver");  
   Connection  con=DriverManager.getConnection("jdbc:mysql://localhost/shop","root","123456");  
   Statement stmt= con.createStatement();
   ResultSet  rs=stmt.executeQuery("select * from goods");     
   while (rs.next())
   {
	   out.print("<tr  align='center'>"); 
	   out.print("<td>"+"<img src="+rs.getString("pic")+" width=140 height=130>"+"</td>");
	   out.print("<td>"+rs.getString("name")+"</td>");
	   out.print("<td>"+rs.getString("description")+"</td>");
	   out.print("<td>"+rs.getString("price")+"</td>");
	   out.print("<td><a href=buy.jsp?id="+rs.getString("id")+">放入购物车</a></td>");
	   out.print("<td><a href=look.jsp>查看我的购物车</a></td>");
       out.print("</tr>");
   } 
   %>
   </table>
  </body>
</html>

4.look.jsp(查看购物车)

<%@ page language="java" import="java.util.*,shopping.cart.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'look.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
   
  <style type="text/css">
        table
        {
            border-collapse: collapse;
            margin: 0 auto;
            text-align: center;
        }
        table td, table th
        {
            border: 1px solid #cad9ea;
            color: #666;
            height: 30px;
        }
        table thead th
        {
            background-color: #CCE8EB;
            width: 100px;
        }
        table tr:nth-child(odd)
        {
            background-color:#eeffee;
        }
        table tr:nth-child(even)
        {
           background: #fff; 
        }
         table thead th
        {
            background-color: #CCE8EB;
            width: 100px;
        }
    tr:hover td, tr:hover th { /*tr也有hover样式*/
     background-color: #B3DE94;
     color:#fff;
}
table caption {
    caption-side: top;
    padding: .2em;
    height:30px;
    font-size: 24px;
    border-bottom: 2px solid #B3DE94;
    border-top: 2px solid #B3DE94;
}


img:hover {
    transform: scale(1.5);
}
 a{
 text-decoration:none;
  color: #666;
 }
    </style>
  </head>
  
  <body>
  <%
  ArrayList <Product> l =(ArrayList)session.getAttribute("list");
  if (l!=null && l.size()>0)
  {
    %>
   <table>
   <caption>购物车中商品列表</caption>
   <tr align="center" >
   <td>商品图片</td>
   <td>商品名称</td>
   <td>商品描述</td>
   <td>商品数量</td>
   <td>商品价格</td>
   <td>商品总价</td>  
   <td>删除商品</td> 
   </tr>
   <%
   double sum=0.0;
   Product p=new Product();
   
   for(int i=0;i<l.size();i++)
   {
    p=(Product)l.get(i);
    sum=sum+p.getPrice()*p.getNumber();
    %>
   <tr  align="center">
   <td><img src=<%=p.getPic()%> width=140 height=130></td>
   <td><%=p.getName() %></td>
   <td><%=p.getDescription() %></td>
   <td><%=p.getNumber() %></td>
   <td><%=p.getPrice() %></td>  
   <td><%=p.getPrice()*p.getNumber()  %></td>  
   <td><a href=del.jsp?id=<%=p.getId() %>>删除商品</a></td>  
   </tr>
  <%
  }
   %>
   <tr>
 <h2> <td  colspan="7">商品总值:<%=sum%>元,<a href="" >支付中心</a></td>  </h2> 
   </tr>
   </table>
   <%
  }else
  {
	  
	 out.print("<script>alert('你还没有购物!请回到购物页码!');location.href='show.jsp'</script>");
  }
   
   %>
  </body>
</html>

5.Product.java

package shopping.cart;
import java.io.Serializable;

public class Product implements Serializable {
	private String id;// 产品标识
	private String name;// 产品名称
	private String description;// 产品描述
	private double price;// 产品价格
    private int  number;//产品数量
    private String pic;//产品图片
	public String getPic() {
		return pic;
	}
	public void setPic(String pic) {
		this.pic = pic;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public int getNumber() {
		return number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
	
}

数据库中信息

在数据库中创建一个shop数据库,创建goods表,以下是创建方法,创建完之后将数据插入到表中

use shop;
CREATE TABLE `goods` (
  `id` varchar(10) NOT NULL DEFAULT '',
  `name` varchar(20) DEFAULT NULL,
  `description` varchar(100) DEFAULT NULL,
  `price` double(8,2) DEFAULT NULL,
  `number` int(10) DEFAULT NULL,
  `pic` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

INSERT INTO `goods` VALUES ('1001', '苹果', '富士山苹果', '4.50', '20', 'image\\1.jpg');
INSERT INTO `goods` VALUES ('1002', '香蕉', '云南昆明香蕉', '2.10', '100', 'image\\2.jpg');
INSERT INTO `goods` VALUES ('1003', '体恤衫', '驻马店产上等体恤衫', '120.00', '12', 'image\\3.jpg');
INSERT INTO `goods` VALUES ('1004', '手表', '上海生产', '800.00', '34', 'image\\4.jpg');

最后运行结果图片

 

 本次购物车只是实现了几个简单的购物车功能,你可以自己多实现几个再改进改进。欢迎交流讨论。

图片如下

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Java使用数据库实现购物车功能的步骤如下: 1. 创建购物车表:在数据库中创建一个购物车表,用于存储购物车中的商品信息。购物车表可以包含以下字段:购物车项ID、用户ID、商品ID、商品数量等。 2. 添加商品到购物车:当用户点击添加商品到购物车时,将商品信息插入购物车表中。可以使用SQL语句或者ORM框架来实现插入操作。 3. 获取购物车中的购物项:通过查询购物车表,可以获取到购物车中的所有购物项。可以使用SQL语句或者ORM框架来实现查询操作。下面是一个获取购物车中购物项的示例代码: ```java @Override public CartItem getCartItem(Long skuId) { BoundHashOperations<String, Object, Object> cartOps = getCartOps(); String s = (String) cartOps.get(skuId.toString()); CartItem cartItem = JSON.parseObject(s, CartItem.class); return cartItem; } ``` 4. 增加购物车中商品数量:当用户修改购物车中商品数量时,可以通过更新购物车表中对应购物项的数量来实现。下面是一个增加购物车中商品数量的示例代码: ```java @Override public void countItem(Long skuId, Integer num) { BoundHashOperations<String, Object, Object> cartOps = getCartOps(); CartItem cartItem = getCartItem(skuId); cartItem.setCount(cartItem.getCount() + num); cartOps.put(skuId.toString(), JSON.toJSONString(cartItem)); } ``` 以上是使用数据库实现购物车功能的基本步骤和示例代码。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

暖暖的味道

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

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

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

打赏作者

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

抵扣说明:

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

余额充值