本项目相关
开发软件:支持web开发的eclipse
开发模式:三层架构
将java代码从jsp文件中分离:使用Servlet技术实现
访问权限:使用Filter过滤器实现
项目目录展示
项目的编写
一,数据库帮助类的编写
package com.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 数据库帮助类
*/
public class DBHelper {
//加载驱动
static{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//定义链接字符串
private static final String URL="jdbc:oracle:thin:@localhost:1521:orcl";
//获得链接
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();
}
}
public static void main(String[] args) {
System.out.println(DBHelper.getCon());
}
}
二、实体类的编写
1.User用户实体类
package com.pojo;
import java.io.Serializable;
/**
* 用户实体类
*/
public class User implements Serializable {
private Integer id;
private String account;
private String password;
public User() {
// TODO Auto-generated constructor stub
}
public User(Integer id, String account, String password) {
super();
this.id = id;
this.account = account;
this.password = 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;
}
@Override
public String toString() {
return "User [id=" + id + ", account=" + account + ", password=" + password + "]";
}
}
2.Goods商品实体类
package com.pojo;
import java.io.Serializable;
/**
* 商品实体类
*/
public class Goods implements Serializable {
private Integer id;
private String name;
private String describe;
private Integer price;
public Goods() {
// TODO Auto-generated constructor stub
}
public Goods(Integer id, String name, String describe, Integer price) {
super();
this.id = id;
this.name = name;
this.describe = describe;
this.price = price;
}
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 String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Goods [id=" + id + ", name=" + name + ", describe=" + describe + ", price=" + price + "]";
}
}
3.OrderItem订单项实体类
package com.pojo;
import java.io.Serializable;
/**
* 订单项实体类
*/
public class OrderItem implements Serializable {
private Integer id;
private Integer orderId;
private Goods goods;
private Integer quantity;
private Integer total;
public OrderItem() {
// TODO Auto-generated constructor stub
}
public OrderItem(Integer id, Integer orderId, Goods goods, Integer quantity, Integer total) {
super();
this.id = id;
this.orderId = orderId;
this.goods = goods;
this.quantity = quantity;
this.total = total;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
@Override
public String toString() {
return "OrderItem [id=" + id + ", orderId=" + orderId + ", goods=" + goods + ", quantity=" + quantity
+ ", total=" + total + "]";
}
}
三、jsp界面的编写
login.jsp 登录界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="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>
<form action="login.do" method="post">
<h1>登录</h1>
<div class="form-group">
<input name="uname" class="form-control" placeholder="用户名">
</div>
<div class="form-group">
<input name="uaddress" class="form-control" placeholder="密码">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block">登录</button>
</div>
</form>
</body>
</html>
index.jsp 主界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ 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="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">
<style>
body {
padding: 20px 40px;
}
</style>
</head>
<c:if test="${list==null}">
<c:redirect url="index.do"></c:redirect>
</c:if>
<body>
<h1>
${user.account}您好, <small>这是首页</small>
</h1>
<h1>
<a href="car.jsp" class="btn btn-primary">点我去购物车🛒</a>
</h1>
<table class="table table-bordered table-striped">
<tbody>
<tr>
<td>商品编号</td>
<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>
</a>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
car.jsp 购物车界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ 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="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="order.jsp"
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>
四、Filter过滤器在项目中的运用
package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter("/*") // 所有的请求都会被拦截
public class LoginFilter implements Filter {
// 如果登录了 正常通行
// 如果没登陆 让你回到登录页面
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String path = req.getServletPath();
// System.out.println(path);
if (path.equals("/login.jsp") || path.equals("/login.do")) {// 所有页面都被拦截了,但登录页面可以进
chain.doFilter(request, response);// 放行
return;// 每做完一个操作中断代码,防止往下运行
}
// 判断你是否登录
Object user = req.getSession().getAttribute("user");
if (user == null) {
resp.sendRedirect("login.do");// 重定向
return;
} else {
chain.doFilter(request, response);
}
}
}
这里Filter导包导入的是下图的第一个
五、表示层的编写
!:之前的表示层都是doXxx.jsp界面中的,但是这期项目中已经实现了java代码从jsp文件的分离,使用到的就是Servlet技术
1.LoginServlet.jsp的编写
package com.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.security.auth.message.callback.PrivateKeyCallback.Request;
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 com.biz.IUserBiz;
import com.biz.impl.UserBizImpl;
import com.pojo.OrderItem;
import com.pojo.User;
/**
* 实现登录功能
*/
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
// 从前端得到数据:request
// 将数据返回前端:response
private IUserBiz biz = new UserBizImpl();
@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("uname");
String password = req.getParameter("uaddress");
User user = new User();
user.setAccount(account);
user.setPassword(password);
// 表示层(servlet)->业务逻辑层(biz)->数据库访问层(dao)
User u = biz.login(user);
if (u == null) {
resp.sendRedirect("login.jsp");
} else {
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");
}
}
}
2.IndexServlet.jsp的编写
package com.servlet;
import java.io.IOException;
import java.util.List;
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 com.biz.IGoodsBiz;
import com.biz.impl.GoodsBizImpl;
import com.pojo.Goods;
/**
* 实现主界面的处理功能-表示层
*/
@WebServlet("/index.do")
public class IndexServlet extends HttpServlet {
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<Goods> list = goodsBiz.list();
req.setAttribute("list", list);// 可以方便从list中拿到商品id
// 转发:可以携带请求数据
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
}
3.AddServlet.jsp的编写
package com.servlet;
import java.io.IOException;
import java.util.List;
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 com.biz.IGoodsBiz;
import com.biz.impl.GoodsBizImpl;
import com.pojo.Goods;
import com.pojo.OrderItem;
/**
* 处理增加购物车商品的功能
*/
@WebServlet("/add.do")
public class AddServlet extends HttpServlet {
private IGoodsBiz biz = 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");
// index传来的商品id
int id = Integer.parseInt(req.getParameter("id"));
// 购物车中已经有了,数量+1
boolean f = true;
for (OrderItem item : car) {
if (item.getGoods().getId().equals(id)) {
item.setQuantity(item.getQuantity() + 1);
// 设置一行商品中的总价
item.setTotal(item.getQuantity() * item.getGoods().getPrice());
f = false;
break;// 退出循环
}
}
// 购物车中没有,添加购物车
if (f) {
// 生成了订单项
OrderItem item = new OrderItem();
// 根据商品的id去数据库查出这件商品
Goods one = biz.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");
}
}
4.DelServlet.jsp的编写
package com.servlet;
import java.io.IOException;
import java.util.List;
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 com.pojo.OrderItem;
/**
* 处理删除购物车中的一行商品
*/
@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");
int id = Integer.parseInt(req.getParameter("id"));
// 购物车中已经有了,删除
OrderItem i = null;
for (OrderItem item : car) {
if (item.getGoods().getId().equals(id)) {
i = item;
}
}
car.remove(i);
req.getSession().setAttribute("total", car.stream().mapToInt(OrderItem::getTotal).sum());
resp.sendRedirect("car.jsp");
}
}
5.UpdServlet.jsp的编写
package com.servlet;
import java.io.IOException;
import java.util.List;
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 com.pojo.OrderItem;
/**
* 处理修改购物车商品的数量
*/
@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");
int id = Integer.parseInt(req.getParameter("id"));
int type = Integer.parseInt(req.getParameter("type"));
for (OrderItem item : car) {
if (item.getGoods().getId().equals(id)) {
// + -
int count = item.getQuantity() + type;
if (count < 1)
count = 1;
if (count > 5)
count = 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");
}
}
6.ClearServlet.jsp的编写
package com.servlet;
import java.io.IOException;
import java.util.List;
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 com.pojo.Goods;
import com.pojo.OrderItem;
/**
* 处理清空购物车功能
*/
@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<Goods> car = (List<Goods>) req.getSession().getAttribute("car");
car.clear();
req.getSession().setAttribute("total", 0);
resp.sendRedirect("car.jsp");
}
}
六、业务逻辑层的编写
1.IUserBiz与UserBizImpl的编写
package com.biz;
import java.util.List;
import com.pojo.Goods;
/**
* 商品业务逻辑层接口
*/
public interface IGoodsBiz {
List<Goods> list();
Goods one(int id);
}
package com.biz.impl;
import org.apache.commons.codec.digest.DigestUtils;
import com.biz.IUserBiz;
import com.dao.IUserDao;
import com.dao.impl.UserDaoImpl;
import com.pojo.User;
/**
* 用户的业务逻辑层
*/
public class UserBizImpl implements IUserBiz{
private IUserDao dao=new UserDaoImpl();
@Override
public User login(User user) {
User u=dao.login(user);
if(u==null) {//没有在数据库中查询到
return null;
}
//如果在数据库中查询到就将用户输入的密码加密
String pwd = DigestUtils.md5Hex(user.getPassword());
if(!u.getPassword().equals(pwd)) {
System.out.println("密码错误");
return null;
}
return u;//不为空并且和数据库密码一致
}
}
2.IGoodsBiz与GoodsBizImpl的编写
package com.biz;
import java.util.List;
import com.pojo.Goods;
/**
* 商品业务逻辑层接口
*/
public interface IGoodsBiz {
List<Goods> list();
Goods one(int id);
}
package com.biz.impl;
import java.util.List;
import com.biz.IGoodsBiz;
import com.dao.IGoodsDao;
import com.dao.impl.GoodsDaoImpl;
import com.pojo.Goods;
/**
* 商品业务逻辑层
*/
public class GoodsBizImpl implements IGoodsBiz{
private IGoodsDao dao=new GoodsDaoImpl();
@Override
public List<Goods> list() {
return dao.list();
}
@Override
public Goods one(int id) {
return dao.one(id);
}
}
七、数据库访问层的编写
1.IUserDao与UserDaoImpl的编写
package com.dao;
import com.pojo.User;
/**
* 用户的数据库访问层接口
*/
public interface IUserDao {
//登录方法
User login(User user);
}
package com.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.dao.IUserDao;
import com.pojo.User;
import com.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 car_user where account=?");
ps.setString(1, user.getAccount());
rs=ps.executeQuery();
if(rs.next()) {
User u=new User();//数据库中的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.IGoodsDao与GoodsDaoImpl的编写
package com.dao;
import java.util.List;
import com.pojo.Goods;
/**
* 商品数据库服务层接口
*/
public interface IGoodsDao {
List<Goods> list();
Goods one(int id);
}
package com.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.dao.IGoodsDao;
import com.pojo.Goods;
import com.util.DBHelper;
/**
* 商品数据库服务层
*/
public class GoodsDaoImpl implements IGoodsDao{
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
@Override
public List<Goods> list() {
//需要一个集合去返回
List<Goods> list=new ArrayList<>();
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);
}
System.out.println(list+"1");
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.close(con, ps, rs);
}
System.out.println(list+"2");
return list;
}
@Override
public Goods one(int id) {
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;
}
}