一、理解分页核心思想
通过上一次对通用分页(一)的探究和了解,我们大概知道了通用分页是什么,也了解到了通用分页的核心思想是:
将上一次查询请求再发一次,只不过页码变了。
示意图:
可以看到,在第二次和第三次的请求时,查询的参数都保存了下来,而且只有page(页码)变了。
二、在jsp页面展示自定义标签通用分页效果
具体思路:
1、补全servlet
2、页面展示
3、分页重要参数(page、rows、是否分页、上一次请求、上一次的表单参数)
4、自定义分页标签
实体类:Book
package 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(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book() {
super();
}
}
Pagebean:
package util;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
private String url ; //保留上一次的地址
private Map<String, String[]> mappage = new HashMap<>(); //保留上一次查询的参数
/**
* pegebean 初始化方法
* @return
*/
public void setRequest (HttpServletRequest req) {
this.setPage(req.getParameter("page"));//控制页码
this.setRows(req.getParameter("rows"));//控制显示条数
this.setPagination(req.getParameter("pagination"));//控制是否分页
this.setUrl(req.getRequestURL().toString());//上一次地址
this.setMappage(req.getParameterMap());//上一次的查询参数
}
/**
* 是否分页
* @param pagination
*/
public void setPagination(String pagination) {
// TODO Auto-generated method stub
if("false".equals(pagination)) {
this.setPagination(false);
}
}
/**
* 改变rows
* @param rows
*/
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows)) {
this.setRows(Integer.valueOf(rows));
}
}
/**
* 改变page(页码)
* @param page
*/
public void setPage(String page) {
// TODO Auto-generated method stub
if(StringUtils.isNotBlank(page)) {
this.setPage(Integer.valueOf(page));
}
}
//求总页数
public int getMaxpage() {
return this.total % this.rows == 0 ? this.total/this.rows : this.total/this.rows+1;
}
//上一页
public int getBackpage() {
return this.page > 1 ? this.page - 1 : this.page;
}
//下一页
public int getNextpage() {
return this.page < this.getMaxpage() ? this.page + 1 :this.page;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getMappage() {
return mappage;
}
public void setMappage(Map<String, String[]> mappage) {
this.mappage = mappage;
}
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 + "]";
}
}
BeanDao2:
package dao;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import util.DBAccess;
import util.PageBean;
/**
* 通用分页查询(带条件查询)
* @author 10570
*
*/
public class BeanDao2<T> {
/**
*
* @param sql 由于不同的表查询语句不一样,所以靠子类写好来传递
* @param cls 需要返回不同的对象集合 查询的对象
* @param bean 可能要分页
* @return
* @throws Exception
*/
public List<T> sqlBean (String sql,Class cls,PageBean bean) throws Exception{
List<T> list = new ArrayList<>();
Connection con = DBAccess.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
//决定是否分页:
if(bean != null && bean.isPagination()) {//判读条件
//分页
/**
* 1.分页是与分页助手类pagebean中的total有关,需要查询数据库得到total赋值给bean
* 2.查询出符合条件的某一页的数据
*/
String countsql = getCountsql(sql);
ps = con.prepareStatement(countsql);
rs = ps.executeQuery();
/**
* -- 符合条件的记录数
select count(1) from (select * from t_mvc_book where bname like '%斗破%') t;
*/
if(rs.next()){
bean.setTotal(rs.getObject(1).toString());//查询多少条数据
}
/**
* --分页的查询语句
select * from t_mvc_book where bname like '%斗破%' limit 起始下标(第几页),变量(每页显示几条)
*/
String pagesql = getPagesql(sql, bean);
ps = con.prepareStatement(pagesql);
rs = ps.executeQuery();
}else {
//不分页
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
}
T t = null;
while (rs.next()) {
/**
* 1. 实例化一个你要查询的对象 (比如book)
* 2. 通过对象的属性名去游标中取出属性值(通过反射来完成)
* 2.1 获取到类对象中的属性
* 2.2 给属性赋值
* 3. 已经赋值好的实例对象放入到list集合当中
*/
t = (T) cls.newInstance();//反射获取对象开始
Field [] fields = cls.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);//打开权限
// 对象 对象的属性名
f.set(t, rs.getObject(f.getName()));
}
list.add(t);
}
return list;
}
/**
*
* @param sql
* @param bean 获取查询的起始下标和变量
* @return
*/
private String getPagesql(String sql , PageBean bean) {
// TODO 分页查询语句
return sql + " limit " +bean.getStartIndex()+","+bean.getRows();
}
private String getCountsql(String sql) {
// TODO 用来查询对应条件有多少条数据
return "select count(1) from ("+sql+") t";
}
}
BookDao3:
package dao;
import java.util.List;
import entity.Book;
import util.PageBean;
import util.StringUtils;
/**
* 测试通用分页查询(带条件)
* @author 10570
*
*/
public class BookDao3 extends BeanDao2<Book>{
public List<Book> list(Book book,PageBean bean) throws Exception{
String sql = "select * from t_mvc_book where true";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql += " and bname like '%"+bname+"%'";
}
return super.sqlBean(sql, Book.class, bean);//父类的查询方法
}
}
Servlet(业务逻辑处理层):
Bookweb:
package servlet;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.BookDao3;
import entity.Book;
import util.PageBean;
public class Bookweb extends HttpServlet{
private static final long serialVersionUID = -6463875662697250764L;
private BookDao3 bookDao3 = new BookDao3();
@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 {
String bname = req.getParameter("bname");
Book book = new Book();
book.setBname(bname);
PageBean pageBean = new PageBean();
// Map<String, String[]> mappage = req.getParameterMap();
// pageBean.setMappage(mappage);
// String url = req.getRequestURL().toString();
// pageBean.setUrl(url);
//System.out.println(pageBean.getUrl());
pageBean.setRequest(req);//把再一次请求的地址存到pageBean
try {
List<Book> list = this.bookDao3.list(book, pageBean);
req.setAttribute("list", list);
req.setAttribute("pageBean", pageBean);
req.getRequestDispatcher("index.jsp").forward(req, resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注意:
如何将上一次查询请求再发一次
String contextPath = req.getContextPath();//根目录
String url = req.getServletPath();//请求的地址
req.getRequestURL() //获取请求全路径
Map<String, String[]> parameterMap = req.getParameterMap();//获得请求中的所有参数
pageBean.setRequest(req);//把再一次请求的地址存到pageBean
注1:不能将分页表单嵌套到其它表单中,否则不能提交表单!!!
不能将分页表单嵌套到其它表单中,否则不能提交表单!!!
不能将分页表单嵌套到其它表单中,否则不能提交表单!!!
这里会出现中文乱码,这就需要我们上一次写的工具类:
EncodingFiter:
package 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;
/**
* 中文乱码处理
*
*/
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();
}
}
}
把bookweb和EncodingFiter配置到web.xml中:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>songwanxi_page</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 防止中文乱码 -->
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
<!-- 配置 -->
<servlet>
<servlet-name>bookweb</servlet-name>
<servlet-class>servlet.Bookweb</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bookweb</servlet-name>
<url-pattern>/bookweb</url-pattern>
</servlet-mapping>
</web-app>
Tld文件:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>sss 1.1 core library</description>
<display-name>sss core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>s</short-name>
<uri>/SwxTag</uri>
<tag>
<name>page</name>
<tag-class>tag.PageTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>pageBean</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
自定义标签助手类:PageTag
package tag;
import java.io.IOException;
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 util.PageBean;
/**
* 自定义通用分页标签
* @author 10570
*
*/
public class PageTag extends BodyTagSupport{
private static final long serialVersionUID = -5888533396741491031L;
private PageBean pageBean;
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
out.print(toHTML());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doStartTag();
}
private String toHTML() {
StringBuilder sb = new StringBuilder();
//拼接下一次分页请求提交的分页表单
sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
sb.append("<input type='hidden' name='page'>");
Map<String, String[]> mappage = pageBean.getMappage();
if(mappage != null && mappage.size()>0) {//判断查询参数是否为空
Set<Entry<String , String[]>> entrySet = mappage.entrySet();
for (Entry<String, String[]> entry : entrySet) {
for (String value : entry.getValue()) {//因为是String数组 所以要再次遍历一遍 取出
if(!"page".equals(entry.getKey())) {
sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+value+"'> ");
}
}
}
}
sb.append("</form>");
//拼接分页条
sb.append("<div style='text-align: right; font-size: 12px;'>");
sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxpage()+"页 ");
sb.append("<a href='javascript:gotoPage(1)'>首页</a> ");
sb.append("<a href='javascript:gotoPage("+pageBean.getBackpage()+")'>上一页</a> ");
sb.append("<a href='javascript:gotoPage("+pageBean.getNextpage()+")'>下一页</a> ");
sb.append("<a href='javascript:gotoPage("+pageBean.getMaxpage()+")'>尾页</a> ");
sb.append("<input type='text' id='skipPage' ");
sb.append(" style='text-align: center; font-size: 12px; width: 50px;'> ");
sb.append("<a href='javascript:skipPage()'>Go</a>");
sb.append("</div>");
//拼接分页的js代码
sb.append("<script type='text/javascript'>");
sb.append("function gotoPage(page) {");
sb.append("document.getElementById('pageBeanForm').page.value = page;");
sb.append("document.getElementById('pageBeanForm').submit();}");
sb.append("function skipPage() {");
sb.append("var page = document.getElementById('skipPage').value;");
sb.append("if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page) > "+pageBean.getMaxpage()+"){");
sb.append("alert('请输入1~N的数字');");
sb.append("return;}");
sb.append("gotoPage(page);}");
sb.append("</script>");
return sb.toString();
}
}
Jsp页面显示:index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="/SwxTag" prefix="sd"%>
<!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>测试</title>
</head>
<body>
<h2>小说目录</h2>
<br>
<!-- 顶部查询表单 用来提交查询条件 -->
<form action="${pageContext.request.contextPath}/bookweb"
method="post">
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</form>
<!-- 查询结果显示表 -->
<table border="1" width="100%">
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
</tr>
<c:forEach items="${list }" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
</tr>
</c:forEach>
</table>
${pageBean.url}
<!-- 底部分页显示 -->
<sd:page pageBean="${pageBean}"></sd:page>
<%--
<form id='pageBeanForm' action='${pagebean.url}' method='post'>
<input type='hidden' name=''> <input type='hidden' name='page'>
</form>
<div style='text-align: right; font-size: 12px;'>
每页${pagebean.rows}条,共${pagebean.total}条,第${pagebean.page}页,共${pagebean.getMaxpage()}页
<a href='javascript:gotoPage(1)'>首页</a> <a
href='javascript:gotoPage(${pagebean.getBackpage()})'>上一页</a> <a
href='javascript:gotoPage(${pagebean.getNextpage()})'>下一页</a> <a
href='javascript:gotoPage(${pagebean.getMaxpage()})'>尾页</a> <input type='text'
id='skipPage'
style='text-align: center; font-size: 12px; width: 50px;'> <a
href='javascript:skipPage()'>Go</a>
</div>
<!-- 分页js代码 -->
<script type='text/javascript'>
function gotoPage(page) {
document.getElementById('pageBeanForm').page.value = page;
document.getElementById('pageBeanForm').submit();
}
function skipPage() {
var page = document.getElementById('skipPage').value;
if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page) > ${pagebean.getMaxpage()}){
alert('请输入1~N的数字');
return;
}
gotoPage(page);
}
</script> --%>
</body>
</html>
显示结果:
第七页:
最后一页: