一. 通用分页核心思路
将上一次查询的请求再发一次,只不过页码发生了变化。
二. 前端通用分页与后端通用分页的区别
1.数据处理位置:后端通用分页在服务器端进行数据处理和分页查询,而前端通用分页在客户端进行数据筛选和展示。
2.数据传输量:后端通用分页只将当前页的数据传输给客户端,减少了数据传输量;前端通用分页将全部数据传输到客户端,可能导致数据量较大。
3.性能和响应时间:后端通用分页可以对大容量数据进行高效的分页查询和处理;前端通用分页在数据量较大时可能导致页面加载缓慢。
4.实现复杂度:后端通用分页需要在服务器端编写查询逻辑和分页逻辑;前端通用分页需要在客户端编写分页逻辑和数据筛选逻辑。
三. PageBean的优化
1.新增一个属性url,保留上一次发送的请求地址
2.新增一个属性paramMap,保留上一次发送请求携带的参数
3.新增一个方法,获取最大页的页码
4.新增一个方法,获取上一页的页码
5.新增一个方法,获取下一页的页码
6.增加一个方法,初始化PageBean
package com.xissl.utils; 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;// 总记录数 private boolean pagination = true;// 是否分页 private String url;//上一次查询的url private Map<String, String[]> paramMap; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Map<String, String[]> getParamMap() { return paramMap; } public void setParamMap(Map<String, String[]> paramMap) { this.paramMap = paramMap; } 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; } // 最大页 public int maxPage() { return this.total % this.rows == 0 ? this.total/this.rows : this.total/this.rows + 1; } // 下一页 public int nextPage() { return this.page < this.maxPage()? this.page+1 : this.page; } // 上一页 public int prevPage() { return this.page>1 ? this.page-1 : this.page; } public void setRequest(HttpServletRequest req) { // 初始化默认查询第几页的数据 this.setPage(req.getParameter("page")); this.setRows(req.getParameter("rows")); this.setPagination(req.getParameter("pagination")); // 保留上一次的url this.setUrl(req.getRequestURL().toString()); // 保留携带的参数 this.setParamMap(req.getParameterMap()); } public void setPagination(String pagination) { if(StringUtils.isNotBlank(pagination)) this.setPagination(!"false".equals(pagination)); } public void setRows(String rows) { if(StringUtils.isNotBlank(rows)) this.setRows(Integer.valueOf(rows)); } public void setPage(String page) { if(StringUtils.isNotBlank(page)) this.setPage(Integer.valueOf(page)); } /** * 获得起始记录的下标 * * @return */ public int getStartIndex() { return (this.page - 1) * this.rows; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]"; } }
四. 自定义pageBean分页标签
运用之前所分享的自定义jsp标签的知识来自定义一个Page标签,PageTag继承 BodyTagSupport类,用stringbuffer中的append方法来实现页面展示效果。最后我们只要在jsp页面引用PageTag标签就可以了
标签助手类PageTag
package com.xissl.tag; import com.xissl.utils.PageBean; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import java.io.IOException; import java.util.Map; import java.util.Set; /** * * @author xissl * */ public class PageTag extends BodyTagSupport { 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) { e.printStackTrace(); } return SKIP_BODY; } private String toHTML() { StringBuilder sb = new StringBuilder(); // 这里拼接的是一个上一次发送的请求以及携带的参数,唯一改变的就是页码 sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>"); sb.append("<input type='hidden' name='methodName' value='list'>"); sb.append("<input type='hidden' name='page'>"); // 重要设置拼接操作,将上一次请求参数携带到下一次 Map<String, String[]> paMap = pageBean.getParamMap(); if(paMap !=null && paMap.size()>0){ Set<Map.Entry<String, String[]>> entrySet = paMap.entrySet(); for (Map.Entry<String, String[]> entry : entrySet) { for (String val : entry.getValue()) { if(!"page".equals(entry.getKey())){ sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'>"); } } } } sb.append("</form>"); int page = pageBean.getPage(); int max = pageBean.maxPage(); int before = page > 4 ? 4 : page-1; int after = 10 - 1 - before; after = page+after > max ? max-page : after; // disabled boolean startFlag = page == 1; boolean endFlag = max == page; // 拼接分页条 sb.append("<ul class='pagination'>"); sb.append("<li class='page-item "+(startFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage(1)'>首页</a></li>"); sb.append("<li class='page-item "+(startFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.prevPage()+")'><</a></li>"); // 代表了当前页的前4页 for (int i = before; i > 0 ; i--) { sb.append("<li class='page-item'><a class='page-link' href='javascript:gotoPage("+(page-i)+")'>"+(page-i)+"</a></li>"); } sb.append("<li class='page-item active'><a class='page-link' href='javascript:gotoPage("+pageBean.getPage()+")'>"+pageBean.getPage()+"</a></li>"); // 代表了当前页的后5页 for (int i = 1; i <= after; i++) { sb.append("<li class='page-item'><a class='page-link' href='javascript:gotoPage("+(page+i)+")'>"+(page+i)+"</a></li>"); } sb.append("<li class='page-item "+(endFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.nextPage()+")'>></a></li>"); sb.append("<li class='page-item "+(endFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.maxPage()+")'>尾页</a></li>"); sb.append("<li class='page-item go-input'><b>到第</b><input class='page-link' type='text' id='skipPage' name='' /><b>页</b></li>"); sb.append("<li class='page-item go'><a class='page-link' href='javascript:skipPage()'>确定</a></li>"); sb.append("<li class='page-item'><b>共"+pageBean.getTotal()+"条</b></li>"); sb.append("</ul>"); // 拼接分页的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("}"); sb.append("function skipPage() {"); sb.append("var page = document.getElementById('skipPage').value;"); sb.append("if (!page || isNaN(page) || parseInt(page) < 1 || parseInt(page) > "+max+") {"); sb.append("alert('请输入1~N的数字');"); sb.append("return;"); sb.append("}"); sb.append("gotoPage(page);"); sb.append("}"); sb.append("</script>"); return sb.toString(); } }
tld配置文件
<tag> <name>page</name> <tag-class>com.xissl.tag.PageTag</tag-class> <!-- 该标签有标签体 --> <body-content>jsp</body-content> <attribute> <name>pageBean</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
五. 案例实现
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 prefix="l" uri="/xissl" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <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> <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" class="form-control-plaintext" name="bname" placeholder="请输入书籍名称"> </div> <button type="submit" class="btn btn-primary mb-2">查询</button> </form> <table class="table table-striped"> <thead> <tr> <th scope="col">书籍ID</th> <th scope="col">书籍名</th> <th scope="col">价格</th> </tr> </thead> <tbody> <c:forEach items="${books }" var="b"> <tr> <td>${b.bid }</td> <td>${b.bname }</td> <td>${b.price }</td> </tr> </c:forEach> </tbody> </table> <l:page pageBean="${pageBean }"></l:page> </body> </html>
查询的servlet
在servlet中调用分页的方法并转发到jsp界面。
1.实例化dao层,实体类,分页类(PageBean)
2.把req请求传进PageBean进行分页的初始化
3.初始化完成后拿到page和实体
4.存入作用域
5.利用转发进行传值
package com.xissl; import java.io.IOException; import java.util.List; import java.util.Map; 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.xissl.dao.BookDao; import com.xissl.entity.Book; import com.xissl.utils.PageBean; @WebServlet("/book.action") public class BookServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @SuppressWarnings("unused") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // String bname = request.getParameter("bname"); map包含了浏览器传递到后台的所有参数键值对 // Map<String, String[]> map = request.getParameterMap(); 浏览器请求的地址 // String url = request.getRequestURL().toString(); PageBean pagebean = new PageBean(); pagebean.setRequest(request); BookDao bookdao = new BookDao(); Book book = new Book(); book.setBname(request.getParameter("bname")); List<Book> books = null; try { books = bookdao.query2(book, pagebean); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("books", books); request.setAttribute("pageBean", pagebean); request.getRequestDispatcher("book.jsp").forward(request, response); } }
运行结果如下:
中文乱码处理
package com.xissl.utils; 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; /** * 中文乱码处理 * */ @WebFilter("*.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(); } } }