文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

JavaWeb购物车项目开发实战指南

2024-04-02 19:55

关注

一、项目前提

1、购物车并不是一直放数据库

2、选择使用的技术:

session:(购物车项目使用session)

好处:快(放在内存当中),存对象的
坏处:占用内存,服务器意外待机数据会丢失

cookie

好处:不占用内存,存储很久
坏处:存在客户端上,只能存String,数据有泄露的风险

二、数据库的创建

用户表

create table shop_user (
   id number primary key,--用户id
   account varchar2(30) not null,--用户账户
   password varchar2(30)not null--用户密码
);

商品表

create table shop_goods(
   id number primary key,--商品id
   name varchar2(50) not null,--商品名称
   price number default 0.0,--商品价格
   info varchar2(255) default '三五产品' not null--商品介绍 
);

三、eclipse进行创建包和类:

com.zking.util    帮助类com.zking.pojo  实体类com.zking.dao(放dao接口)com.zking.dao.imp    (放dao接口实现类)com.zking.biz (业务逻辑层放dao方法)com.zking.biz.imp(业务逻辑层放dao实现类) com.zking.vo (view object 视图对象 前端用)

四、主要实现功能

1、购物车用户登录

login.jsp

界面效果

代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css" rel="external nofollow"  rel="external nofollow" >
    <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    <style>
        * {
            outline: none !important;
        }
 
        html,
        body {
            background: #1abe9c;
        }
 
        form {
            width: 300px;
            background: #ebeff2;
            box-shadow: 0px 0px 50px rgba(0, 0, 0, .5);
            border-radius: 5px;
            padding: 20px;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
 
        .btn-group {
            width: 100%;
        }
 
        .btn-group button {
            width: 50%;
        }
    </style>
</head>
 
<body>
<form action="doLogin.jsp" method="post">
    <h3 class="text-center" style="text-shadow: 2px 2px 1px #ed3f3f;">欢迎光临苡桉超市</h3>
    <div class="form-group">
        <input name="account" type="text" class="form-control" placeholder="请输入您的用户名">
    </div>
    <div class="form-group">
        <input name="password" type="password" class="form-control" placeholder="请输入您的密码">
    </div>
    <div class="btn-group">
        <button type="submit" class="btn btn-primary">登录</button>
        <button type="button" class="btn btn-danger">没有账号?</button>
    </div>
</form>
</body>
</html>

doLogin.jsp(处理登录界面)

<%@page import="com.zking.vo.CarItem"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="com.zking.pojo.User"%>
<%@page import="com.zking.biz.impl.UserBizImpl"%>
<%@page import="com.zking.biz.IUserBiz"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    
     request.setCharacterEncoding("UTF-8");
     String account=request.getParameter("account");
     String password=request.getParameter("password");
     
     IUserBiz userBiz=new UserBizImpl();
     User user=userBiz.login(new User(0,account,password));
     
     if(user==null){
    	 response.sendRedirect("login.jsp");
     }else{
    	 //首页需要登录数据
    	 session.setAttribute("user",user);
    	 //分配购物车
    	 List<CarItem>car=new ArrayList<>();
    	 //放到session中(把购物车给我)
    	 session.setAttribute("car", car);
    	 response.sendRedirect("index.jsp");
 
     }
%>

用户实体类User.java

package com.zking.pojo;
 
public class User {
    private Integer id;
    private String account;
    private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public User(Integer id, String account, String password) {
		super();
		this.id = id;
		this.account = account;
		this.password = password;
	}
	public User() {
		super();
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", account=" + account + ", password=" + password + "]";
	}
}

IUserBiz.java (用户逻辑接口) 

package com.zking.biz;
 
import com.zking.pojo.User;

public interface IUserBiz {
  User login(User user);
}

 UserBizImpl.java (用户逻辑接口实现类)

package com.zking.biz.impl;
 
import com.zking.biz.IUserBiz;
import com.zking.dao.IUserDao;
import com.zking.dao.impl.UserDaoImpl;
import com.zking.pojo.User;

public class UserBizImpl implements IUserBiz{
      
	private IUserDao userDao=new UserDaoImpl();
	
	@Override
	public User login(User user) {
		User u = userDao.login(user);
		if(u!=null) {
			if(u.getPassword().equals(user.getPassword())) {
				return u;
			}
		}
		return null;
	}
}

  IUserDao.java(用户数据访问接口)

package com.zking.dao;
 
import com.zking.pojo.User;

public interface IUserDao {
	User login(User user);
}

UserDaoImpl.java(用户数据访问接口实现类)

package com.zking.dao.impl;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
 
import com.zking.dao.IUserDao;
import com.zking.pojo.User;
import com.zking.util.DBHelper;
 
public class UserDaoImpl implements IUserDao {
     
	private Connection con;
	private PreparedStatement ps;
	private ResultSet rs;
	
	@Override
    public User login(User user) {
		try {
		  con=DBHelper.getCon();
		  ps=con.prepareStatement("select * from shop_user where account=?");
		  ps.setString(1,user.getAccount());
		  rs=ps.executeQuery();
		  if(rs.next()) {
			  User u=new User();
			  u.setId(rs.getInt(1));
			  u.setAccount(rs.getString(2));
			  u.setPassword(rs.getString(3));
              return u;
		   }
		} catch (Exception e) {
          e.printStackTrace();
		}finally {
			DBHelper.close(con, ps, rs);
		}
    	return null;
    }
}

2、商品显示

实现效果如下:

将数据库存放的数据显示在页面上,尊贵的xxx通过session拿到登录的用户名

 Goods.java(商品实体类)

package com.zking.pojo;
 
public class Goods {
	 private Integer id;
	 private String name;
	 private Integer price;
	 private String info;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getPrice() {
		return price;
	}
	public void setPrice(Integer price) {
		this.price = price;
	}
	public String getInfo() {
		return info;
	}
	public void setInfo(String info) {
		this.info = info;
	}
	public Goods(Integer id, String name, Integer price, String info) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.info = info;
	}
	public Goods() {
		super();
	}
	@Override
	public String toString() {
		return "Goods [id=" + id + ", name=" + name + ", price=" + price + ", info=" + info + "]";
	}
}

