**个人笔记*/
目录
目录
1.软件整体
1.软件整体
2.依赖jar包
3.数据库连接池
#驱动加载
driverClassName=com.mysql.cj.jdbc.Driver
#注册驱动
url=jdbc:mysql://localhost:3306/day17?characterEncoding=utf-8
#连接数据库的用户名
username=root
#连接数据库的密码
password=123
#属性类型的字符串,通过别名的方式配置扩展插件, 监控统计用的stat 日志用log4j 防御sql注入:wall
filters=stat
#初始化时池中建立的物理连接个数。
initialSize=5
#最大的可活跃的连接池数量
maxActive=300
#获取连接时最大等待时间,单位毫秒,超过连接就会失效。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降, 如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
maxWait=10000
#连接回收器的运行周期时间,时间到了清理池中空闲的连接,testWhileIdle根据这个判断
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
#用来检测连接是否有效的sql,要求是一个查询语句。
validationQuery=SELECT 1
#建议配置为true,不影响性能,并且保证安全性。 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis, 执行validationQuery检测连接是否有效。
testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。设置为false
testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能,设置为false
testOnReturn=false
#是否缓存preparedStatement,也就是PSCache。
poolPreparedStatements=false
#池中能够缓冲的preparedStatements语句数量
maxPoolPreparedStatementPerConnectionSize=200
4.制作JDBCUtils
package Util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/*
* jdbc工具类
* */
public class JDBCUtils {
//创建一个数据库连接池对象
private static DataSource dataSource;
//定义静态加载代码块
static {
try {
//加载配置文件
Properties properties = new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("Druid.properties");
properties.load(is);
//初始化数据库链接池对象
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接池对象
public static DataSource getDataSource() {
return dataSource;
}
//获取Connection对象
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
5.登录页面(jsp)
<%--
Created by IntelliJ IDEA.
User: Yanghao2
Date: 2021/11/1
Time: 15:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>管理员登录</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
</script>
<script>
/**
* 验证码的函数,保证回退页面的验证码不重复
* */
function refreshCode() {
vcode = document.getElementById("vcode");
vcode.src = "${pageContext.request.contextPath}/checkCode?time="+ new Date().getTime();
}
</script>
</head>
<body>
<%--登陆表单的模块--%>
<div class="container" style="width: 400px;">
<h3 style="text-align: center;">管理员登录</h3>
<%--设置动态路径将数据以”post“方式提交到”loginServlet“页面--%>
<form action="${pageContext.request.contextPath}/loginServlet" method="post">
<%--用户名表单--%>
<div class="form-group" >
<label for="user">用户名:</label>
<input type="text" name="username" class="form-control" id="user" placeholder="请输入用户名"/>
</div>
<%--密码表单--%>
<div class="form-group">
<label for="password">密码:</label>
<input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/>
</div>
<%--验证码表单--%>
<div class="form-inline">
<label for="vcode">验证码:</label>
<input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/>
<a href="javascript:refreshCode()"><img src="${pageContext.request.contextPath}/checkCode" title="看不清点击刷新" id="vcode"/></a>
</div>
<hr/>
<div class="form-group" style="text-align: center;">
<input class="btn btn btn-primary" type="submit" value="登录">
</div>
</form>
<!-- 出错显示的信息框 -->
<c:if test="${not empty sessionScope.prompt}">
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" >
<span>×</span></button>
<strong>${sessionScope.prompt}</strong>
<strong>${requestScope.login_msg}</strong>
</div>
</c:if>
</div>
</body>
</html>
5.1登陆页面的后台
package web.Servlet;
import Service.UserServiceImpl.UserServiceImpl;
import com.mysql.cj.xdevapi.Session;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* 登陆页面
* */
/*新建控制器对象*/
UserServiceImpl userService = new UserServiceImpl();
/*设置编码格式*/
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
/*创建session对象*/
HttpSession session = request.getSession();
/*用session服务器内获取验证码对象*/
String checkCode_server = (String) session.getAttribute("CHECKCODE_SERVER");
/*获取完删除验证码以保证回退页面的验证码唯一性*/
session.removeAttribute("CHECKCODE_SERVER");
/*获取验证码输入框的内容*/
String verifyCode = request.getParameter("verifycode");
/*先判断验证码的正确性*/
if (checkCode_server != null && checkCode_server.equals(verifyCode) ) {
/*使用JAVABean将表单封装*/
Map<String, String[]> parameterMap = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
/*使用控制器的Login方法传递一个封装后的user接受一个对比后的user*/
User login = userService.Login(user);
/*如果没有查到对应的用户名或密码会返回null,如果为null则判定账户密码错误。
* 如果非空则跳转index页面,并将用户的User对象传递过去*/
if (login == null) {
session.setAttribute("prompt","账户或密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request,response);
} else {
session.setAttribute("login",login);
request.getRequestDispatcher("/index.jsp").forward(request,response);
}
/*验证码不正确的处理方法*/
}else {
session.setAttribute("prompt","验证码错误!");
request.getRequestDispatcher("/login.jsp").forward(request,response);
session.removeAttribute("checkNull");
}
}
}
5.2 验证码的制作
package web.Servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 验证码
*/
@WebServlet("/checkCode")
public class CheckCodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
//服务器通知浏览器不要缓存
response.setHeader("pragma","no-cache");
response.setHeader("cache-control","no-cache");
response.setHeader("expires","0");
//在内存中创建一个长80,宽30的图片,默认黑色背景
//参数一:长
//参数二:宽
//参数三:颜色
int width = 80;
int height = 30;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//获取画笔
Graphics g = image.getGraphics();
//设置画笔颜色为灰色
g.setColor(Color.GRAY);
//填充图片
g.fillRect(0,0, width,height);
//产生4个随机验证码,12Ey
String checkCode = getCheckCode();
//将验证码放入HttpSession中
System.out.println(checkCode);
request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);
//设置画笔颜色为黄色
g.setColor(Color.YELLOW);
//设置字体的小大
g.setFont(new Font("黑体",Font.BOLD,24));
//向图片上写入验证码
g.drawString(checkCode,15,25);
//将内存中的图片输出到浏览器
//参数一:图片对象
//参数二:图片的格式,如PNG,JPG,GIF
//参数三:图片输出到哪里去
ImageIO.write(image,"PNG",response.getOutputStream());
}
/**
* 产生4位随机字符串
*/
private String getCheckCode() {
String base = "0123456789ABCDEFGabcdefg";
int size = base.length();
Random r = new Random();
StringBuffer sb = new StringBuffer();
for(int i=1;i<=4;i++){
//产生0到size-1的随机值
int index = r.nextInt(size);
//在base字符串中获取下标为index的字符
char c = base.charAt(index);
//将c放入到StringBuffer中去
sb.append(c);
}
return sb.toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
5.3 UserBean的制作(用于封装数据)
package domain;
/*
* UserBean
* */
public class User {
private int id ;
private String name;
private String gender;
private int age;
private String address;
private String qq;
private String email;
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
", address='" + address + '\'' +
", qq='" + qq + '\'' +
", email='" + email + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
5.4 登录成功后的页面(JSP)
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>首页</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<%--页面主体--%>
<div align="center">
<H3>${sessionScope.login.name},欢迎您!</H3>
<a
href="${pageContext.request.contextPath}/findUserByPageServlet" style="text-decoration:none;font-size:33px">查询所有用户信息
</a>
<hr>
<a href="${pageContext.request.contextPath}/exitUserServlet">
退出登录
</a>
</div>
</body>
</html>
6.数据展示
5.1 默认显示分页查询的后台
package web.Servlet;
import Service.UserService;
import Service.UserServiceImpl.UserServiceImpl;
import domain.PageBean;
import domain.User;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@WebServlet("/findUserByPageServlet")
public class FindUserByPageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**设置编码*/
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
/*获取当前页和显示条目数的数据*/
String _currentPage = request.getParameter("currentPage");
String _rows = request.getParameter("rows");
/**创建控制器对象*/
UserService userService = new UserServiceImpl();
/**
*将表单提交的内容存入Map集合
* 用于复杂查询功能
* */
Map<String, String[]> condition = request.getParameterMap();
/**
* 应对页码溢出的程序健壮性判断
* */
if (_currentPage == null || "".equals(_currentPage)) {
_currentPage = "1";
}
if (_rows == null || "".equals(_rows)) {
_rows = "5";
}
/**
* 调用控制器
* @param _currentPage 当前页码 ,
* @param _rows 查询与当前页显示条目数,
* @param condition 复杂查询的封装后对象
* */
PageBean<User> userByPage = userService.findUserByPage(_currentPage, _rows,condition);
/**
* 设置共享对象
* @param userByPage 分页查询后的User对象
* @param Condition 复杂查询的参数
* */
request.setAttribute("userByPage",userByPage);
request.setAttribute("condition",condition);
/**
* 页面转发至list.jsp
* @param list.jsp 数据展示页面
* */
request.getRequestDispatcher(request.getContextPath()+"/list.jsp").forward(request,response);
}
}
6.2 数据展示的前端页面(JSP)
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<!-- 使用Edge最新的浏览器的渲染方式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
width: 默认宽度与设备的宽度相同
initial-scale: 初始的缩放比,为1:1 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>用户信息管理系统</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="js/bootstrap.min.js"></script>
<script>
/**
* 单项删除的函数,主要做删除前提示功能
* @param id 要删除的数据的ID
* @param name 要删除的数据的Name属性
* */
function deleteUser(id , name) {
if(confirm("您确定要删除"+name+"的信息吗?")) {
/**
* 调用后台的删除功能
* */
location.href = "${pageContext.request.contextPath}/deleteUser?id=" + id;
}
}
/**
* 页面加载完执行的函数
* */
window.onload = function() {
/**
* 绑定单击事件
* 实现批量操作
* */
document.getElementById("findBox").onclick = function (){
//获取每一td的id的集合
var cbs = document.getElementsByName("uid");
//遍历集合 并执行操作
for ( var i = 0; i < cbs.length; i++) {
cbs[i].checked = this.checked;
}
}
/**
* 绑定单击事件函数
* 实现批量删除功能
* */
document.getElementById("deleteSelected").onclick = function () {
//删除前的提示
if (confirm("您确定要删除所选信息吗?")) {
flag = false;
//批量获取td的id
var cbs = document.getElementsByName("uid");
for ( var i = 0; i < cbs.length; i++) {
if (cbs[i].checked){
flag = true;
break;
}
}
if (true) {
document.getElementById("delSelected").submit();
}
}
}
}
</script>
<%--批量设置格式--%>
<style type="text/css">
td, th {
text-align: center;
}
</style>
</head>
<%--html代码很基本,现在已经00:36分,不想写注释,有时间补上--%>
<body>
<%--复杂查询表单--%>
<div class="container" >
<h3 style="text-align: center">用户信息列表</h3>
<form class="form-inline" style="float: left;margin: 5px" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post" >
<div class="form-group" >
<label for="exampleInputName2">姓名</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="李四" value="${condition.name[0]}" name="name">
</div>
<div class="form-group">
<label for="exampleInputAddress">籍贯</label>
<input type="text" class="form-control" name="address" id="exampleInputAddress" value="${condition.address[0]}" placeholder="北京">
</div>
<div class="form-group">
<label for="exampleInputEmail2">邮箱</label>
<input type="text" class="form-control" name="email" value="${condition.email[0]}" id="exampleInputEmail2" >
</div>
<button type="submit" class="btn btn-default">查询</button>
</form>
<div style="float: right;margin: 5px">
<tr style="float: right;margin: 5px" >
<td colspan="8" align="center"><a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp" >添加联系人</a></td>
<td colspan="8" align="center"><a class="btn btn-primary" href="javascript:void(0); " id="deleteSelected">删除选中</a></td>
</tr>
</div>
<form name="form" action="${pageContext.request.contextPath}/deleteSelectedServlet" id="delSelected" method="post">
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th><input type="checkbox" id="findBox" ></th>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>籍贯</th>
<th>QQ</th>
<th>邮箱</th>
<th>操作</th>
</tr>
<c:forEach items="${userByPage.list}" var="user" varStatus="s">
<tr>
<td><input type="checkbox" id="uid" name="uid" value="${user.id}"></td>
<td>${s.count}</td>
<td>${user.name}</td>
<td>${user.gender}</td>
<td>${user.age}</td>
<td>${user.address}</td>
<td>${user.qq}</td>
<td>${user.email}</td>
<td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/updateServlet?id=${user.id}">修改</a><a class="btn btn-default btn-sm" href="javascript:deleteUser('${user.id}','${user.name}')">删除</a></td> </tr>
</c:forEach>
</table>
</form>
<nav aria-label="...">
<ul class="pagination">
<c:if test="${userByPage.currentPage == 1}">
<li class="disabled">
</c:if>
<c:if test="${userByPage.currentPage != 1}">
<li>
</c:if>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${userByPage.currentPage - 1 }&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">
<span><span aria-hidden="true">«</span>
</span>
</a>
</li>
<%--<li class="active">
<span>1 <span class="sr-only">(current)</span></span>
</li>--%>
<c:forEach begin="1" end="${userByPage.totalPage}" var="i" >
<c:if test="${userByPage.currentPage == i}">
<li class="active">
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">
<span >${i}<span class="sr-only">(current)</span></span>
</a>
</li>
</c:if>
<c:if test="${userByPage.currentPage != i}">
<li>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">
<span>${i}<span class="sr-only">(current)</span></span>
</a>
</li>
</c:if>
</c:forEach>
<c:if test="${userByPage.currentPage == userByPage.totalPage}">
<li class="disabled">
</c:if>
<c:if test="${userByPage.currentPage != userByPage.totalPage}">
<li>
</c:if>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${userByPage.currentPage + 1 }&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">
<span href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</span>
</a>
</li>
<span style="font-size: 25px;color: gray" >
共${userByPage.totalCount}条数据,共${userByPage.totalPage}页。
</span>
</ul>
</nav>
</div>
</body>
</html>
6.3所有控制器的接口
package Service;
import domain.PageBean;
import domain.User;
import java.util.List;
import java.util.Map;
/**
* 用户查询的的业务接口、
* @<code> UserService { 整个系统的控制器模块的接口
* <p>findAll 查询全部的方法</p>
* <p>longin 登录的方法</p>
* <p>addUser 添加用户的方法</p>
* <p> deleteUser 删除用户的方法</p>
* <p> update 更改用户信息页面的回显方法</p>
* <p> updateUser 更改用户信息</p>
* <p> deleteSelectedUser 批量删除的方法</p>
* <p> findUserByPage 分页查询功能</p>
* }
* @author Yh =_=
*
* </code>
* */
public interface UserService {
//未启用
public List<User> findAll() ;
/**
* @param user 传入封装后的用户输入的包含账户名和密码的User对象
* @return User 返回查询到的用户名和密码
* */
public User Login(User user);
/**
* @param user 添加用户页面封装后的数据
* */
public void addUser(User user);
/**
* @param id 删除数据的唯一标识ID
* */
public void deleteUser(int id);
/**
* @param id 回显数据的唯一标识ID
* */
public User update(int id);
/**
* @param user 更改数据的封装对象
* @param id 唯一表示 ,封装的对象内没有该属性,所以需要单独传参
* */
public void updateUser(User user,int id);
/**
* @param ids 批量删除的用户们的ID的字符集
* */
void deleteSelectedUser(String[] ids);
/**
* @param rows 分页查询的当前页显示行数
* @param currentPage 当前页码
* @param condition 复杂查询的参数
* @return 页面参数的封装类 内部包含用户信息列表
* */
PageBean<User> findUserByPage(String currentPage, String rows, Map<String, String[]> condition);
}
6.3所有控制器的实现类
package Service.UserServiceImpl;
import DAO.UseDao;
import DAO.UserDaoImpl.UserDaoImpl;
import Service.UserService;
import domain.PageBean;
import domain.User;
import java.util.List;
import java.util.Map;
/**
* 控制器实现类
* * @<code> UserServiceImpl { 整个系统的控制器模块的实现类
* * <p>findAll 查询全部的方法</p>
* * <p>longin 登录的方法</p>
* * <p>addUser 添加用户的方法</p>
* * <p> deleteUser 删除用户的方法</p>
* * <p> update 更改用户信息页面的回显方法</p>
* * <p> updateUser 更改用户信息</p>
* * <p> deleteSelectedUser 批量删除的方法</p>
* * <p> findUserByPage 分页查询功能</p>
* * }
* * @author Yh =_=
* * @author <a herf = request.getContentPath + "UserService"></a>
* *
* * </code>
* */
public class UserServiceImpl implements UserService {
private UseDao dao = new UserDaoImpl();
/**
* @return List<User> this user is All date
* */
@Override
public List<User> findAll() {
//返回查询后的数据
return dao.findAll();
}
@Override
public User Login(User user) {
User login = dao.Login(user);
return login;
}
@Override
public void addUser(User user) {
dao.addUser(user);
}
@Override
public void deleteUser(int id) {
dao.deleteUser(id);
}
@Override
public User update(int id) {
User update = dao.update(id);
return update;
}
@Override
public void updateUser(User user,int id) {
dao.updateUser(user,id);
}
@Override
public void deleteSelectedUser(String[] ids) {
//判断如果ids非空或长度>0 则遍历 保证健壮性
if (ids != null && ids.length > 0) {
for (String id:ids) {
//将字符类型转为数字类型
int i = Integer.parseInt(id);
dao.deleteUser(i);
}
}
}
/**
* @param _rows 分页查询的当前页显示行数
* @param _currentPage 当前页码
* @param condition 复杂查询的参数
* @return 页面参数的封装类 内部包含用户信息列表
* */
@Override
public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {
//创建Bean
PageBean pageBean = new PageBean();
//将页码与条目转型为数字类型
int currentPage = Integer.parseInt(_currentPage);
int rows = Integer.parseInt(_rows);
//保证程序健壮性,不写会500
if (currentPage < 1) {
currentPage = 1;
}
//调用dao查询总条目数
int totalCount = dao.findTotalCount(condition);
/**
* 计算总页码的小算法{
* 页数 (等于) 总条目数 (余) 显示行数 (等于) 0吗? (等于0)则 总条目数(除) 页面行数 : (不等于0)则 总条目数(除) 页面行数 (加) 1
* }
*
* */
int pageCount = totalCount % rows == 0 ? totalCount / rows : totalCount / rows + 1;
//保证程序健壮性 ,不写会显示空页面
if (currentPage > pageCount) {
currentPage = pageCount;
}
/**
* 分页开始的小算法{
* 分页开始 = (当前页码 - 1)* 总行数
* }
* */
int begin = (currentPage - 1) * rows;
/**
* 调用dao分页查询
*
* */
List<User> userByPage = dao.findUserByPage(begin, rows,condition);
/**
* 设置参数
* */
pageBean.setRows(rows);
pageBean.setCurrentPage(currentPage);
pageBean.setList(userByPage);
pageBean.setTotalCount(totalCount);
pageBean.setTotalPage(pageCount);
return pageBean;
}
}
6.4 pageBean(用于封装数据)
package domain;
import java.util.List;
public class PageBean<T> {
private int totalCount;//总记录数
private int totalPage;//总页码
private List<T> list;//每页的数据
private int currentPage;//当前的页码
private int rows;//每页显示的记录数
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
@Override
public String toString() {
return "PageBean{" +
"totalCount=" + totalCount +
", totalPage=" + totalPage +
", list=" + list +
", currentPage=" + currentPage +
", rows=" + rows +
'}';
}
}
6.5 批量删除的页面后台
package web.Servlet;
import Service.UserService;
import Service.UserServiceImpl.UserServiceImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
/**
* 批量删除
* */
@WebServlet("/deleteSelectedServlet")
public class deleteSelectedServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserService userService = new UserServiceImpl();
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
//获取批量id
String[] ids = request.getParameterValues("uid");
//调方法
userService.deleteSelectedUser(ids);
//重定向
response.sendRedirect(request.getContextPath()+ "/userLIstServlet");
}
}
6.6 单选删除后台
package web.Servlet;
import Service.UserServiceImpl.UserServiceImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "deleteUser", value = "/deleteUser")
public class deleteUser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
//创建控制器
UserServiceImpl userService = new UserServiceImpl();
//调方法
userService.deleteUser(Integer.parseInt(id));
//重定向
response.sendRedirect(request.getContextPath() + "/userLIstServlet");
}
}
6.7 信息回显功能
package web.Servlet;
import Service.UserService;
import Service.UserServiceImpl.UserServiceImpl;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
@WebServlet("/updateServlet")
public class UpdateServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//创建控制器
UserServiceImpl userService = new UserServiceImpl();
//设置编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
//获取唯一标识符
String id = request.getParameter("id");
//调方法
User user = userService.update(Integer.parseInt(id));
//数据域内共享与转发
request.setAttribute("user",user);
request.setAttribute("id",Integer.parseInt(id));
request.getRequestDispatcher("/update.jsp").forward(request,response);
}
}
6.8 修改信息
package web.Servlet;
import Service.UserServiceImpl.UserServiceImpl;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet( "/updateUserServlet")
public class UpdateUserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//创建控制器与设置编码
request.setCharacterEncoding("utf-8");
UserServiceImpl userService = new UserServiceImpl();
response.setContentType("text/html;charset=UTF-8");
//获取id
int id =Integer.parseInt(request.getParameter("id")) ;
//表单数据封装
Map<String, String[]> parameterMap = request.getParameterMap();
User user1 = new User();
try {
BeanUtils.populate(user1,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调方法
userService.updateUser(user1,id);
//重定向
response.sendRedirect(request.getContextPath()+"/userLIstServlet");
}
}
6.9 findAll
package web.Servlet;
import Service.UserServiceImpl.UserServiceImpl;
import domain.User;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
/*
* 未启用该功能,转发至FindUserByPageServlet
* */
@WebServlet("/userLIstServlet")
public class UserLIstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//转发到FindUserByPageServlet
request.getRequestDispatcher("/findUserByPageServlet").forward(request,response);
}
}
7.dao层
7.1 dao接口
package DAO;
import domain.User;
import java.util.List;
import java.util.Map;
/*
* 数据库操作的接口
* */
public interface UseDao {
/*
* 查询全部数据
* */
public List<User> findAll();
/**
* 查账户名和密码
* */
public User Login(User user);
/**
* 添加数据
* */
void addUser(User user);
/**
* 删除数据
* */
void deleteUser(int id);
/**
* 信息回显
* */
User update(int id);
/**
* 信息修改
* */
void updateUser(User user,int id);
/**
* 分页查询
* */
List<User> findUserByPage(int begin, int end, Map<String, String[]> condition);
/**
* 复杂查询
* */
int findTotalCount(Map<String, String[]> condition);
}
7.2 dao实现类
package DAO.UserDaoImpl;
import DAO.UseDao;
import Util.JDBCUtils;
import domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class UserDaoImpl implements UseDao {
//使用数据库连接对象
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
/*
* 操作JDBC数据库
* */
public List<User> findAll() {
/**
* 查询整张表返回一个User的list集合
* */
String sql = "select * from user";
List<User> users = template.query(sql, new BeanPropertyRowMapper<>(User.class));
return users;
}
@Override
public User Login(User user) {
//比对username & password 返回查询结果 没有结果会报错 返回null
try {
String sql = "select * from user where username=? and password = ?";
User admin = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), user.getUsername(), user.getPassword());
return admin;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public void addUser(User user) {
//添加数据
String sql = "insert into user values (null,?,?,?,?,?,?,null ,null )";
template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail());
}
@Override
public void deleteUser(int id) {
//删除数据
String sql = "delete from user where id = ?";
template.update(sql, id);
}
@Override
public User update(int id) {
//信息回显 返回一个含数据的User对象
String sql = "select * from user where id = ?";
User user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
return user;
}
@Override
public void updateUser(User user, int id) {
//数据修改
String sql = "update user set name = ? ,gender =? ,age = ?,address = ? ,qq = ? ,email = ? where id = ?";
template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail(), user.getId());
}
@Override
public List<User> findUserByPage(int begin, int rows, Map<String, String[]> condition) {
//分页查询包含复杂查询 返回一个list集合
String sql = "select * from user where 1=1";
StringBuilder sb = new StringBuilder(sql);
List<Object> param = new ArrayList<Object>();
Set<String> keySet = condition.keySet();
//程序的健壮性
for (String key: keySet) {
if ("currentPage".equals(key) || "rows".equals(key)) {
continue;
}
String value = condition.get(key)[0];
if (value != null && !"".equals(value)) {
sb.append(" and " + key + " like ? ");
param.add("%"+value+"%");
}
}
sb.append(" limit ? , ? " );
param.add(begin);
param.add(rows);
sql = sb.toString();
System.out.println(sql);
System.out.println(param);
List<User> query = template.query(sql, new BeanPropertyRowMapper<>(User.class),param.toArray());
return query;
}
/**
* todo 凌晨三点了 扛不住了,有空把注释补全 黑马Y Y D S!!!
*
====================
* || ___ ||
* || | | ||
* || =====| |====== ||
* || // | | \\ ||
* || // | | \\ ||
* || | | ||
* || --- ||
* ||==================||
* */
@Override
public int findTotalCount(Map<String, String[]> condition) {
//查数
String sql = "select count(*) from user where 1=1 ";
StringBuilder sb = new StringBuilder(sql);
List<Object> param = new ArrayList<Object>();
Set<String> keySet = condition.keySet();
for (String key: keySet) {
if ("currentPage".equals(key) || "rows".equals(key)) {
continue;
}
String value = condition.get(key)[0];
if (value != null && !"".equals(value)) {
sb.append(" and " + key + " like ? ");
param.add("%"+value+"%");
}
}
System.out.println(sb.toString());
sql = sb.toString();
Integer integer = template.queryForObject(sql, Integer.class,param.toArray());
return integer;
}
}
8.拦截器
package web.Filter;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 权限控制
* */
@WebFilter("/*")
public class UserFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
//强转为HttpServlet获取uri
HttpServletRequest request1 = (HttpServletRequest) request;
String requestURI = request1.getRequestURI();
//对登录相关的资源放行
if (requestURI.contains("/login.jsp") || requestURI.contains("/css/") || requestURI.contains("/js/") || requestURI.contains("/fonts/") || requestURI.contains("/checkCode") || requestURI.contains("/loginServlet")) {
chain.doFilter(request, response);
}else {
Object login = request1.getSession().getAttribute("login");
//权限判断
if (login != null) {
chain.doFilter(request, response);
} else {
request1.setAttribute("login_msg","您尚未登录,请登录");
request1.getRequestDispatcher("/login.jsp").forward(request1,response);
}
}
}
}
9.退出登录
package web.Servlet;
import com.mysql.cj.Session;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/exitUserServlet")
public class exitUserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取session对象
HttpSession session = request.getSession();
//设置编码
request.setCharacterEncoding("utf-8");
//删除login属性
session.removeAttribute("login");
//转发 随意转发到哪都可以 有拦截器
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}