hello,家人们,我来更知识啦!今天是用servlet来写一个小项目
目录
一.准备工作
1.需要导入5个jar包,并且导入Build Path
2.数据库建表:
用户表
订单项表
订单表
商品表
3.需要用到的Java
二.servlet版的简易购物车
User用户实体类
package com.zking.pojo;
public class User {
//用户实体类
private Integer id;
private String name;
private String pwd;
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public User() {
}
public User(Integer id, String name, String pwd) {
super();
this.id = id;
this.name = name;
this.pwd = pwd;
}
public String toString() {
return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + "]";
}
}
商品实体类
package com.zking.pojo;
public class Goods {
private Integer id;
private String name;
private String info;
private Integer 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 getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Goods() {
// TODO Auto-generated constructor stub
}
public Goods(Integer id, String name, String info, Integer price) {
super();
this.id = id;
this.name = name;
this.info = info;
this.price = price;
}
@Override
public String toString() {
return "Goods [id=" + id + ", name=" + name + ", info=" + info + ", price=" + price + "]";
}
}
订单项实体类
package com.zking.pojo;
/**
* 订单项详情表
* @author zjjt
*
*/
public class OrderItem {
private Integer id;
private Integer orderId;
private Goods goods;
private Integer quantity;
private Integer total;
public OrderItem() {
}
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;
}
public String toString() {
return "OrderItem [id=" + id + ", orderId=" + orderId + ", goods=" + goods + ", quantity=" + quantity
+ ", total=" + total + "]";
}
}
用户的三层架构:
(com.xxx.dao)IUserDao
package com.zking.dao;
import com.zking.pojo.User;
public interface IUserDao {
User login(User user);
}
(com.xxx.daompl) UserDaoImpl
package com.zking.daoimpl;
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.util.DBHelper;
public class UserDaoImpl implements IUserDao{
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
//登录验证
public User login(User user) {
try {
con=DBHelper.getCon();
ps=con.prepareStatement("select * from car_user where c_name=?");
ps.setString(1,user.getName());
rs=ps.executeQuery();
if(rs.next()) {
User u=new User();
u.setId(rs.getInt(1));
u.setName(rs.getString(2));
u.setPwd(rs.getString(3));
return u;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.getClose(con, ps, rs);
}
return null;
}
}
(com.xxx.biz) IUserBiz
package com.zking.biz;
import com.zking.pojo.User;
public interface IUserBiz {
User login(User user);
}
(com.xxx.bizimpl) 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.daoimpl.UserDaoImpl;
import com.zking.pojo.User;
public class UserBizImpl implements IUserBiz{
private IUserDao userdao=new UserDaoImpl();
public User login(User user) {
User u=userdao.login(user);
if(u==null) {
return null; //name账号在数据库中查找不到
}
//需要将前端给我的那个密码加密之后在和数据库的密码进行比较
String pwd=DigestUtils.md5Hex(user.getPwd());
if(u.getPwd().equals(pwd)) {
return null;//账号存在,但是密码不一样
}
return null;
}
}
商品的三层架构:
(com.xxx.dao) IGoodsDao
package com.zking.dao;
import java.util.List;
import com.zking.pojo.Goods;
public interface IGoodsDao {
List<Goods> list();
Goods one(Integer id);
}
(com.xxx.daoimpl) UserDaoImpl
package com.zking.daoimpl;
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;
public class GoodsDaoImpl implements IGoodsDao{
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
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 g=new Goods();
g.setId(rs.getInt(1));
g.setName(rs.getString(2));
g.setInfo(rs.getString(3));
g.setPrice(rs.getInt(4));
list.add(g);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.getClose(con, ps, rs);
}
return list;
}
public Goods one(Integer id){
try {
con=DBHelper.getCon();
ps=con.prepareStatement("select * from car_goods where g_id=?");
ps.setInt(1, id);
rs=ps.executeQuery();
if(rs.next()) {
Goods g=new Goods();
g.setId(rs.getInt(1));
g.setName(rs.getString(2));
g.setInfo(rs.getString(3));
g.setPrice(rs.getInt(4));
return g;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.getClose(con, ps, rs);
}
return null;
}
}
(com.xxx.biz) IGoodsBiz
package com.zking.biz;
import java.util.List;
import com.zking.pojo.Goods;
public interface IGoodsBiz {
List<Goods> list();
Goods one(Integer id);
}
(com.xxx.bizimpl) GoodsBizImpl
package com.zking.biz.impl;
import java.util.List;
import com.zking.biz.IGoodsBiz;
import com.zking.dao.IGoodsDao;
import com.zking.daoimpl.GoodsDaoImpl;
import com.zking.pojo.Goods;
public class GoodsBizImpl implements IGoodsBiz{
private IGoodsDao dao=new GoodsDaoImpl();
public List<Goods> list(){
return dao.list();
}
public Goods one(Integer id) {
return dao.one(id);
}
}
login.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body class="container">
<form action="login.do" method="post">
<h1>登录</h1>
<div class="form-group">
<input name="username" class="form-control" placeholder="请输入用户名">
</div>
<div class="form-group">
<input name="userpwd" class="form-control" placeholder="请输入密码">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block">登录</button>
</div>
</form>
</body>
</html>
(com.xxx.servlet) 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();
//接收用户数据
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 name=req.getParameter("username");
String pwd=req.getParameter("userpwd");
//去biz完成登录验证
//表示层调用业务逻辑层,业务逻辑层调用数据库访问层
User user=new User();
user.setName(name);
user.setPwd(pwd);
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");
}
}
}
(com.xxx.filter) 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;
/**
*
* @author zjjt
*
*/
@WebFilter("/*") //跟我这个项目有关的所有请求都要经过我的过滤
public class LoginFilter implements Filter {
//如果登录了,正常通行
//如果没登陆,让你回到登录页面
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();//-》login.jsp
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);//放行
}
}
}
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="bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
<script src="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>
<body>
<h1>
${user.name} 您好, <small>这是首页</small>
</h1>
<h1>
<a href="car.jsp" class="btn btn-primary" onclick="location.href='myCar.jsp'">点我去购物车🛒</a>
</h1>
${car}
<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.info}</td>
<td>${goods.price}</td>
<td>
<a href="add.do?id="${goods.id}" class="btn btn-default">加入🚗</a>
</td>
</tr>
</c:forEach>
</tbody></table>
</body></html>
(com.xxx.servlet) 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();
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//取到biz层中商品数据的集合
List<Goods> list=goodsbiz.list();
//把数据放到index.jsp中去显示(用request比较合适)用请求存数据必须使用转发
req.setAttribute("list", list);
//只有转发才能携带请求的数据
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
}
(com.xxx.servlet) AddServlet
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;
import com.zking.pojo.OrderItem;
/**
*
* @author zjjt
*
*/
@WebServlet("/add.do")
public class AddServlet extends HttpServlet{
private IGoodsBiz biz=new GoodsBizImpl();
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//购物车在哪里?
List<OrderItem> car=(List<OrderItem>)req.getSession().getAttribute("car");//拿购物车
//是哪件商品?需要用户在index.jsp界面带一个id过来
int id=Integer.parseInt(req.getParameter("id"));
//有两种情况,一.购物车中已经有了,就直接数量加1
boolean f=false;
for(OrderItem item:car) {
//item就是订单项,订单项中有一个与他对应的商品
if(item.getGoods().getId().equals(id)) {
//如果id相同,就说明在购物车里已经有了一个一样的商品了,数量+1
item.setQuantity(item.getQuantity()+1);
//重新计算价格
item.setTotal(item.getQuantity()*item.getGoods().getPrice());
Integer total=(Integer)req.getSession().getAttribute("total");
total+=item.getGoods().getPrice();
req.getSession().setAttribute("total",total);
f=true;
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);
Integer total=(Integer)req.getSession().getAttribute("total");
total+=one.getPrice();
req.getSession().setAttribute("total",total);
}
//返回首页
resp.sendRedirect("index.jsp");
}
}
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 charset="UTF-8">
<title>我的购物车</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>
<c:if test="${list==null}">
<c:redirect url="index.do"></c:redirect>
</c:if>
<body>
<div class="container">
<h1>
${user.name}您好, <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 hred="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>
<h2>sum:${total}</h2>
</div>
</body></html>
(com.xxx.servlet) ClearServlet 清空购物车的功能
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.OrderItem;
/**
*
* @author zjjt
*
*/
@WebServlet("/clear.do")
public class ClearServlet extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
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");
}
}
(com.xxx.servlet) 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.biz.IGoodsBiz;
import com.zking.biz.impl.GoodsBizImpl;
import com.zking.pojo.Goods;
import com.zking.pojo.OrderItem;
/**
*
* @author zjjt
*
*/
@WebServlet("/del.do")
public class DelServlet extends HttpServlet{
private IGoodsBiz biz=new GoodsBizImpl();
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//购物车在哪里?
List<OrderItem> car=(List<OrderItem>)req.getSession().getAttribute("car");//拿购物车
//是哪件商品?需要用户在index.jsp界面带一个id过来
int id=Integer.parseInt(req.getParameter("id"));
//购物车已经有的时候,就删除
OrderItem i=null;
for(OrderItem item:car) {
//item就是订单项,订单项中有一个与他对应的商品
if(item.getGoods().getId().equals(id)) {
//你就是我要删除的
i=item;
Integer total=(Integer)req.getSession().getAttribute("total");
total+=item.getTotal();
req.getSession().setAttribute("total",total);
break;
}
}
car.remove(i);
//返回首页
resp.sendRedirect("car.jsp");
}
}
给商品数量做加减的操作 (com.xxx.servlet) updServlet
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;
import com.zking.pojo.OrderItem;
/**
*
* @author zjjt
*
*/
@WebServlet("/upd.do")
public class updServlet extends HttpServlet {
private IGoodsBiz biz=new GoodsBizImpl();
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//购物车在哪里?
List<OrderItem> car=(List<OrderItem>)req.getSession().getAttribute("car");//拿购物车
//是哪件商品?需要用户在index.jsp界面带一个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)) {
//数量+还是-,根据type来决定
int count=item.getQuantity()+type;
if(count>1) {
item.setQuantity(count);
//重新计算价格
item.setTotal(item.getQuantity()*item.getGoods().getPrice());
Integer total=(Integer)req.getSession().getAttribute("total");
total+=type*item.getGoods().getPrice();
req.getSession().setAttribute("total",total);
}
break;
}
}
//返回首页
resp.sendRedirect("car.jsp");
}
}
今天的代码就分享到这里啦~,下期见!
今天也要记得微笑呀.