前言:这一篇我会使用servlet,EL,JSTL,三层架构写一个简单的购物车项目,内容比较多,这只是第一部分,只有登陆,首页数据显示和商品添加到购物车的功能。还有一部分功能的代码我会写在下一篇博客里,感兴趣的朋友们可以看一看,也希望大家可以为我提一点建议(●'◡'●)。
目录
一.Filter
二. 数据库代码
三.项目代码
1.业务逻辑层代码的编写
biz(接口)代码
biz.impl代码
2.数据库访问层代码的编写
dao(接口)代码
dao.impl代码
3.filter的使用
4.实体类(pojo)代码
5.表示层代码的编写
6.数据库帮助类代码编写
7.jsp界面代码
a.主页面代码(index.jsp)
b.购物车代码(car.jsp)
c.登陆代码(login.jsp)
在这个项目里我会运用到Filter,Filter称之为过滤器,是servlet中最实用的技术,web开发人员通过Filter技术,对web服务器所管理的资源(jsp,servlet,静态图片或者静态html文件)进行拦截,从而实现一些特殊的功能。简单说就是过滤从服务端向服务器发送请求的。
这是过滤器在我项目里的作用:
这是我建的表:
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, '[email protected]', 'ff9830c42660c1dd1942844f8069b74a');-- root123
insert into car_user
values (2, '[email protected]', 'e10adc3949ba59abbe56e057f20f883e');-- 123456
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);
commit
IGoodsBiz:
List list();
IUserBiz:
User login(User user);
GoodsBizImpl:
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 list() {
return goodsDao.list();
}
@Override
public Goods one(int id) {
return goodsDao.one(id);
}
}
UserBizImpl:
package com.zking.biz.impl;
import org.apache.commons.codec.digest.DigestUtils;
import com.zking.biz.IUserBiz;
import com.zking.dao.IUserDao;
import com.zking.dao.impl.UserDaoImpl;
import com.zking.pojo.User;
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;
}
}
IGoodsDao:
List list();
Goods one(int id);
IUserDao:
User login(User user);
GoodsDaoImpl:
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 list() {
List 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);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.close(con, ps, rs);
}
return list;
}
@Override
public Goods one(int id) {
List list = new ArrayList();
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:
package com.zking.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.zking.dao.IUserDao;
import com.zking.pojo.User;
import com.zking.utli.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();
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;
}
}
LoginFilter:
package com.zking.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.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 {
//有一些页面需要放行【login.do】
//强转
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);//放行
}
}
}
User:
package com.zking.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
public class User {
private int id;
private String account;
private String password;
public int getId() {
return id;
}
public void setId(int 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(int id, String account, String password) {
super();
this.id = id;
this.account = account;
this.password = password;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "User [id=" + id + ", account=" + account + ", password=" + password + "]";
}
}
Goods:
package com.zking.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
public class Goods {
private int id;
private String name;
private String describe;
private int price;
public int getId() {
return id;
}
public void setId(int 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 int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Goods(int id, String name, String describe, int price) {
super();
this.id = id;
this.name = name;
this.describe = describe;
this.price = price;
}
public Goods() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Goods [id=" + id + ", name=" + name + ", describe=" + describe + ", price=" + price + "]";
}
}
OrderItem:
package com.zking.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
public class OrderItem {
private Integer id;
private Integer orderId;
private Goods goods;
private Integer quantity;
private Integer 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;
}
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 OrderItem() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "OrderItem [id=" + id + ", orderId=" + orderId + ", goods=" + goods + ", quantity=" + quantity
+ ", total=" + total + "]";
}
}
AddServlet(商品添加进购物车):
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;
@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 car = (List) 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()==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(清空购物车):
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;
@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 car = (List)req.getSession().getAttribute("car");
//清空购物车
car.clear();
//返回首页
resp.sendRedirect("car.jsp");
}
}
DelServlet(从购物车中删除商品):
package com.zking.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.zking.pojo.Goods;
import com.zking.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 car = (List) req.getSession().getAttribute("car");
//是哪件商品?需要用户带一个商品的id
int id = Integer.parseInt(req.getParameter("id"));
//购物车中已经有了,删除
OrderItem i = null;
for (OrderItem item : car) {
// item就是订单项,订单项中有一个与他对应的商品
if (item.getGoods().getId()==id) {
//是需要删除的
i = item;
break;
}
}
car.remove(i);
//返回首页
resp.sendRedirect("car.jsp");
}
}
IndexServlet(主页面数据显示):
package com.zking.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.zking.biz.IGoodsBiz;
import com.zking.biz.impl.GoodsBizImpl;
import com.zking.pojo.Goods;
@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 list = goodsBiz.list();
//把数据放到index.jsp中去显示
//把数据放到请求里
req.setAttribute("list", list);
//只有转发才能携带请求的数据
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
}
LoginServlet(登陆处理):
package com.zking.servlet;
import java.io.IOException;
import java.util.ArrayList;
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.zking.biz.IUserBiz;
import com.zking.biz.impl.UserBizImpl;
import com.zking.pojo.OrderItem;
import com.zking.pojo.User;
/**
*
* @author zjjt
*实现登录功能
*/
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet{
private IUserBiz userBiz = new UserBizImpl();
//接收用户数据【get 】【post】
@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 car = new ArrayList<>();
req.getSession().setAttribute("car", car);
//把总价直接放到session中
req.getSession().setAttribute("total",0);
//去首页
resp.sendRedirect("index.do");
}
}
}
UpdServlet(购物车商品数量加减):
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;
/**
* @author harrison
* @version v1.0
* @create 2022-04-25@星期一
* @Description {自定义描述}
**/
@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 car = (List)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()==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");
}
}
util代码( DBHelper):
package com.zking.utli;
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","sa123");
} 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.print(DBHelper.getCon());
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
主界面
${user.account},您好, 这是首页
点我去购物车
商品编号
商品名称
商品描述
商品价格
商品操作
${goods.id}
${goods.name}
${goods.describe}
${goods.price}
加入
<%--
login.jsp-(表单)->login.do-(登录验证)->index.do-(拿到首页需要的数据)->index.jsp 显示数据
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
我的购物车
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
登录界面
剩下功能,运行效果和界面我会写在下一篇博客里,感兴趣的朋友们一键三连呦(~ ̄▽ ̄)~,也希望各位大佬们能给我提一点建议。