目录
GoodsDaoImpl.java(商品数据访问接口实现类)
之所以选择session做购物车的登录功能是因为session是回话级存储。可以保留客户端每次发送请求的数据。相比较于数据库版的购物车,session运行的速度更快,但是也会存在相应的缺点。比如缺少安全性,针对这方面的问题,后续我们会更新内存数据库版的购物车。
购物车的主要功能:
- 登录验证(session)
- 增加购物车(session)
登录:
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!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.yilin.biz.IUserBiz"%>
<%@ page import="com.yilin.biz.impl.UserBizImpl"%>
<%@ page import="com.yilin.pojo.User"%>
<%@ page import="java.util.List"%>
<%@ page import="com.yilin.vo.CarItem"%>
<%@ page import="java.util.ArrayList"%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%
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.yilin.pojo;
/**
* 用户实体类
* @author 一麟
*
*/
public class User {
private Integer id;
private String account;
private String password;
public User() {
// TODO Auto-generated constructor stub
}
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;
}
@Override
public String toString() {
return "User [id=" + id + ", account=" + account + ", password=" + password + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((account == null) ? 0 : account.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (account == null) {
if (other.account != null)
return false;
} else if (!account.equals(other.account))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
return true;
}
}
UserBizImpl.java(用户逻辑接口实现类)
package com.yilin.biz.impl;
import com.yilin.biz.IUserBiz;
import com.yilin.dao.IUserDao;
import com.yilin.dao.impl.UserDaoImpl;
import com.yilin.pojo.User;
/**
*
* @author 一麟
*
*/
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.yilin.dao;
import com.yilin.pojo.User;
/**
*
* @author 一麟
*
*/
public interface IUserDao {
User login(User user);
}
UserDaoImpl.java(用户数据访问接口实体类)
package com.yilin.dao.impl;
import com.yilin.dao.IUserDao;
import com.yilin.pojo.User;
import com.yilin.util.DBHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author 一麟
*
*/
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;
}
}
增加购物车
goods.java(商品实体类)I
package com.yilin.pojo;
/**
* 商品实体类
*
* @author 一麟
*
*/
public class Goods {
private Integer id;
private String name;
private Integer price;
private String info;
public Goods() {
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Goods [id=" + id + ", name=" + name + ", price=" + price + ", info=" + info + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((info == null) ? 0 : info.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((price == null) ? 0 : price.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Goods other = (Goods) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (info == null) {
if (other.info != null)
return false;
} else if (!info.equals(other.info))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (price == null) {
if (other.price != null)
return false;
} else if (!price.equals(other.price))
return false;
return true;
}
public Goods(Integer id, String name, Integer price, String info) {
super();
this.id = id;
this.name = name;
this.price = price;
this.info = 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;
}
}
IGoodsBiz,java(商品逻辑接口)
package com.yilin.biz;
import com.yilin.pojo.Goods;
import java.util.List;
/**
*
* @author 一麟
*
*/
public interface IGoodsBiz {
List<Goods> getAll();
Goods getOne(Integer id);
}
GoodsBizImpl.java(商品逻辑接口实现类)
package com.yilin.biz.impl;
import com.yilin.biz.IGoodsBiz;
import com.yilin.dao.IGoodsDao;
import com.yilin.dao.impl.GoodsDaoImpl;
import com.yilin.pojo.Goods;
import java.util.List;
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.yilin.dao;
import com.yilin.pojo.Goods;
import java.util.List;
/**
*
* @author 一麟
*
*/
public interface IGoodsDao {
//商品集合
List<Goods> getAll();
Goods getOne(Integer id);
}
GoodsDaoImpl.java(商品数据访问接口实现类)
package com.yilin.dao.impl;
import com.yilin.dao.IGoodsDao;
import com.yilin.pojo.Goods;
import com.yilin.util.DBHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author 一麟
*
*/
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;
}
}
doAdd.jsp(处理购物车的增加)
<%@page import="com.yilin.biz.impl.GoodsBizImpl"%>
<%@ page import="com.yilin.vo.CarItem" %>
<%@ page import="com.yilin.biz.IGoodsBiz" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
//拿购物车
List<CarItem> car=(List<CarItem>)session.getAttribute("car");//将object类型转换为list<carItem>类型
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] 中
car.add(carItem);
}
//更新购物车
session.setAttribute("car", car);
//跳回首页
response.sendRedirect("index.jsp");
%>
CarItem.java(商品项实体类)
package com.yilin.vo;
import com.yilin.pojo.Goods;
/**
*
* @author 一麟
*
*/
public class CarItem {
private Integer count;//总价
private Integer sum;//条目总价
private Goods goods;//商品对象
public CarItem() {
// TODO Auto-generated constructor stub
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((count == null) ? 0 : count.hashCode());
result = prime * result + ((goods == null) ? 0 : goods.hashCode());
result = prime * result + ((sum == null) ? 0 : sum.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarItem other = (CarItem) obj;
if (count == null) {
if (other.count != null)
return false;
} else if (!count.equals(other.count))
return false;
if (goods == null) {
if (other.goods != null)
return false;
} else if (!goods.equals(other.goods))
return false;
if (sum == null) {
if (other.sum != null)
return false;
} else if (!sum.equals(other.sum))
return false;
return true;
}
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;
}
@Override
public String toString() {
return "CarItem [count=" + count + ", sum=" + sum + ", goods=" + goods + "]";
}
public CarItem(Integer count, Integer sum, Goods goods) {
super();
this.count = count;
this.sum = sum;
this.goods = goods;
}
}
index(主页)
<%@ page import="com.yilin.pojo.User"%>
<%@ page import="com.yilin.biz.IGoodsBiz"%>
<%@ page import="com.yilin.biz.impl.GoodsBizImpl"%>
<%@ page import="com.yilin.pojo.Goods"%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<!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>
数据库建表:
--用户表
CREATE TABLE SHOP_USER(
ID NUMBER PRIMARY KEY,
ACCOUNT VARCHAR2(30) NOT NULL,
PASSWORD VARCHAR2(30) NOT NULL
)
insert into shop_user values(1,'yilin','jiang');
commit;
--商品表
CREATE TABLE SHOP_GOODS(
ID NUMBER PRIMARY KEY,
NAME VARCHAR2(30) NOT NULL,
PRICE NUMBER DEFAULT 0,
INFO VARCHAR2(30) DEFAULT '暂无描述'
)
文件目录:
这期的分享就到此为止了,下期继续完善购物车小项目!😄😄😄😄