首頁 > 軟體

JavaWeb購物車專案開發實戰指南

2022-06-15 18:01:25

一、專案前提

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;
/**
 * 使用者邏輯介面
 * @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" 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;
/**
 * 商品邏輯介面
 * @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 + "]";
	}
}

效果先簡單列印到頁面 之後會進行修改 

今天的分享就到這裡結束啦!!


IT145.com E-mail:sddin#qq.com