通用分页功能

目录

分页信息实体(PageBean)

后台分页数据查询

1. 处理流程

2. 实现

重构-提取公用方法

分页标签

1. 准备一个Servlet

2. 过滤器解决中文乱码问题

3. 加入分页功能

封装分页标签


前言:在前几篇文章我写了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 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. 处理流程

  1.  查询满足条件的总记录数
  2.  查询满足条件的当前页的数据
  3.  上两个步骤的查询条件要一致

流程图:

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实体类为例子,及对应的数据库表。

通用分页功能_第1张图片 

 小伙伴们要注意了,我的数据库里的列名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 paramList, 
			PageBean pageBean,
			ICovent covent
			) {
		
		Object[] params = paramList.toArray();
		
		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);
				
				//设置查询参数
				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 getStudents(String sname, PageBean pageBean) {
		//构造sql语句    变化部分
		String sql = "select * from student ";
		List param = new ArrayList<>();
		if (!Objects.isNull(sname) && sname.length() > 0) {
			sql += " where sname like ?";
			param.add("%"+sname+"%");
		}
		List list = BaseDao.query(sql, param, pageBean, new ICovent () {
			
			public List convent(ResultSet rs) throws SQLException {
				List 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 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 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文件)配置


  encodingFiter
  com.zking.util.EncodingFiter
  
  
  encodingFiter
  /*
  

3. 加入分页功能

<%@ 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}
第${pageBean.page}页    共${pageBean.total}条记录    首页    上页    下页    尾页    第 GO
"/>

目前为止,分页功能已经实现了。

但是还有几个问题:

  1. 如果其他功能需要分页,则需要复制大量代码才能重用该功能
  2. 如果系统需要修改分页工具栏的显示风格呢?

为了解决这几个问题我们需要封装分页标签。 

封装分页标签

为了方便代码的复用,及可维护性,我们将分页功能封装了一个自定义标签(其实就是将原来写在页面中的代码,通过移入到自定义标签中去实现),开发自定义标签分成三步:

  • 编写助手类
  • 编写标签描述文件
  • 在页面上引入标签库,并使用

编写助手类

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 = "
\r\n" + " 第"+pageBean.getPage()+"页   \r\n" + " 共"+pageBean.getTotal()+"条记录   \r\n" + " 首页   \r\n" + " 上页    \r\n" + " 下页    \r\n" + " 尾页   \r\n" + " 第 \r\n" + " GO\r\n" + "
"; String hiddenForm = "
" + ""; Map parameterMap = pageBean.getParameterMap(); //循环所有的参数,并为所有的参数生成隐藏表单 for(Map.Entry param: parameterMap.entrySet()) { String paramName = param.getKey(); if("page".equals(paramName)) continue; String[] values = param.getValue(); for(String val: values) { hiddenForm += ""; } } hiddenForm += ""; String js = ""; return pagingTool+hiddenForm+js; } }

  标签库(mytag.xml)描述文件中添加paging标签


		paging
		com.zking.tag.PagingTag
		empty
		分页标签
		
			pageBean
			true
			true
		
	

使用分页标签

首先在页面中引入标签

<%@taglib prefix="z" uri="/zking" %>

将原来的分页功能,替换为标签即可

页面的参考代码: 

<%@ 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" %>




Insert title here



	

学生信息

学号 姓名 年龄 备注
${student.sid} ${student.sname} ${student.score} ${student.clazz}

运行结果: 

通用分页功能_第2张图片

 

你可能感兴趣的:(java,servlet,开发语言)