目录
前言:在前几篇文章我写了xml,java反射机制,自定义jsp标签,这一篇文章我会运用前几篇文章的知识来写一个通用分页功能。
分页信息实体(PageBean)
用于存储和传递分页参数,主要内容如下:
- 页码,从页面传递过来
- 每页行数,从也能传递过来
- 总记录数, 从数据库中统计得到
- 是否分页, 如果为false,则查询所有记录
- 查询参数, 点击上一页或下一页时需要及携带用户输入的所有查询参数
- 另外提供上页,下页,总页数等计算
参考代码:
package com.zking.util;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.mysql.jdbc.StringUtils;
public class PageBean {
/**
* 页码
*/
private int page = 1;
/**
* 每页显示的记录数
*/
private int rows = 10;
/**
* 总记录数
*/
private int total = 0;
/**
* 是否分页
*/
private boolean pagination = true;
/**
* 记录查询的url,以便于点击分页时再次使用
*/
private String url;
/**
* 存放请求参数,用于生成隐藏域中的元素
*/
private Map<String,String[]> parameterMap;
/**
* 根据传入的Request初始化分页对象
* @param request
*/
public void setRequest(HttpServletRequest request) {
if(!StringUtils.isNullOrEmpty(request.getParameter("page"))) {
this.page = Integer.valueOf(request.getParameter("page"));
}
if(!StringUtils.isNullOrEmpty(request.getParameter("rows"))) {
this.rows = Integer.valueOf(request.getParameter("rows"));
}
if(!StringUtils.isNullOrEmpty(request.getParameter("pagination"))) {
this.pagination = Boolean.valueOf(request.getParameter("pagination"));
}
this.url = request.getRequestURI();
this.parameterMap = request.getParameterMap();
request.setAttribute("pageBean", this);
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map<String, String[]> parameterMap) {
this.parameterMap = parameterMap;
}
//计算起始页码
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
//获取总页数
public int getTotalPage() {
if (this.getTotal() % this.rows == 0) {
return this.getTotal() / this.rows;
} else {
return this.getTotal() / this.rows + 1;
}
}
//上一页
public int getPreviousPage() {
return this.page - 1 > 0 ? this.page - 1 : 1;
}
//下一页
public int getNextPage() {
return this.page + 1 > getTotalPage() ? getTotalPage() : this.page + 1;
}
}
后台分页数据查询
1. 处理流程
- 查询满足条件的总记录数
- 查询满足条件的当前页的数据
- 上两个步骤的查询条件要一致
流程图:
2. 实现
1.为简化数据库(mysql)操作,需要一个DBUtil工具类。
package com.zking.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
//获得驱动
private static String DRIVER_NAME = "com.mysql.jdbc.Driver";
//连接语句
private static String DB_URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
//用户名
private static String DB_USER = "root";
//密码
private static String DB_PASSWORD = "910814";
private DBUtil() {
}
static {
//驱动只需要加载一次所以放在静态代码块里
try {
Class.forName(DRIVER_NAME);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConection() throws SQLException {
Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
return connection;
}
public static void closeDB(ResultSet rs, Statement ps, Connection con) {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
if (ps != null && !ps.isClosed()) {
ps.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeDB(ResultSet rs, Statement ps) {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2.然后写一个Student实体类为例子,及对应的数据库表。
小伙伴们要注意了,我的数据库里的列名class在我的实体类里是clazz,这是应为我写列名的时候忘了class在java中是关键字了〒▽〒,但是我懒得改(。・ω・。),将就一下吧。
package com.zking.model;
public class Student {
private Integer sid;
private String sname;
private Integer score;
private String clazz;
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", score=" + score + ", clazz=" + clazz + "]";
}
}
3.分页查询的功能(写一个StudentDao)
package com.zking.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.zking.model.Student;
import com.zking.util.BaseDao.ICovent;
public class StudentDao {
public List<Student> getStudents(String sname, PageBean pageBean) {
// 编写sql语句
String sql = "select * from student ";
if (!Objects.isNull(sname) && sname.length() > 0) {
sql += " where sname like ?";
}
List<Student> students = new ArrayList<>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
// 不分页的情况
if (pageBean == null || !pageBean.isPagination()) {
try {
con = DBUtil.getConection();
ps = con.prepareStatement(sql);
// 设置查询参数
if (sname != null) {
ps.setObject(1, sname);
}
rs = ps.executeQuery();
while (rs.next()) {
Student stu = new Student();
stu.setSid(rs.getInt("sid"));
stu.setSname(rs.getString("sname"));
stu.setScore(rs.getInt("score"));
stu.setClazz(rs.getString("class"));
students.add(stu);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.closeDB(rs, ps, con);
}
} else {
// 需要分页的情况
String countSql = "SELECT COUNT(*) FROM (" + sql + ")tmp";
try {
con = DBUtil.getConection();
ps = con.prepareStatement(sql);
// 设置查询参数
if (sname != null) {
ps.setObject(1, sname);
}
rs = ps.executeQuery();
if (rs.next()) {
Integer total = rs.getInt(1);
pageBean.setTotal(total);
}
// 判断总记录数是否大于0,如果大于0表示有记录,需要查询当前记录
// 如果没有就直接返回
if (pageBean.getTotal() <= 0) {
return students;
}
// 查询当前页的数据
String pagingSql = sql + "limit" + pageBean.getStartIndex() + "," + pageBean.getRows();
// 设置查询参数
if (sname != null) {
ps.setObject(1, sname);
}
rs = ps.executeQuery();
while (rs.next()) {
Student stu = new Student();
stu.setSid(rs.getInt("sid"));
stu.setSname(rs.getString("sname"));
stu.setScore(rs.getInt("score"));
stu.setClazz(rs.getString("class"));
students.add(stu);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.closeDB(rs, ps, con);
}
}
return students;
}
public static void main(String[] args) {
StudentDao dao = new StudentDao();
List<Student> students = dao.getStudents(null, new PageBean());
students.forEach(t-> System.out.println(t));
}
}
重构-提取公用方法
(1)为了进行公共方法的抽取,需要找出上面实习中的可通用部分,和差异化部分。
-
只要是分页,就会统计总记录数,而总记录数的统计是在业务sql外封装了一个select count(*)是有规律可循的,可以通用
-
只要是分页,则封装分页sql也是有规律可循的(在业务sql后加limit子句即可),可以通用
-
因为每个查询对应的业务实体(即模型)不同,所以ORM映射部分不能通用
(2)公用方法封装思路
-
将可通用的部分封装到模板中
-
差异化部分(即不可通用部分),可以定义一个处理接口,以便于通过参数传入个性化的实现部分
(3) 具体实现
通用分页查询模板类:
package com.zking.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public final class BaseDao {
private BaseDao() {}
//回调函数接口
public static interface ICovent<T> {
List<T> convent(ResultSet rs) throws SQLException;
}
public static <T> List<T> query(String sql,
List<Object> paramList,
PageBean pageBean,
ICovent<T> covent
) {
Object[] params = paramList.toArray();
List<T> students = new ArrayList<>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
if(pageBean == null || !pageBean.isPagination()) {
try {
con = DBUtil.getConection();
ps = con.prepareStatement(sql);
//设置查询参数
int i = 1;
for(Object param: params) {
ps.setObject(i, param);
i++;
}
rs = ps.executeQuery();
//通过使用者传入的回调函数,执行转换
students = covent.convent(rs);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.closeDB(rs, ps, con);
}
} else {
//需要分页的情况
String countSql = "select COUNT(*) from (" + sql + ") tmp";
try {
con = DBUtil.getConection();
ps = con.prepareStatement(countSql);
//设置查询参数
int i = 1;
for(Object param: params) {
ps.setObject(i, param);
i++;
}
rs = ps.executeQuery();
if(rs.next()) {
Integer total = rs.getInt(1);
pageBean.setTotal(total);
}
//判断总记录数是否大于0,如果大于零表示有记录,需求查询当前记录
//如果没有就直接返回
if(pageBean.getTotal() <= 0) {
return students;
}
//查询当前业的数据
String pagingSql = sql + " limit " + pageBean.getStartIndex() + ", " + pageBean.getRows();
ps = con.prepareStatement(pagingSql);
//设置查询参数
int j = 1;
for(Object param: params) {
ps.setObject(j, param);
j++;
}
rs = ps.executeQuery();
//变化部分
students = covent.convent(rs);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.closeDB(rs, ps, con);
}
}
return students;
}
}
将公用方法封装好后,记得把StudentDao代码修改一下
package com.zking.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.zking.model.Student;
import com.zking.util.BaseDao.ICovent;
public class StudentDao {
public List<Student> getStudents(String sname, PageBean pageBean) {
//构造sql语句 变化部分
String sql = "select * from student ";
List<Object> param = new ArrayList<>();
if (!Objects.isNull(sname) && sname.length() > 0) {
sql += " where sname like ?";
param.add("%"+sname+"%");
}
List<Student> list = BaseDao.query(sql, param, pageBean, new ICovent<Student> () {
public List<Student> convent(ResultSet rs) throws SQLException {
List<Student> students = new ArrayList<>();
while(rs.next()) {
Student stu = new Student();
stu.setSid(rs.getInt("sid"));
stu.setSname(rs.getString("sname"));
stu.setScore(rs.getInt("score"));
stu.setClazz(rs.getString("class"));
students.add(stu);
}
return students;
}
});
return list;
}
public static void main(String[] args) {
StudentDao dao = new StudentDao();
List<Student> students = dao.getStudents(null, new PageBean());
students.forEach(t-> System.out.println(t));
}
}
分页标签
1. 准备一个Servlet
准备一个servlet用于处理请求,获取数据库中的数据,并转发到结果显示页面。
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.model.Student;
import com.zking.util.PageBean;
import com.zking.util.StudentDao;
@WebServlet("/students")
public class StudentServlet extends HttpServlet{
private StudentDao dao = new StudentDao();
@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 {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
String sname =req.getParameter("sname");
List<Student> students = dao.getStudents(sname, pageBean);
req.setAttribute("students", students);
req.getRequestDispatcher("/student.jsp").forward(req, resp);
}
}
2. 过滤器解决中文乱码问题
package com.zking.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 乱码处理
* @author zjjt
*
*/
public class EncodingFiter implements Filter{
private String encoding = "UTF-8";// 默认字符集
public EncodingFiter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 中文处理必须放到 chain.doFilter(request, response)方法前面
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
Set set = map.keySet();// 取出所有参数名
Iterator it = set.iterator();
while (it.hasNext()) {
String name = (String) it.next();
String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
for (int i = 0; i < values.length; i++) {
values[i] = new String(values[i].getBytes("ISO-8859-1"),
this.encoding);
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
在web.xml(新建项目自带的xml文件)配置
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.zking.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3. 加入分页功能
<%@ 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>Insert title here</title>
</head>
<body>
<h1>学生信息</h1>
<form action="<%=request.getContextPath()%>/students" method="post">
<input type="text" name="sname">
<input type="submit" value="查询">
</form>
<table border="1" style="width: 98%;">
<tr>
<td>学号</td>
<td>姓名</td>
<td>成绩</td>
<td>班级</td>
</tr>
<c:forEach items="${students}" var="student">
<tr>
<td>${student.sid}</td>
<td>${student.sname}</td>
<td>${student.score}</td>
<td>${student.clazz}</td>
</tr>
</c:forEach>
</table>
<div style="text-align: right; width:98%;">
第${pageBean.page}页
共${pageBean.total}条记录
<a href="javascript: goPage(1);">首页</a>
<a href="javascript: goPage(${pageBean.previousPage});">上页</a>
<a href="javascript: goPage(${pageBean.nextPage});">下页</a>
<a href="javascript: goPage(${pageBean.totalPage});">尾页</a>
第<input type="text" size="2" id="pageNumber" onkeypress="toPageNumber(event,this.value)"/>
<a href="javascript: goPage(document.getElementById('pageNumber').value);">GO</a>
</div>
<!-- 隐藏表达,用与分页时保存查询参数 -->
<form action="${pageBean.url}" id="pagingForm" method="post">
<input type="hidden" name="page" value="${pageBean.page}"/>
<!-- 先只考虑本功能的查询参数,没有考虑公用性(不同功能的参数不同) -->
<input type="hidden" name="sname" value="<%=request.getParameter("sname")%>"/>
</form>
</body>
<script>
function goPage(pageNum) {
debugger;
let form = document.getElementById("pagingForm");
let lastPage = '${pageBean.totalPage}';
if(pageNum > lastPage) pageNum = lastPage;
if(pageNum < 1) pageNum = 1;
form.page.value = pageNum;
form.submit();
}
function toPageNumber(event,pn) {
//debugger;
if(event.keyCode == 13) {
let form = document.getElementById("pagingForm");
form.page.value = pn;
form.submit();
}
}
</script>
</body>
</html>
目前为止,分页功能已经实现了。
但是还有几个问题:
- 如果其他功能需要分页,则需要复制大量代码才能重用该功能
- 如果系统需要修改分页工具栏的显示风格呢?
为了解决这几个问题我们需要封装分页标签。
封装分页标签
为了方便代码的复用,及可维护性,我们将分页功能封装了一个自定义标签(其实就是将原来写在页面中的代码,通过移入到自定义标签中去实现),开发自定义标签分成三步:
- 编写助手类
- 编写标签描述文件
- 在页面上引入标签库,并使用
编写助手类
package com.zking.tag;
import java.io.IOException;
import java.util.Map;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import com.zking.util.PageBean;
public class PagingTag extends BodyTagSupport {
private PageBean pageBean;
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public int doStartTag() {
JspWriter out = this.pageContext.getOut();
try {
out.println(buildHtml());
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
//构造分页的页面输出
private String buildHtml() {
String pagingTool = "<div style=\"text-align: right; width:98%;\">\r\n" +
" 第"+pageBean.getPage()+"页 \r\n" +
" 共"+pageBean.getTotal()+"条记录 \r\n" +
" <a href=\"javascript: goPage(1);\">首页</a> \r\n" +
" <a href=\"javascript: goPage("+pageBean.getPreviousPage()+");\">上页</a> \r\n" +
" <a href=\"javascript: goPage("+pageBean.getNextPage()+");\">下页</a> \r\n" +
" <a href=\"javascript: goPage("+pageBean.getTotalPage()+");\">尾页</a> \r\n" +
" 第<input type=\"text\" size=\"2\" id=\"pageNumber\" onkeypress=\"toPageNumber(event,this.value)\"/> \r\n" +
" <a href=\"javascript: goPage(document.getElementById('pageNumber').value);\">GO</a>\r\n" +
" </div>";
String hiddenForm = "<form action='" + pageBean.getUrl() + "' id=\"pagingForm\" method=\"post\">"
+ "<input type=\"hidden\" name=\"page\" />";
Map<String, String[]> parameterMap = pageBean.getParameterMap();
//循环所有的参数,并为所有的参数生成隐藏表单
for(Map.Entry<String, String[]> param: parameterMap.entrySet()) {
String paramName = param.getKey();
if("page".equals(paramName)) continue;
String[] values = param.getValue();
for(String val: values) {
hiddenForm += "<input type='hidden' name='" + paramName + "' value='" + val + "'>";
}
}
hiddenForm += "</form>";
String js = "<script>\r\n" +
"function goPage(pageNum) {\r\n" +
" debugger;\r\n" +
" let form = document.getElementById(\"pagingForm\");\r\n" +
" let lastPage = '"+pageBean.getTotalPage()+"';\r\n" +
" if(pageNum > lastPage) pageNum = lastPage;\r\n" +
" if(pageNum < 1) pageNum = 1;\r\n" +
" form.page.value = pageNum;\r\n" +
" form.submit();\r\n" +
"}\r\n" +
"\r\n" +
"function toPageNumber(event,pn) {\r\n" +
" //debugger;\r\n" +
" if(event.keyCode == 13) {\r\n" +
" let form = document.getElementById(\"pagingForm\");\r\n" +
" form.page.value = pn;\r\n" +
" form.submit();\r\n" +
" }\r\n" +
"}\r\n" +
"</script>";
return pagingTool+hiddenForm+js;
}
}
标签库(mytag.xml)描述文件中添加paging标签
<tag>
<name>paging</name>
<tag-class>com.zking.tag.PagingTag</tag-class>
<body-content>empty</body-content>
<description>分页标签</description>
<attribute>
<name>pageBean</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
使用分页标签
首先在页面中引入标签
<%@taglib prefix="z" uri="/zking" %>
将原来的分页功能,替换为标签即可
<z:paging pageBean="${pageBean}"/>
页面的参考代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="z" uri="/zking" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>学生信息</h1>
<form action="<%=request.getContextPath()%>/students" method="post">
<input type="text" name="sname">
<input type="submit" value="查询">
</form>
<table border="1" style="width: 98%;">
<tr>
<td>学号</td>
<td>姓名</td>
<td>年龄</td>
<td>备注</td>
</tr>
<c:forEach items="${students}" var="student">
<tr>
<td>${student.sid}</td>
<td>${student.sname}</td>
<td>${student.score}</td>
<td>${student.clazz}</td>
</tr>
</c:forEach>
</table>
<z:paging pageBean="${pageBean}"/>
</body>
</html>
运行结果: