目录
前言:
上篇给大家介绍了一下关于Servlet的一些知识及用法,今天就来给大家分享一下运用Servlet知识来创作的一个小项目吧。
项目简介:
1.登陆界面
做了简单的登陆验证处理,当账号和密码错误时就完成不了界面的跳转
2.主界面
主界面会显示登陆进来的用户名,购物车里会显示商品,点击上方的蓝色按钮,就可以跳转到购物车界面,点击加入购物车的按钮就可以把主页的商品添加至购物车中。
3.购物车界面
购物车界面会根据商品的价格计算总价,右边的按钮可以对商品的数量进行操作,增加或者减少,当商品数量小于1时,数量会默认为1,每种商品限定5件。点击删除按钮可以直接删除该商品。
代码详解:
先在项目中建立如下的包:
com.zking.biz包
IGoodsBiz.java:
package com.zking.biz;
import com.zking.pojo.Goods;
import java.util.List;
public interface IGoodsBiz {
List<Goods> list();
Goods one(int id);
}
IUserBiz.java:
package com.zking.biz;
import com.zking.pojo.User;
public interface IUserBiz {
User login(User user);
}
com.zking.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;
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;
public class UserBizImpl implements IUserBiz {
private IUserDao userDao=new UserDaoImpl();
@Override
public User login(User user) {
User u = userDao.login(user);
if(u==null){
return null;
}
String pwd= DigestUtils.md5Hex(user.getPassword());
if(!u.getPassword().equals(pwd)){
return null;
}
return u;
}
}
com.zking.dao包
IGoodsDao.java:
package com.zking.dao;
import com.zking.pojo.Goods;
import java.util.List;
public interface IGoodsDao {
List<Goods> list();
Goods one(int id);
}
IUserDao.java:
package com.zking.dao;
import com.zking.pojo.User;
public interface IUserDao {
User login(User user);
}
com.zking.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;
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;
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;
}
}
com.zking.filter包
LoginFilter.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;
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;
}
}
com.zking.pojo包
Goods.java:
package com.zking.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
public class Goods {
private Integer id;
private String name;
private String describe;
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 getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
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 describe, Integer price) {
super();
this.id = id;
this.name = name;
this.describe = describe;
this.price = price;
}
}
OrderItem.java:
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() {
// 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;
}
}
User.java:
package com.zking.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
public class User {
private Integer id;
private String account;
private String 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;
}
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;
}
}
com.zking.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;
@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");
int id = Integer.parseInt(req.getParameter("id"));
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();
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;
@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;
@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;
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;
@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 {
List<Goods> list = goodsBiz.list();
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;
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
private IUserBiz userBiz=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("account");
String password = req.getParameter("password");
User user = new User();
user.setAccount(account);
user.setPassword(password);
User u = userBiz.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);
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;
@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");
}
}
com.zking.util包
DBHelper:
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", "tiger");
} 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();
}
}
}
Web部分:
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>