index.jsp(首页代码)

<%@page import="com.zking.pojo.Goods"%>
<%@page import="com.zking.biz.impl.GoodsBizImpl"%>
<%@page import="com.zking.biz.IGoodsBiz"%>
<%@page import="com.zking.pojo.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css" rel="external nofollow"  rel="external nofollow" >
  <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
  <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
  <style>
 
    td:nth-child(3)::before{
      content: "$";
    }
 
  </style>
</head>
 
<body>
<%
   Object obj=session.getAttribute("user");
   if(obj==null){
	   response.sendRedirect("login.jsp");
       return;
   }
%>
    <div class="jumbotron">
        <div class="container">
            <h1>欢迎光临苡桉SuperMarket</h1>
            <p>尊贵的<%=((User)obj).getAccount() %></p>
        </div>
    </div>
    <%=session.getAttribute("car")%>
   <div class="container">
    <table class="table">
        <tr>
            <th>商品序号</th>
            <th>商品名称</th>
            <th>商品单价</th>
            <th>商品描述</th>
            <th>操作</th>
        </tr>
       <%
           IGoodsBiz goodsBiz=new GoodsBizImpl();
           for(Goods goods:goodsBiz.getAll()){
       %>
        <tr>
            <td><%=goods.getId() %></td>
            <td><%=goods.getName() %></td>
            <td><%=goods.getPrice() %></td>
            <td><%=goods.getInfo() %></td>
            <td>
                <div class="btn-group btn-group-xs">
                    <a href="doAddCar.jsp?id=<%=goods.getId() %>" rel="external nofollow"  class="btn btn-primary">添加购物车</a>
                </div>
            </td>
        </tr>
       <%
       }
       %>
    </table>
    </div>
</body>
</html>

IGoodsBiz.java (商品逻辑接口) 

package com.zking.biz;
import java.util.List;
import com.zking.pojo.Goods;

public interface IGoodsBiz {
     List<Goods>getAll();
  
	 //查询单个
	 Goods getOne(Integer id);
}

GoodsBizImpl.java (商品逻辑接口实现类)  

package com.zking.biz.impl;
 
import java.util.List;
 
import com.zking.biz.IGoodsBiz;
import com.zking.dao.IGoodsDao;
import com.zking.dao.impl.GoodsDaoImpl;
import com.zking.pojo.Goods;

public class GoodsBizImpl implements IGoodsBiz {
 
	private IGoodsDao goodsDao=new GoodsDaoImpl();
	@Override
	public List<Goods> getAll() {
		return goodsDao.getAll(); 
	}
   
	@Override
	public Goods getOne(Integer id) {
		return goodsDao.getOne(id);
	}
}

IGoodsDao.java (商品数据访问接口)

package com.zking.dao;
import java.util.List;
import com.zking.pojo.Goods;

public interface IGoodsDao {
	//查询所有
	 List<Goods>getAll();
	 
	 //查询单个
	 Goods getOne(Integer id);
}

GoodsDaoImpl.java (商品数据访问接口实现类)  

package com.zking.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.zking.dao.IGoodsDao;
import com.zking.pojo.Goods;
import com.zking.pojo.User;
import com.zking.util.DBHelper;

