目录
分页信息实体(PageBean)
后台分页数据查询
1. 处理流程
2. 实现
重构-提取公用方法
分页标签
1. 准备一个Servlet
2. 过滤器解决中文乱码问题
3. 加入分页功能
封装分页标签
前言:在前几篇文章我写了xml,java反射机制,自定义jsp标签,这一篇文章我会运用前几篇文章的知识来写一个通用分页功能。
用于存储和传递分页参数,主要内容如下:
参考代码:
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 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 getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map 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.为简化数据库(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 getStudents(String sname, PageBean pageBean) {
// 编写sql语句
String sql = "select * from student ";
if (!Objects.isNull(sname) && sname.length() > 0) {
sql += " where sname like ?";
}
List 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 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 {
List convent(ResultSet rs) throws SQLException;
}
public static List query(String sql,
List
将公用方法封装好后,记得把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 getStudents(String sname, PageBean pageBean) {
//构造sql语句 变化部分
String sql = "select * from student ";
List
准备一个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 students = dao.getStudents(sname, pageBean);
req.setAttribute("students", students);
req.getRequestDispatcher("/student.jsp").forward(req, resp);
}
}
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文件)配置
encodingFiter
com.zking.util.EncodingFiter
encodingFiter
/*
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Insert title here
学生信息
学号
姓名
成绩
班级
${student.sid}
${student.sname}
${student.score}
${student.clazz}