目录
购物车代码
SQL语句
create table car_user
(
id number primary key,
account varchar2(30) not null,
password varchar(32) not null
);
comment on column car_user.ID is '用户编号';
comment on column car_user.account is '用户账户';
comment on column car_user.password is '用户密码(MD5)';
create table car_goods
(
id number primary key,
name varchar2(20) not null,
describe varchar2(100) default '此商品暂时没有介绍🤣' not null,
price number not null
);
comment on column car_goods.ID is '商品编号';
comment on column car_goods.name is '商品名称';
comment on column car_goods.describe is '商品描述';
comment on column car_goods.price is '用户价格';
create table car_order
(
id number primary key,
user_id number not null,
total number not null
);
comment on column car_order.ID is '订单编号';
comment on column car_order.user_id is '谁的订单!';
comment on column car_order.total is '订单总价';
create table car_order_item
(
id number primary key,
order_id number not null,
goods_id number not null,
quantity number not null,
total number not null
);
comment on column car_order_item.ID is '订单项编号';
comment on column car_order_item.order_id is '哪个订单!';
comment on column car_order_item.goods_id is '哪个商品!';
comment on column car_order_item.quantity is '下单数量';
comment on column car_order_item.total is '订单项总价';
comment on table car_user is '购物车用户表';
comment on table car_goods is '购物车商品表';
comment on table car_order is '购物车订单表';
comment on table car_order_item is '购物车订单项表';
create unique index car_user_account_idx on car_user (account);
insert into car_user
values (1, '2890@fox.com', 'ff9830c42660c1dd1942844f8069b74a');-- root123
insert into car_user
values (2, '2357@fox.com', 'e10adc3949ba59abbe56e057f20f883e');-- 123456
insert into car_goods
select 1, '丝袜奶茶', '冰冰娘娘,很好喝', 99
from dual
union
select 2, '勃勃奶茶', '啊~,好冰冰', 29
from dual
union
select 3, '蜜雪大补丁', '可以加个桃桃🍑', 59
from dual
union
select 4, '臭🐟咖啡', '人气最高', 88
from dual
union
select 5, '雪王咖啡', 'incredible taste', 999
from dual
union
select 6, '拉稀弹筒', '👌,就亿点点', 1
from dual;
insert into car_order_item
values (1, 1, 1, 2, 99 * 2);
insert into car_order_item
values (2, 1, 2, 3, 29 * 3);
insert into car_order_item
values (3, 1, 6, 100, 100);
insert into car_order
values (1, 1, 99 * 2 + 29 * 3 + 100);
insert into car_order_item
values (4, 2, 3, 2, 59 * 2);
insert into car_order_item
values (5, 2, 4, 3, 88 * 3);
insert into car_order_item
values (6, 2, 5, 100, 999 * 100);
insert into car_order
values (2, 2, 59 * 2 + 88 * 3 + 999 * 100);
select *
from car_user;
select *
from car_order;
select *
from car_order_item;
select *
from car_goods;
pojo包
Goods.java
package com.zking.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@SuppressWarnings("all")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Goods {
private Integer id;
private String name;
private String describe;
private Integer price;
}
OrderItem.java
package com.zking.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@SuppressWarnings("all")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OrderItem {
private Integer id;
private Integer orderId;
private Goods goods;
private Integer quantity;
private Integer total;
}
User.java
package com.zking.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@SuppressWarnings("all")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class User {
private Integer id;
private String account;
private String password;
}
util包
DBHelper.java
package com.zking.util;
import java.sql.*;
@SuppressWarnings("all")
public class DBHelper {
//定义链接字符串
private static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
//加载驱动
static {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获得链接
public static Connection getCon() {
try {
return DriverManager.getConnection(URL, "scott", "123");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//关闭资源
public static void close(Connection con, PreparedStatement ps, ResultSet rs) {
try {
if (con != null && !con.isClosed()) {
con.close();
}
if (ps != null) {
ps.close();
}
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
dao包
IGoodsDao.java
package com.zking.dao;
import com.zking.pojo.Goods;
import java.util.List;
@SuppressWarnings("all")
public interface IGoodsDao {
List<Goods> list();
Goods one(int id);
}
IUserDao.java
package com.zking.dao;
import com.zking.pojo.User;
@SuppressWarnings("all")
public interface IUserDao {
User login(User user);
}
dao.impl包
GoodsDaoImpl.java
package com.zking.dao.impl;
import com.zking.dao.IGoodsDao;
import com.zking.pojo.Goods;
import com.zking.util.DBHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("all")
public class GoodsDaoImpl implements IGoodsDao {
//定义资源
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
@Override
public List<Goods> list() {
List<Goods> list = new ArrayList<Goods>();
try {
con = DBHelper.getCon();
ps = con.prepareStatement("select * from car_goods");
rs = ps.executeQuery();
while (rs.next()) {
Goods goods = new Goods();
goods.setId(rs.getInt(1));
goods.setName(rs.getString(2));
goods.setDescribe(rs.getString(3));
goods.setPrice(rs.getInt(4));
list.add(goods);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.close(con, ps, rs);
}
return list;
}
@Override
public Goods one(int id) {
List<Goods> list = new ArrayList<Goods>();
try {
con = DBHelper.getCon();
ps = con.prepareStatement("select * from car_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.setDescribe(rs.getString(3));
goods.setPrice(rs.getInt(4));
return goods;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.close(con, ps, rs);
}
return null;
}
}
UserDaoImpl.java
package com.zking.dao.impl;
import com.zking.dao.IUserDao;
import com.zking.pojo.User;
import com.zking.util.DBHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@SuppressWarnings("all")
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 car_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;
}
}
biz包
IGoodsBiz.java
package com.zking.biz;
import com.zking.pojo.Goods;
import java.util.List;
@SuppressWarnings("all")
public interface IGoodsBiz {
List<Goods> list();
Goods one(int id);
}
IUserBiz.java
package com.zking.biz;
import com.zking.pojo.User;
@SuppressWarnings("all")
public interface IUserBiz {
User login(User user);
}
biz.impl包
GoodsBizImpl.java
package com.zking.biz.impl;
import com.zking.biz.IGoodsBiz;
import com.zking.dao.IGoodsDao;
import com.zking.dao.impl.GoodsDaoImpl;
import com.zking.pojo.Goods;
import java.util.List;
@SuppressWarnings("all")
public class GoodsBizImpl implements IGoodsBiz {
private IGoodsDao goodsDao=new GoodsDaoImpl();
@Override
public List<Goods> list() {
return goodsDao.list();
}
@Override
public Goods one(int id) {
return goodsDao.one(id);
}
}
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;
import org.apache.commons.codec.digest.DigestUtils;
@SuppressWarnings("all")
public class UserBizImpl implements IUserBiz {
private IUserDao userDao=new UserDaoImpl();
@Override
public User login(User user) {
//user 是用户给进来的
//u 是数据库中存在的
User u = userDao.login(user);
if(u==null){
return null;//account账号在数据库中查询不到记录
}
//需要将前端给我的那个用户的密码加密之后再和数据库的密码进行比较
String pwd= DigestUtils.md5Hex(user.getPassword());
if(!u.getPassword().equals(pwd)){
return null;//账号存在,但是密码不一致
}
return u;
}
}
filter包
LoginFilter.java
package com.zking.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@SuppressWarnings("all")
@WebFilter("/*") //所有的请求都会被拦截
public class LoginFilter implements Filter {
//如果登录了 正常通行
//如果没登陆 让你回到登录页面
//【req.getServletPath()】
// localhost:8080/login.jsp -> /login.jsp
// localhost:8080/index.jsp -> /index.jsp
// localhost:8080/manager.jsp -> /manager.jsp
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//有一些页面需要放行 【login.jsp】
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
//拿的是当前项目之后的路径
String path = req.getServletPath();
if (path.equals("/login.jsp")||path.equals("/login.do")) {
chain.doFilter(request, response);//放行
return;
}
//判断你是否可以通行【有没有登录:session中是否有user属性】
Object user = req.getSession().getAttribute("user");
if (user == null) {
resp.sendRedirect("login.jsp");
return;
} else {
chain.doFilter(request, response);//放行
}
}
}
servlet包
AddServlet.java
package com.zking.servlet;
import com.zking.biz.IGoodsBiz;
import com.zking.biz.impl.GoodsBizImpl;
import com.zking.pojo.Goods;
import com.zking.pojo.OrderItem;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@SuppressWarnings("all")
@WebServlet("/add.do")
public class AddServlet extends HttpServlet {
private IGoodsBiz GoodsBiz = new GoodsBizImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//购物车在哪里?
List<OrderItem> car = (List<OrderItem>) req.getSession().getAttribute("car");
//是哪件商品?需要用户带一个商品的id
int id = Integer.parseInt(req.getParameter("id"));
//购物车中已经有了,数量+1
boolean f = true;
for (OrderItem item : car) {
// item就是订单项,订单项中有一个与他对应的商品
if (item.getGoods().getId().equals(id)) {
//数量+1
item.setQuantity(item.getQuantity() + 1);
//价格需要重新计算
item.setTotal(item.getQuantity() * item.getGoods().getPrice());
f = false;
break;
}
}
//购物车中没有,添加购物车
if (f) {
//生成了订单项
OrderItem item = new OrderItem();
//根据商品的id去数据库查出这件商品
Goods one = GoodsBiz.one(id);
item.setGoods(one);
item.setQuantity(1);
item.setTotal(one.getPrice());
//添加订单项到购物车
car.add(item);
}
req.getSession().setAttribute("total", car.stream()
.mapToInt(OrderItem::getTotal)
.sum());
//返回首页
resp.sendRedirect("index.do");
}
}
ClearServlet.java
package com.zking.servlet;
import com.zking.pojo.OrderItem;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@SuppressWarnings("all")
@WebServlet("/clear.do")
public class ClearServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//购物车在哪里?
List<OrderItem> car = (List<OrderItem>)req.getSession().getAttribute("car");
//清空购物车
car.clear();
//返回首页
resp.sendRedirect("car.jsp");
}
}
DelServlet.java
package com.zking.servlet;
import com.zking.pojo.Goods;
import com.zking.pojo.OrderItem;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@SuppressWarnings("all")
@WebServlet("/del.do")
public class DelServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//购物车在哪里?
List<OrderItem> car = (List<OrderItem>)req.getSession().getAttribute("car");
//是哪件商品?需要用户带一个商品的id
int id = Integer.parseInt(req.getParameter("id"));
//购物车中已经有了,删除
OrderItem i=null;
for (OrderItem item : car) {
// item就是订单项,订单项中有一个与他对应的商品
if(item.getGoods().getId().equals(id)){
//你就是我要删除的
i=item;
break;
}
}
car.remove(i);
req.getSession().setAttribute("total",car.stream()
.mapToInt(OrderItem::getTotal)
.sum());
//返回首页
resp.sendRedirect("car.jsp");
}
}
IndexServlet.java
package com.zking.servlet;
import com.zking.biz.IGoodsBiz;
import com.zking.biz.impl.GoodsBizImpl;
import com.zking.pojo.Goods;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@SuppressWarnings("all")
@WebServlet("/index.do")
public class IndexServlet extends HttpServlet {
private IGoodsBiz goodsBiz=new GoodsBizImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//取到biz层中的商品数据的集合
List<Goods> list = goodsBiz.list();
//把数据放到index.jsp中去显示
//request【转发】 session appliction
req.setAttribute("list",list);
//只有转发才能携带请求的数据
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
LoginServlet.java
package com.zking.servlet;
import com.zking.biz.IUserBiz;
import com.zking.biz.impl.UserBizImpl;
import com.zking.pojo.Goods;
import com.zking.pojo.OrderItem;
import com.zking.pojo.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("all")
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
private IUserBiz userBiz=new UserBizImpl();
//接收用户的数据: 【post】【get】
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//参数的获取
String account = req.getParameter("account");
String password = req.getParameter("password");
User user = new User();
user.setAccount(account);
user.setPassword(password);
//去biz完成登录验证
// 表示层(servlet)->业务逻辑层(biz)->数据库访问层(dao)
User u = userBiz.login(user);
if(u==null){
resp.sendRedirect("login.jsp");
}else{
//将数据放到session中
req.getSession().setAttribute("user",u);
//为这个用户生成一个购物车
List<OrderItem> car=new ArrayList<>();
req.getSession().setAttribute("car",car);
//把总价直接放到session中
req.getSession().setAttribute("total",0);
//去到首页
resp.sendRedirect("index.do");
}
}
}
UpdServlet.java
package com.zking.servlet;
import com.zking.pojo.Goods;
import com.zking.pojo.OrderItem;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@SuppressWarnings("all")
@WebServlet("/upd.do")
public class UpdServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//购物车在哪里?
List<OrderItem> car = (List<OrderItem>)req.getSession().getAttribute("car");
//是哪件商品?需要用户带一个商品的id
int id = Integer.parseInt(req.getParameter("id"));
//获取需要改变的类型(1,-1)
int type = Integer.parseInt(req.getParameter("type"));
//购物车中已经有了,数量+1
for (OrderItem item : car) {
// item就是订单项,订单项中有一个与他对应的商品
if(item.getGoods().getId().equals(id)){
//数量+还是-
int count = item.getQuantity() + type;
if(count<1)count=1;//最少一个
if(count>5)count=5;//最多5个
item.setQuantity(count);
//价格需要重新计算
item.setTotal(item.getQuantity()*item.getGoods().getPrice());
req.getSession().setAttribute("total",car.stream()
.mapToInt(OrderItem::getTotal)
.sum());
break;
}
}
//返回首页
resp.sendRedirect("car.jsp");
}
}
显示页面
car.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<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>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>购物车界面</title>
</head>
<body>
<div class="container">
<h1>
${user.account},您好, <small>这是购物车</small>
</h1>
<h1>
<a href="index.do" class="btn btn-default">继续购买</a>
<a href="" class="btn btn-default">订单结算</a>
<a href="" class="btn btn-default">查看订单</a>
<a href="clear.do" class="btn btn-default">清空🛒</a>
</h1>
<table class="table table-bordered table-striped">
<tbody>
<tr>
<th>商品编号</th>
<th>商品名字</th>
<th>商品数量</th>
<th>商品总价</th>
<th>商品操作</th>
</tr>
<c:forEach items="${car}" var="item">
<tr>
<td>${item.goods.id}</td>
<td>${item.goods.name}</td>
<td>${item.quantity}</td>
<td>${item.total}</td>
<td>
<a href="del.do?id=${item.goods.id}" class="btn btn-default">删除</a>
<a href="upd.do?id=${item.goods.id}&type=1" class="btn btn-default">+1</a>
<a href="upd.do?id=${item.goods.id}&type=-1" class="btn btn-default">-1</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<h1>
total: ${total}
</h1>
</div>
</body>
</html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<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>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>主界面</title>
<style>
body {
padding: 20px 40px;
}
</style>
</head>
<c:if test="${list == null}">
<c:redirect url="index.do"/>
</c:if>
<body>
<h1>
${user.account},您好, <small>这是首页</small>
</h1>
<h1>
<a href="car.jsp" class="btn btn-primary" onclick="">点我去购物车🛒</a>
</h1>
<table class="table table-bordered table-striped">
<tbody>
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>商品描述</th>
<th>商品价格</th>
<th>商品操作</th>
</tr>
<c:forEach items="${list}" var="goods">
<tr>
<td>${goods.id}</td>
<td>${goods.name}</td>
<td>${goods.describe}</td>
<td>${goods.price}</td>
<td>
<a href="add.do?id=${goods.id}" class="btn btn-default">加入🚗</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<%--
login.jsp-(表单)->login.do-(登录验证)->index.do-(拿到首页需要的数据)->index.jsp 显示数据
--%>
</body>
</html>
login.jsp
%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<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>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>登录界面</title>
<style>
form {
width: 500px;
margin: auto;
}
</style>
</head>
<body class="container">
<form action="login.do" method="post">
<h1>登录</h1>
<div class="form-group">
<input name="account" class="form-control" placeholder="用户名">
</div>
<div class="form-group">
<input name="password" class="form-control" placeholder="密码">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block">登录</button>
</div>
</form>
</body>
</html>