public class GoodsDaoImpl implements IGoodsDao{
	private Connection con;
	private PreparedStatement ps;
	private ResultSet rs;
	
	
	@Override
	public List<Goods> getAll() {
		List<Goods>list=new ArrayList<Goods>();
		try {
			  con=DBHelper.getCon();
			  ps=con.prepareStatement("select * from shop_goods ");
			  rs=ps.executeQuery();
			  while(rs.next()) {
				  Goods goods=new Goods();
				  goods.setId(rs.getInt(1));
				  goods.setName(rs.getString(2));
				  goods.setPrice(rs.getInt(3));
				  goods.setInfo(rs.getString(4));
	              list.add(goods);
			   }
			  return list;
			} catch (Exception e) {
	          e.printStackTrace();
			}finally {
				DBHelper.close(con, ps, rs);
			}
		return list;
	}
 
	
	@Override
	public Goods getOne(Integer id) {
 
		try {
			  con=DBHelper.getCon();
			  ps=con.prepareStatement("select * from shop_goods where id=? ");
			 ps.setInt(1, id);
			  rs=ps.executeQuery();
			  if(rs.next()) {
				  Goods goods=new Goods();
				  goods.setId(rs.getInt(1));
				  goods.setName(rs.getString(2));
				  goods.setPrice(rs.getInt(3));
				  goods.setInfo(rs.getString(4));
			      return goods; 
			  }
			 
			} catch (Exception e) {
	          e.printStackTrace();
			}finally {
				DBHelper.close(con, ps, rs);
			}
		return null;
	}
}

3、购物车添加&商品总数和价格的计算

doAddCar.java(处理添加购物车的页面)

<%@page import="java.util.List"%>
<%@page import="com.zking.biz.impl.GoodsBizImpl"%>
<%@page import="com.zking.biz.IGoodsBiz"%>
<%@page import="com.zking.vo.CarItem"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   //添加购物车的页面
   
   //拿购物车
   List<CarItem>car=(List<CarItem>)session.getAttribute("car");
   
   IGoodsBiz goodsBiz=new GoodsBizImpl();
 
   
   //1、得知道是那件商品
   String str=request.getParameter("id");
   int id=-1;
   if(str!=null){
	   id=Integer.parseInt(str);
   }
   
   //2-1 判断该商品是否存在
   boolean f=true;
   for(CarItem item:car){
	   //item.getGoods().getId()  条目的商品id
	   if(id==item.getGoods().getId()){
		   //商品应该是已经被添加了[购物车中某个条目的商品id和你需要添加的商品id相同了]
		   item.setCount(item.getCount()+1);//数量+1   
		   item.setSum(item.getCount()*item.getGoods().getPrice());
		   f=false;
		   break;
	   }
   }
   //只要判断f是否发生了改变
   if(f){
   //2-2、生成一个CarItem[如果购物车没有该商品]
   CarItem carItem=new CarItem();
 
   //设置对应的商品数据
   carItem.setGoods(goodsBiz.getOne(id));
   //数量
   carItem.setCount(1);
   //加车数量*商品单价
   //carItem.getCount()商品加车的数量
   //carItem.getGoods().getPrice() 商品的单价
   carItem.setSum(carItem.getCount()*carItem.getGoods().getPrice());
   //将购物条目carItem 绑定到购物车
   car.add(carItem);
   
  }
   //更新购物车
   session.setAttribute("car", car);
   //跳回首页
   response.sendRedirect("index.jsp");
%>

  CarItem.java(购物车中的每一项,每一个条目)

package com.zking.vo;
 
import com.zking.pojo.Goods;
 

public class CarItem {
  
	private Integer count;//数量
	private Integer sum;//条目总价
	private Goods goods;//对应的商品
	public Integer getCount() {
		return count;
	}
	public void setCount(Integer count) {
		this.count = count;
	}
	public Integer getSum() {
		return sum;
	}
	public void setSum(Integer sum) {
		this.sum = sum;
	}
	public Goods getGoods() {
		return goods;
	}
	public void setGoods(Goods goods) {
		this.goods = goods;
	}
	public CarItem(Integer count, Integer sum, Goods goods) {
		super();
		this.count = count;
		this.sum = sum;
		this.goods = goods;
	}
	
	public CarItem() {
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "CarItem [count=" + count + ", sum=" + sum + ", goods=" + goods + "]";
	}
}

效果先简单打印到页面 之后会进行修改 

今天的分享就到这里结束啦!!?

以上就是关于JavaWeb购物车项目的一些内容!!?

总结

到此这篇关于JavaWeb购物车项目开发的文章就介绍到这了,更多相关JavaWeb购物车项目内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