1.所需技术点
Servlet,Tag助手类,StringUtils,BaseDao,配置tld,分页工具类
2.实现流程
2.1.Servlet
package com.YU.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.YU.dao.BookDao; import com.YU.entity.Book; import com.YU.util.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 { PageBean pagebean = new PageBean(); pagebean.setRequest(request); request.setAttribute("pagebean", pagebean); request.getRequestDispatcher("bookList.jsp").forward(request, response); BookDao bk = new BookDao(); Book book = new Book(); book.setBname(request.getParameter("bname")); try { List<Book> books = bk.find2(book, pagebean); request.setAttribute("books", books); } catch (Exception e) { e.printStackTrace(); } } }
作用:获取参数传递前端页面
2.2 分页工具类
package com.YU.util; 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; private Map<String, String[]> paramMap; //获取最大页码的方法 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 request) { //初始化默认查询的页码数据 this.setPage(request.getParameter("page")); //初始化默认一页查询多少条数据 this.setRows(request.getParameter("rows")); //判断是否分页 this.setPagination(request.getParameter("pagination")); //保留前一次的url this.setUrl(request.getRequestURI().toString()); //保留携带的参数 this.setParamMap(request.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 PageBean() { super(); } public Map<String, String[]> getParamMap() { return paramMap; } public void setParamMap(Map<String, String[]> paramMap) { this.paramMap = paramMap; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } 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 + "]"; } }
作用:获取分页属性,并编写上一页下一页的方法及判断是否分页,初始化分页数据,任意获取分页中的单独一页的多少条数据,并将保留的数据传递到servlet
2.3 助手类及配置
(1)助手类
package com.YU.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.YU.util.PageBean; /** * * @author 21879 * */ public class Tag 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(); } }
(2).配置tld
<?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <description>JSTL 1.1 core library</description> <display-name>JSTL core</display-name> <tlib-version>1.1</tlib-version> <short-name>y</short-name> <uri>http://jsp.YU.cn</uri> <tag> <name>page</name> <tag-class>com.YU.tag.Tag</tag-class> <body-content>JSP</body-content> <attribute> <name>pageBean</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
配置tld的两种方式
1.直接配置在lib包中
2.将其放在WEB-INF的根目录中,并在XML文件中进行配置
例(XML文件):
<jsp-config> <taglib> <taglib-uri>http://jsp.YU.cn</taglib-uri> <taglib-location>/WEB-INF/YU.tld</taglib-location> </taglib> </jsp-config>
在XML文件中加入以下代码
2.4 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="http://jsp.YU.cn" prefix="y" %> <!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"> <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> <y:page pageBean="${pagebean }"></y:page> <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) > 1122) { alert('请输入1~N的数字'); return; } gotoPage(page); } </script> </body> </html>
在jsp页面中引入我们刚刚编写的标签库,并进行引用:
<y:page pageBean="${pagebean }"></y:page>
注意点:
1.配置tld时直接配置在lib文件夹中出现错误时,可以使用前面提到的第二种方式
2.编写分页方法时要重载方法并重新调用修改的方法
3.定义map集合进行保存PageBean属性