通用分页精装版本(二)

通用分页精装版本

  • 前言
    • 通用分页的思路及步骤
    • 最终实现的效果
    • 所需要的所有类结构以及架包
    • 代码实践
          • 使用的数据库表
          • 1.实体类Book.java
          • 2.共性部分BaseDao.java
          • 3.写dao层(BookDao.java 继承BaseDao)
          • 4.写分页工具类(pageBean.java)
          • 5.封装分页标签类(PageTag.java)
          • 6.处理业务逻辑BookAction.java
          • 7.配置字符编码过滤器(EncodingFiter.java)
          • 8.展示页面bookList.jsp
            • 9.附加StringUtils类
    • 总结

前言

小编在前面的博客中已把通用分页细讲解了,今天我们来整理一下前两篇博客中的通用分页,可能很多细节方面在此不会重复啰嗦,所以需要的朋友欢迎去查阅
链接: 通用分页(一).与通用分页(二).
本章节重要的是梳理业务逻辑以及全部代码合在一起

通用分页的思路及步骤

准备工作的文字说明前面的通用分页中已说明,去查阅就好,本次直接从代码着手

通用分页精装版本(二)_第1张图片
通用分页精装版本(二)_第2张图片

最终实现的效果

通用分页精装版本(二)_第3张图片

所需要的所有类结构以及架包

通用分页精装版本(二)_第4张图片

代码实践

使用的数据库表

通用分页精装版本(二)_第5张图片

1.实体类Book.java
package com.xiaoqing.entity;

public class Book {
	private int bid;
	private String bname;
	private float price;
	@Override
	public String toString() {
		return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
	}
	public int getBid() {
		return bid;
	}
	public void setBid(int bid) {
		this.bid = bid;
	}
	public String getBname() {
		return bname;
	}
	public void setBname(String bname) {
		this.bname = bname;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public Book() {
	}
	public Book(int bid, String bname, float price) {
		this.bid = bid;
		this.bname = bname;
		this.price = price;
	}
}
2.共性部分BaseDao.java
package com.xiaoqing.dao;

import java.lang.reflect.Field;
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 com.xiaoqing.util.DBAccess;
import com.xiaoqing.util.PageBean;

public class BaseDao<T> {
	/*public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
		List<T> list=new ArrayList<T>();
		Connection con=DBAccess.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		if(pageBean!=null&&!pageBean.isPagination()) {
			//想要分页---->列表需求
			//查询出符合条件的总记录数
			String countSql=getCountSql(sql);
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			if(rs.next()) {
				pageBean.setTotal(rs.getLong(1)+ "");
			}
			//查询出符合条件的结果集
			String pageSql=getPageSql(sql,pageBean);
			ps=con.prepareStatement(pageSql);
			rs=ps.executeQuery();
			System.out.println(ps);
			//展示想要看到的分页效果
		}else {
			//不想分页---->下拉框需求
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			System.out.println(ps);
		}
		T t;//为了节省内存,所以定义在while外面
		while(rs.next()) {
			//list.add(new k(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
			*//**
			 * Book b=new Book();
			 * b.setBid(rs.getInt("bid"));
			 * b.setBname(rs.getString("bname"));
			 * b.setPrice(rs.getFloat("price"));
			 * list.add(b);
			 * 
			 * 实例化了一个对象
			 * 给这一个空对象的每一个属性赋值
			 * 将赋值完的对象添加到list集合中返回
			 *//*
			 t =(T)clz.newInstance();
			for (Field f : clz.getDeclaredFields()) {
				f.setAccessible(true);
				f.set(t, rs.getObject(f.getName()));
			}
		}
		DBAccess.close(con, ps, rs);
		return list;
	}
	*/
public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = null;
		ResultSet rs = null;
		//判断是否分页
	if(pageBean!=null&&pageBean.isPagination()) {
			//想要分页的-----》列表需求
			//查询出符合条件的总记录数
			String countSql=getCountSql(sql);
			//重新执行countSql
			pst=con.prepareStatement(countSql);
			rs=pst.executeQuery();
			if(rs.next()) {
				//设置总记录数
				pageBean.setTotal(rs.getLong(1)+ "");
			}
			//查询出符合条件的结果集
			String pageSql=getPageSql(sql,pageBean);
			pst=con.prepareStatement(pageSql);
			rs=pst.executeQuery();
		}else {
			//不想要分页的----》下拉框需求
			pst=con.prepareStatement(sql);
			rs=pst.executeQuery();
		}
		List<T> list=new ArrayList<T>();
		T t;//为了节省内存,所以定义在while外面
		while(rs.next()) {
			/**
			 * 1.实例化一个book对象(该对象是空的,不是null)
			 * 2.取book的所有属性,然后给其赋值
			 * 	2.1 获取所有属性对象
			 * 	2.2 给属性对象赋值
			 * 3.赋完值的book对象装进list容器中
			 */
			//反射实例化
			t =(T)clz.newInstance();//相当于Book b=new Book();
			//反射获取所以属性对象
			Field[] fields = clz.getDeclaredFields();
			//遍历
			for (Field field : fields) {
				//打开通道
				field.setAccessible(true);
				//给属性对象赋值
				field.set(t, rs.getObject(field.getName()));
			}
			//把对象增加到集合
			list.add(t);
		}
		DBAccess.close(con, pst, rs);
		return list;
	}
	public String getCountSql(String sql) {
		// TODO Auto-generated method stub
		return "select count(1) from ("+sql+") t";
	}
	/**
	 * sql=select * from t_mvc_book where true and bname like '%圣墟%';//原生sql
	 * countSql=select count(1) from (select * from t_mvc_book where true and bname like '%圣墟%')
	 * pageSql=select * from t_mvc_book where true and bname like '%圣墟%' limit 10,10;
	 */
	public String getPageSql(String sql,PageBean pageBean) {	
		return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
	}	
}
3.写dao层(BookDao.java 继承BaseDao)
package com.xiaoqing.dao;

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 com.xiaoqing.entity.Book;
import com.xiaoqing.util.DBAccess;
import com.xiaoqing.util.PageBean;
import com.xiaoqing.util.StringUtils;

