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" 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()%20%>" 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 + "]";
	}
}

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

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

以上就是關於JavaWeb購物車項目的一些內容!!📚

總結

到此這篇關於JavaWeb購物車項目開發的文章就介紹到這瞭,更多相關JavaWeb購物車項目內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: