0


JavaWeb购物车项目

一、项目前提

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">
    <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;
/**
 * 用户逻辑接口
 * @author zjjt
 *
 */
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;
/**
 * 用户逻辑接口实现类
 * @author zjjt
 *
 */
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;
/**
 * 用户数据访问接口
 * @author zjjt
 *
 */
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">
  <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() %>" 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;
/**
 * 商品逻辑接口
 * @author zjjt
 *
 */
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;
/**
 * 商品逻辑接口实现类
 * @author zjjt
 *
 */
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;
/**
 * 商品数据访问接口
 * @author zjjt
 *
 */
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;
/**
 * 访问数据接口实现类
 * @author zjjt
 *
 */
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;
    }

    /**
     * 根据id查询商品
     */
    @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;

/**
 * 购物车中的每一项,每一个条目
 * @author zjjt
 *
 */
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购物车项目的一些内容!!📚

标签: eclipse java tomcat

本文转载自: https://blog.csdn.net/weixin_62270300/article/details/124159838
版权归原作者 時宜 所有, 如有侵权,请联系我们删除。

“JavaWeb购物车项目”的评论:

还没有评论