public class BookDao   extends  BaseDao<Book> {
	//通过反射改装后的通用查询方法
	public List<Book> list(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
		String sql="select * from t_mvc_book where 1=1";
		String bname=book.getBname();
		if(StringUtils.isNotBlank(bname)) {
			sql+=" and bname like '%"+bname+"%'";
		}
		return super.executeQuery(sql, Book.class, pageBean);
	}
}
4.写分页工具类(pageBean.java)
package com.xiaoqing.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页工具类
 *
 */
public class PageBean {
	private int page = 1;// 当前页码
	private int rows = 10;// 页大小
	private int total = 0;//总记录数
	//上一次查询的url
	private String url;
	//上一次查询所携带的查询条件
	private Map<String, String[]> parameterMap=new HashMap<String, String[]>();
	//对pagebean进行初始化
	public void setRequest(HttpServletRequest req) {
		//初始化jsp页面传递过来的当前页
		this.setPage(req.getParameter("page"));
		//初始化jsp页面传递过来的页大小
		this.setRows(req.getParameter("rows"));
		//初始化jsp页面 传递过来是否分页
		this.setPagination(req.getParameter("pagination"));
		//保留上一次的查询请求
		this.setUrl(req.getRequestURL().toString());
		//保留上一次的查询条件
		this.setParameterMap(req.getParameterMap());
	}
	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;
	}
	private void setPage(String page) {
		if(StringUtils.isNotBlank(page)) {
			this.setPage(Integer.valueOf(page));
		}
	}
	private void setRows(String rows) {
		if(StringUtils.isNotBlank(rows)) {
			this.setRows(Integer.valueOf(rows));
		}
	}
	private void setPagination(String pagination) {
		//只有填了false字符串,才代表不分页
		this.setPagination(!"false".equals(pagination));;
	}
	private boolean pagination = true;// 是否分页
	public PageBean() {
		super();
	}
	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 void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}
	public boolean isPagination() {
		return pagination;
	}
	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}
	/**
	 * 获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}
	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}
	//上一页
	public int getPrevPage() {
		return this.page>1?this.page-1:this.page;
	}
	//下一页
	public int getNextPage() {
		return this.page<this.getMaxPage()?this.page+1:this.page;
	}
	//最大页
	public int getMaxPage() {
		return this.total%this.rows==0?this.total/this.rows:(this.total/this.rows)+1;
	}
}

5.封装分页标签类(PageTag.java)
package com.xiaoqing.tag;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import com.xiaoqing.util.PageBean;

public class PageTag extends BodyTagSupport{
	private static final long serialVersionUID = -258029245678348536L;
	private PageBean pageBean;
	public PageBean getPageBean() {
		return pageBean;
	}
	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}
	@Override
	public int doStartTag() throws JspException {
		// TODO Auto-generated method stub
		JspWriter out = pageContext.getOut();
		try {
			out.print(toHTML());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return super.doStartTag();
	}
	private String toHTML() {
		// TODO Auto-generated method stub
		StringBuilder sb=new StringBuilder();
		//上一次查询的form表单的HTML拼接
		sb.append(" 
"); //查第几页的数据 sb.append(" "); Map<String, String[]> parameterMap = pageBean.getParameterMap(); if(parameterMap.size()>0) { Set<Entry<String,String[]>> entrySet = parameterMap.entrySet(); for (Entry<String, String[]> entry : entrySet) { if(!"page".equals(entry.getKey())) { for (String val : entry.getValue()) { sb.append(""); } } } } sb.append(" "
); //默认展示前面4页,当前页 ,后面5也 int page=pageBean.getPage(); int max=pageBean.getMaxPage(); int before=page>4?4:page-1; int after=10-1-before;//5 after=max-page>after?after:max-page; //用来控制上一页的点击按钮特效的 boolean startFlag=page>1; //用来控制下一页的点击按钮特效的 boolean endFlag=page<max; //拼接分页条 sb.append("
    "); sb.append("
  • 首页
  • "
    ); sb.append("
  • <
  • "
    ); //代表了当前页的前4页 for (int i = before; i > 0 ; i--) { sb.append("
  • "+(page-i)+"
  • "
    ); } sb.append("
  • "+pageBean.getPage()+"
  • "
    ); //代表了当前页的后5页 for (int i = 1; i <= after; i++) { sb.append("
  • "+(page+i)+"
  • "
    ); } sb.append("
  • >
  • "
    ); sb.append("
  • 尾页
  • "
    ); sb.append("
  • 到第
  • "
    ); sb.append("
  • 确定
  • "
    ); sb.append("
  • 共"+pageBean.getTotal()+"条
  • "
    ); sb.append("
"
); //拼接分页的js代码 sb.append(""); return sb.toString(); } }
6.处理业务逻辑BookAction.java
package com.xiaoqing.web;

import java.io.IOException;
import java.sql.SQLException;
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.xiaoqing.dao.BookDao;
import com.xiaoqing.entity.Book;
import com.xiaoqing.util.PageBean;
@WebServlet(name="book",urlPatterns="/book.action")
public class BookAction extends HttpServlet{
	private static final long serialVersionUID = 6817006004626927502L;
	private BookDao bookDao=new BookDao();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Book book=new Book();
		book.setBname(req.getParameter("bname"));
		PageBean pageBean=new PageBean();
		pageBean.setRequest(req);
		try {
			List<Book> list = this.bookDao.list(book, pageBean);
			req.setAttribute("bookList", list);
			req.setAttribute("pageBean", pageBean);
			req.getRequestDispatcher("bookList.jsp").forward(req, resp);
		} catch (InstantiationException | IllegalAccessException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
}

7.配置字符编码过滤器(EncodingFiter.java)
package com.xiaoqing.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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebFault;

/**
 * 中文乱码处理
 * 
 */
