前言
今天博主所讲解一个网站或者app常见的分页功能,看完这篇会有想象不到的收获。试想一下我每一个类别都需要写一套分页或者修改吗?这样会造成不必要的麻烦和代码的冗余。
博主也是对分页进行了一个封装,避免了代码的冗余,在通用分页详解【上】也进行了详细介绍,本篇会对其进行优化讲解。接下来将让博主带你们去如何运用在网页中😊
一、通用分页的核心思想
将上一次查询请求再发一次,只不过页码变了。
二、PageBean的分页要素及优化
- page—当前页
- rows—条目数
- url—处理查询的url
- Map<String, String[]> parameterMap----上一次查询的条件
- pagination—是否分页—视图层传递过来
- total—总记录数—后台查出来
也新增了获取最大页码、上一页、下一页和初始化数据的方法
三、SQL的通用
在通用分页详解【上】中没有提到,这里也说明一下
1.获取总记录数
// 获取总共行数 private String getCountSql(String sql) { return "select count(1) from (" + sql + ") t"; }
2.获取分页语句
// 获取分页语句 private String getPageSql(String sql, PageBean pageBean) { return sql += " limit " + pageBean.getStartIndex() + "," + pageBean.getRows(); }
四、PageTag的核心逻辑见解
五、运行流程
案例运用
注意:
博主是利用bootstrap官网中的组件写的jsp
贴上地址:警告框(Alert) · Bootstrap v4 中文文档 v4.6 | Bootstrap 中文网
注意博主的jsp界面运行的时候要联网的哦!不然样式显示不出来
1.pageBean优化
package com.ctb.utils; import java.util.Map; import javax.servlet.http.HttpServletRequest; /** * 分页工具类 * * @author biao * */ 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[]> maps;// 保留上一次发送的请求携带的参数 // 最大页 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.setmaps(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)); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Map<String, String[]> getmaps() { return maps; } public void setmaps(Map<String, String[]> maps) { this.maps = maps; } 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 + "]"; } }
2.tld文件
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <!-- 标签库描述符 --> <taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor"> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>Simple Tags</short-name> <uri>/com.ctb</uri> <tag> <name>page</name> <tag-class>com.ctb.tag.PageTag</tag-class> <body-content>JSP</body-content> <attribute> <name>pageBean</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
3.分页标签助手类
package com.ctb.tag; import java.io.IOException; import java.util.Map; import java.util.Set; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import com.ctb.utils.PageBean; /** * page助手类 * @author biao * */ 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.getmaps(); 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(); //获取前面展示页数,如果当前页数大于4的话那么前面就显示4页,否则就当前页数-1 int before = page > 4 ? 4 : page-1; //获取后面部分展示页,默认的10-当前占用的自身-前面显示数 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(); } }
4.Servlet层
package com.ctb.servlet; 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.ctb.dao.BookDao; import com.ctb.entity.Book; import com.ctb.utils.PageBean; /** * 数据显示以及分页模糊查询 * @author biao * */ @WebServlet("/book.action") public class BookServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PageBean pageBean = new PageBean(); //初始化 pageBean.setRequest(req); //实例化bookdao类 BookDao bookDao = new BookDao(); //实例化实体--书 Book book = new Book(); //获取模糊查询内容中的关键字 book.setBname(req.getParameter("bname")); try { //调用分页模糊查询的方法 List<Book> books = bookDao.list2(book, pageBean); //将数据保存到request作用域中 req.setAttribute("books", books); } catch (Exception e) { e.printStackTrace(); } //将数据保存在request作用域中 req.setAttribute("pageBean", pageBean); //跳转 req.getRequestDispatcher("booklist.jsp").forward(req, resp); } }
<%@ 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="/com.ctb" prefix="t" %> <!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> <t:page pageBean="${pageBean }"></t:page> </body> </html>
6.结果输出
以GIF动图展示效果给大家看
到这讲解的也差不多了,若有任何疑问欢迎评论区留言