目录
一. 登录
login.jsp
代码如下
需注意的是:
点击验证码刷新,验证码是一直不重复的,我们需要在生成验证码的地址后加入时间戳,因为时间是永远不会重复的。
<%@ 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() {
var vcode = document.getElementById("vcode");
vcode.src ="${pageContext.request.contextPath}/checkCodeServlet?time=" + new Date().getTime();
}
</script>
</head>
<body>
<div class="container" style="width: 400px;">
<h3 style="text-align: center;">管理员登录</h3>
<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}/checkCodeServlet"
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>
<!-- 出错显示的信息框 -->
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert">
<span>×</span></button>
<strong>${login_msg}</strong>
</div>
</div>
</body>
</html>
随机生成验证码方法
checkCodeServlet.java
package web.Servlet;
/**
* 验证码
*/
@WebServlet("/checkCodeServlet")
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中
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);
}
}
做完前端页面的准备后,就要开始实现登录的验证了。
LoginServlet.java
//1.设置编码
request.setCharacterEncoding("utf-8");
//2.获取数据
//2.1 获取用户填写验证码
String verifycode = request.getParameter("verifycode");
//2.2.校验验证码
HttpSession session = request.getSession();
String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");
//确保验证码一次性
session.removeAttribute("verifycode");
if (!checkcode_server.equalsIgnoreCase(verifycode)){
//验证码不正确
request.setAttribute("login_msg","验证码错误!");
request.getRequestDispatcher("/login.jsp").forward(request,response);
return;
}
Map<String, String[]> map = request.getParameterMap();
//3.封装User对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//4.调用service查询
UserService service = new UserServiceimpl();
User loginUser = service.login(user);
//5.判断是否登录成功
if (loginUser!=null){
//登录成功
//将用户存入session,并跳转页面
session.setAttribute("user",loginUser);
response.sendRedirect(request.getContextPath()+"/index.jsp");
}else {
//登录失败
request.setAttribute("login_msg","用户名或密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
二、index界面
登录成功后,我们进入index界面,显示出用户姓名。
index.jsp
<body>
<div align="center"><h2>${user.name},欢迎您</h2></div>
<div align="center">
<a
href="${pageContext.request.contextPath}/findUserByPageServlet" style="text-decoration:none;font-size:33px">查询所有用户信息
</a>
</div>
</body>
点击查询所有用户信息(原来你也玩原神!)
list.jsp 展示信息
<%@ 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">
<!-- 使用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>
<style type="text/css">
td, th {
text-align: center;
}
</style>
<script>
function deleteUser(id) {
if (confirm("确定要删除吗?")) {
location.href = "${pageContext.request.contextPath}/delUserServlet?id=" + id;
}
}
window.onload = function () {
document.getElementById("delSelected").onclick = function () {
if (confirm("确认要删除吗?")) {
var flag = false;
var uids = document.getElementsByName("uid");
//判断是否有选中条目
for (var i = 0; i < uids.length; i++) {
if (uids[i].checked) {
flag = true;
}
}
if (flag) {
document.getElementById("delForm").submit();
}
}
};
//获取第一个cb
document.getElementById("firstCb").onclick = function () {
//获取下边所有的cb
var cbs = document.getElementsByName("uid")
//遍历
for (var i = 0; i < cbs.length; i++) {
//设置cbs[i]的状态与第一个cb状态一致
cbs[i].checked = this.checked;
}
}
}
</script>
</head>
<body>
<div class="container">
<h3 style="text-align: center">用户信息列表</h3>
<div style="float: left">
<form class="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post">
<div class="form-group">
<label for="exampleInputName2">姓名</label>
<input type="text" class="form-control" name="name" value="${condition.name[0]}" id="exampleInputName2">
</div>
<div class="form-group">
<label for="exampleInputName3">籍贯</label>
<input type="text" class="form-control" name="address" value="${condition.address[0]}" id="exampleInputName3">
</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>
<div style="float:right;margin: 5px">
<a class="btn btn-primary" href="add.jsp">添加联系人</a>
<a class="btn btn-primary" href="javascript:void(0);" id="delSelected">删除选中联系人</a>
</div>
<form id="delForm" action="${pageContext.request.contextPath}/delSelectedServlet" method="post">
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th><input type="checkbox" id="firstCb"></th>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>籍贯</th>
<th>QQ</th>
<th>邮箱</th>
<th>操作</th>
</tr>
<c:forEach items="${pb.list}" var="user" varStatus="s">
<tr>
<th><input type="checkbox" name="uid" value="${user.id}"></th>
<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}/findUserServlet?id=${user.id}">修改</a>
<a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a></td>
</tr>
</c:forEach>
<tr>
<td colspan="8" align="center"></td>
</tr>
</table>
</form>
<div>
<nav>
<ul class="pagination">
<c:if test="${pb.currentPage == 1}">
<li class="disabled">
</c:if>
<c:if test="${pb.currentPage != 1}">
<li>
</c:if>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage - 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<c:forEach begin="1" end="${pb.totalPage}" var="i">
<c:if test="${pb.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]}">${i}</a>
</li>
</c:if>
<c:if test="${pb.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]}">${i}</a>
</li>
</c:if>
</c:forEach>
<c:if test="${pb.currentPage == pb.totalPage}">
<li class="disabled">
</c:if>
<c:if test="${pb.currentPage != pb.totalPage}">
<li>
</c:if>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
<span style="font-size: 25px;margin-left: 5px">
共${pb.totalCount}条记录,共${pb.totalPage}页
</span>
</ul>
</nav>
</div>
</div>
</body>
</html>
FindUserByPageServlet.java
@WebServlet("/findUserByPageServlet")
public class FindUserByPageServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//1.获取参数
String currentPage = request.getParameter("currentPage"); //当前页码
String rows = request.getParameter("rows"); //每页显示条数
if (currentPage == null || "".equals(currentPage) ){
currentPage="1";
}
if (rows == null || "".equals(rows) ){
rows="5";
}
//获取条件查询参数
Map<String, String[]> condition = request.getParameterMap();
//2.调用service
UserService service = new UserServiceimpl();
PageBean<User> pb = service.findUsersByPage(currentPage, rows,condition);
//System.out.println(pb);
//3.将数据转存入request
request.setAttribute("pb",pb);
request.setAttribute("condition",condition);//将查询条件存入request
//4.转发到list.jsp
request.getRequestDispatcher("/list.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
至此基础的登录以及基本信息查询功能就做完了,接下来我们将对界面中的每个功能进行完善。
三、添加功能
3.1 添加逻辑思路
通过这张图,其实我们就可以明白添加信息整个逻辑思路了。
首先在jsp页面中输入数据,然后在Servlet中获取前台输入的数据进行封装,然后在Service业务逻辑层进行数据逻辑操作,最后调用Dao层数据处理层交互数据库进行数据的添加,最后返回页面进行数据展示。
3.2 代码实现
add.jsp
<body>
<div class="container">
<center><h3>添加联系人页面</h3></center>
<form action="${pageContext.request.contextPath}/addUserServlet" method="post">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
</div>
<div class="form-group">
<label >性别:</label>
<input type="radio" name="gender" value="男" checked="checked"/>男
<input type="radio" name="gender" value="女" />女
</div>
<div class="form-group">
<label for="age">年龄:</label>
<input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄">
</div>
<div class="form-group">
<label >籍贯:</label>
<select name="address" class="form-control" id="jiguan">
<option value="陕西">陕西</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
</select>
</div>
<div class="form-group">
<label for="qq">QQ:</label>
<input type="text" class="form-control" name="qq" id="qq" placeholder="请输入QQ号码"/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email" id="email" placeholder="请输入邮箱地址"/>
</div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交" />
<input class="btn btn-default" type="reset" value="重置" />
<input class="btn btn-default" type="button" value="返回" />
</div>
</form>
</div>
</body>
addUserServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码
request.setCharacterEncoding("utf-8");
//获取参数
Map<String, String[]> map = request.getParameterMap();
//封装对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调用service保存信息
UserService service = new UserServiceimpl();
service.addUser(user);
//跳转到用户列表页面
response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
}
四、删除功能
目录
4.1 删除逻辑思路
4.2 代码实现
在list.jsp中,展示数据的时候,为了数据能够动态展示,我们使用for循环进行数据遍历展示
所以在删除的时候,我们需要传给后台服务器需要删除数据的唯一标识,即id
<c:forEach items="${pb.list}" var="user" varStatus="s">
<tr>
<th><input type="checkbox" name="uid" value="${user.id}"></th>
<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}/findUserServlet?id=${user.id}">修改</a>
<a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a></td>
</tr>
</c:forEach>
当然,有时候用户万一误操作,进行了本不想的删除操作,如果不在删除之前进行提示,可能会带来不必要的损失,因此我们在删除这里加一个confirm提示,并且用JavaScript封装为一个方法
document.getElementById("delSelected").onclick = function () {
if (confirm("确认要删除吗?")) {
var flag = false;
var uids = document.getElementsByName("uid");
//判断是否有选中条目
for (var i = 0; i < uids.length; i++) {
if (uids[i].checked) {
flag = true;
}
}
if (flag) {
document.getElementById("delForm").submit();
}
}
};
DelUserServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取id
String id = request.getParameter("id");
//调用service删除
UserService service = new UserServiceimpl();
service.delUser(id);
//跳转到查询所有页面
response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
}
五、修改功能
5.1 修改功能逻辑
5.2 代码实现
在修改页面,我们需要实现一个数据回显。 所以我们需要先写一个findUserServlet来获取用户信息,并存入request域中。
FindUserServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取id
String id = request.getParameter("id");
//根据id查询用户
UserService service = new UserServiceimpl();
User user = service.selUserById(id);
request.setAttribute("user",user);
request.getRequestDispatcher("/update.jsp").forward(request,response);
}
update.jsp
数据回显需在input输入框中加入value属性
<body>
<div class="container" style="width: 400px;">
<h3 style="text-align: center;">修改联系人</h3>
<form action="${pageContext.request.contextPath}/updateServlet" method="post">
<input type="hidden" name="id" value="${user.id}">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" class="form-control" id="name" name="name" value="${user.name}" readonly="readonly"
placeholder="请输入姓名"/>
</div>
<div class="form-group">
<label>性别:</label>
<c:if test="${user.gender == '男'}">
<input type="radio" name="gender" value="男" checked/>男
<input type="radio" name="gender" value="女"/>女
</c:if>
<c:if test="${user.gender == '女'}">
<input type="radio" name="gender" value="男"/>男
<input type="radio" name="gender" value="女" checked/>女
</c:if>
</div>
<div class="form-group">
<label for="age">年龄:</label>
<input type="text" class="form-control" id="age" value="${user.age}" name="age" placeholder="请输入年龄"/>
</div>
<div class="form-group">
<label for="address">籍贯:</label>
<select name="address" id="address" class="form-control" >
<c:if test="${user.address == '陕西'}">
<option value="陕西" selected>陕西</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
</c:if>
<c:if test="${user.address == '北京'}">
<option value="陕西" >陕西</option>
<option value="北京" selected>北京</option>
<option value="上海">上海</option>
</c:if>
<c:if test="${user.address == '上海'}">
<option value="陕西" >陕西</option>
<option value="北京">北京</option>
<option value="上海" selected>上海</option>
</c:if>
</select>
</div>
<div class="form-group">
<label for="qq">QQ:</label>
<input type="text" class="form-control" value="${user.qq}" id="qq" name="qq" placeholder="请输入QQ号码"/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email" value="${user.email}" id="email"
placeholder="请输入邮箱地址"/>
</div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交"/>
<input class="btn btn-default" type="reset" value="重置"/>
<input class="btn btn-default" type="button" value="返回"/>
</div>
</form>
</div>
</body>
uodateUserServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置编码
request.setCharacterEncoding("utf-8");
//2.获取数据
Map<String, String[]> map = request.getParameterMap();
String id = request.getParameter("id");
//3.封装对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调用service修改信息
UserService service = new UserServiceimpl();
service.updateUser(user,id);
response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
}
六、分页查询
6.1 分页查询逻辑
6.2 代码实现
创建PageBean实体类,存储页码信息。
PageBean.java
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 +
'}';
}
}
在UserServiceimp.java中进行数据逻辑处理
public PageBean<User> findUsersByPage(String _currentPage, String _rows, Map<String,String[]> condition) {
int currentPage = Integer.parseInt(_currentPage);
int rows = Integer.parseInt(_rows);
int totalCount = dao.findTotalCount(condition);
int totalPage = totalCount % rows == 0 ? (totalCount/rows) : (totalCount/rows) + 1;
if (currentPage<=0){
currentPage=1;
}
if (currentPage >= totalPage){
currentPage = totalPage;
}
//1.创建pageBean对象
PageBean<User> pb = new PageBean<User>();
//2.设置参数
pb.setCurrentPage(currentPage);
pb.setRows(rows);
//3. 调用dao查询总记录数
pb.setTotalCount(totalCount);
//4.调用dao 查询List集合
//计算开始记录索引
int start = (currentPage - 1) * rows;
List<User> list = dao.findByPage(start,rows,condition);
pb.setList(list);
//5. 计算总页码
pb.setTotalPage(totalPage);
return pb;
}
在前端代码中,加入第一页和最后一页的判定。
<div>
<nav>
<ul class="pagination">
<c:if test="${pb.currentPage == 1}">
<li class="disabled">
</c:if>
<c:if test="${pb.currentPage != 1}">
<li>
</c:if>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage - 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<c:forEach begin="1" end="${pb.totalPage}" var="i">
<c:if test="${pb.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]}">${i}</a>
</li>
</c:if>
<c:if test="${pb.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]}">${i}</a>
</li>
</c:if>
</c:forEach>
<c:if test="${pb.currentPage == pb.totalPage}">
<li class="disabled">
</c:if>
<c:if test="${pb.currentPage != pb.totalPage}">
<li>
</c:if>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
<span style="font-size: 25px;margin-left: 5px">
共${pb.totalCount}条记录,共${pb.totalPage}页
</span>
</ul>
</nav>
</div>
七、模糊查询
7.1 模糊查询逻辑
这个功能需要注意的是sql语句的拼接
public int findTotalCount(Map<String, String[]> condition) {
//1.定义模板初始化sql
String sql = "select count(*) from user where 1=1";
StringBuilder sb = new StringBuilder(sql);
//2.遍历map
Set<String> keySet = condition.keySet();
//定义参数集合
List<Object> params = new ArrayList<Object>();
for (String key : keySet) {
//排除分页条件参数
if ("currentPage".equals(key) || "rows".equals(key)){
continue;
}
String value = condition.get(key)[0];
// 判断value是否有值
if (value!=null && !"".equals(value)){
//有值
sb.append(" and "+key+" like ? ");
params.add("%"+value+"%");//加条件值
}
}
System.out.println(sb.toString());
System.out.println(params);
return template.queryForObject(sb.toString(),Integer.class,params.toArray());
}
public List<User> findByPage(int start, int rows, Map<String, String[]> condition) {
String sql = "select * from user where 1=1";
StringBuilder sb = new StringBuilder(sql);
//2.遍历map
Set<String> keySet = condition.keySet();
//定义参数集合
List<Object> params = new ArrayList<Object>();
for (String key : keySet) {
//排除分页条件参数
if ("currentPage".equals(key) || "rows".equals(key)){
continue;
}
String value = condition.get(key)[0];
// 判断value是否有值
if (value!=null && !"".equals(value)){
//有值
sb.append(" and "+key+" like ? ");
params.add("%"+value+"%");//加条件值
}
}
//添加分页查询
sb.append(" limit ?,? ");
//添加分页查询参数值
params.add(start);
params.add(rows);
sql = sb.toString();
System.out.println(sql);
System.out.println(params);
return template.query(sql,new BeanPropertyRowMapper<User>(User.class),params.toArray());
}
至此,这个项目的关键点就全部介绍完毕。
文章评论