@WebFilter(filterName="encodingFiter",urlPatterns="*.action")
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();
		}
	}

}

8.展示页面bookList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
     <%@taglib uri="/xiaoqing" prefix="z" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>书籍展示</title>
<style type="text/css">
.page-item input {
	padding: 0;
	width: 40px;
	height: 100%;
	text-align: center;
	margin: 0 6px;
}
.page-item input,
.page-item b {
	line-height: 38px;
	float: left;
	font-weight: 400;
}
.page-item.go-input {
	margin: 0 10px;
}
</style>
</head>
<body>
<form class="form-inline" action="${pageContext.request.contextPath }/book.action" method="post">
  <div class="form-group mb-2">
    <input type="text" name="bname" class="form-control-plaintext" id="staticEmail2"  placeholder="请输入书籍名称">
  </div>
  <button type="submit" class="btn btn-primary mb-2">查询</button>
</form>
<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">书籍编号</th>
      <th scope="col">书籍名字</th>
      <th scope="col">书籍价格</th>
    </tr>
  </thead>
  <tbody>
  <c:forEach var="b" items="${bookList }">
    <tr>
      <td>${b.bid }</td>
      <td>${b.bname }</td>
      <td>${b.price }</td>
    </tr>
  </c:forEach>
  </tbody>
</table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>
9.附加StringUtils类
package com.xiaoqing.util;

public class StringUtils{
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}
	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}
}

总结

OK了,整个通用分页的流程就是这样,本篇博客讲的不是很详细,需要详细的通用分页讲解在小编前面的博客中有记录,不懂的欢迎大家评论!!!
谢谢!!

你可能感兴趣的:(通用分页精装版本(二))