当前位置:网站首页>通用分页功能
通用分页功能
2022-07-25 23:02:00 【一只奈良森屿】
目录
总体思路:
1) 为了提高查询性能及节约网络流量,每次只查询指定的记录数,而不是全部, 在数量比较大时很有用 2)当点击下一页或指定页面的数据时,将带着所有的查询条件,再次执行查询
优化之前代码:
1.首先编写一个实体类:
package com.zking.reflect; public class Student { private int sid; private String sname; public Integer age; private double score; private String clazz; public double getScore() { return score; } public void setScore(double score) { this.score = score; } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public Student(int sid, String sname, Integer age, double score, String clazz) { super(); this.sid = sid; this.sname = sname; this.age = age; this.score = score; this.clazz = clazz; } static{ System.out.println("加载进jvm中!"); } public Student() { super(); System.out.println("调用无参构造方法创建了一个学生对象"); } public Student(int sid) { super(); this.sid = sid; System.out.println("调用带一个参数的构造方法创建了一个学生对象"); } @Override public String toString() { return "Student [sid=" + sid + ", sname=" + sname + ", age=" + age + "]"; } public Student(int sid, String sname) { super(); this.sid = sid; this.sname = sname; System.out.println("调用带二个参数的构造方法创建了一个学生对象"); } @SuppressWarnings("unused") private Student(Integer age) { System.out.println("调用Student类私有的构造方法创建一个学生对象"); this.age = age; } public int getSid() { return sid; } public void setSid(int i) { this.sid = i; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public void hello() { System.out.println("你好!我是" + this.sname); } public void hello(String name) { System.out.println(name + "你好!我是" + this.sname); } @SuppressWarnings("unused") private Integer add(Integer a, Integer b) { return new Integer(a.intValue() + b.intValue()); } }2.DButil类,用于连接数据库
package com.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public final class DBUtil { private static String DRIVER_NAME = "com.mysql.jdbc.Driver"; private static String DB_URL = "jdbc:mysql://localhost:3306/t234?useUnicode=true&characterEncoding=utf-8&useSSL=false"; private static String DB_USER = "root"; private static String DB_PASSWORD = "123456"; private DBUtil() { } static { try { Class.forName(DRIVER_NAME); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConection() throws SQLException { Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); return connection; } public static void closeDB(ResultSet rs, Statement ps, Connection con) { try { if (rs != null && !rs.isClosed()) { rs.close(); } if (ps != null && !ps.isClosed()) { ps.close(); } if (con != null && !con.isClosed()) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } } public static void closeDB(ResultSet rs, Statement ps) { try { if (rs != null && !rs.isClosed()) { rs.close(); } if (ps != null && !ps.isClosed()) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } } }3.PageBean类
package com.util; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.mysql.jdbc.StringUtils; public class PageBean { /** * 页码 */ private int page = 1; /** * 每页显示的记录数 */ private int rows = 10; /** * 总记录数 */ private int total = 0; /** * 是否分页 */ private boolean pagination = true; /** * 记录查询的url,以便于点击分页时再次使用 */ private String url; /** * 存放请求参数,用于生成隐藏域中的元素 */ private Map<String, String[]> parameterMap; /** * 根据传入的Request初始化分页对象 * * @param request */ public void setRequest(HttpServletRequest request) { //每一次查询获取页码 if (!StringUtils.isNullOrEmpty(request.getParameter("page"))) { this.page = Integer.valueOf(request.getParameter("page")); } //每一页的显示条数 if (!StringUtils.isNullOrEmpty(request.getParameter("rows"))) { this.rows = Integer.valueOf(request.getParameter("rows")); } //是否分页 if (!StringUtils.isNullOrEmpty(request.getParameter("pagination"))) { this.pagination = Boolean.valueOf(request.getParameter("pagination")); } this.url = request.getRequestURI(); this.parameterMap = request.getParameterMap(); request.setAttribute("pageBean", this); } 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 boolean isPagination() { return pagination; } public void setPagination(boolean pagination) { this.pagination = pagination; } 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; } // 计算起始页码,从0开始,每一页显示10条数据 //0--9 (1-1)*10 //10--19 (2-1)*10 public int getStartIndex() { return (this.page - 1) * this.rows; } // 获取总页数,如果判断!=0(存在余数),那么就会加一行显示多余的条数 public int getTotalPage() { if (this.getTotal() % this.rows == 0) { return this.getTotal() / this.rows; } else { return this.getTotal() / this.rows + 1; } } // 上一页,如果判断-1后>0,那么就可以进行上一页 public int getPreviousPage() { return this.page - 1 > 0 ? this.page - 1 : 1; } // 下一页,如果判断+1后>总页数,那么就不可以进行下一页 public int getNextPage() { return this.page + 1 > getTotalPage() ? getTotalPage() : this.page + 1; } }4.BaseDao类
package com.util; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.mysql.jdbc.StringUtils; public class PageBean { /** * 页码 */ private int page = 1; /** * 每页显示的记录数 */ private int rows = 10; /** * 总记录数 */ private int total = 0; /** * 是否分页 */ private boolean pagination = true; /** * 记录查询的url,以便于点击分页时再次使用 */ private String url; /** * 存放请求参数,用于生成隐藏域中的元素 */ private Map<String, String[]> parameterMap; /** * 根据传入的Request初始化分页对象 * * @param request */ public void setRequest(HttpServletRequest request) { //每一次查询获取页码 if (!StringUtils.isNullOrEmpty(request.getParameter("page"))) { this.page = Integer.valueOf(request.getParameter("page")); } //每一页的显示条数 if (!StringUtils.isNullOrEmpty(request.getParameter("rows"))) { this.rows = Integer.valueOf(request.getParameter("rows")); } //是否分页 if (!StringUtils.isNullOrEmpty(request.getParameter("pagination"))) { this.pagination = Boolean.valueOf(request.getParameter("pagination")); } this.url = request.getRequestURI(); this.parameterMap = request.getParameterMap(); request.setAttribute("pageBean", this); } 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 boolean isPagination() { return pagination; } public void setPagination(boolean pagination) { this.pagination = pagination; } 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; } // 计算起始页码,从0开始,每一页显示10条数据 //0--9 (1-1)*10 //10--19 (2-1)*10 public int getStartIndex() { return (this.page - 1) * this.rows; } // 获取总页数,如果判断!=0(存在余数),那么就会加一行显示多余的条数 public int getTotalPage() { if (this.getTotal() % this.rows == 0) { return this.getTotal() / this.rows; } else { return this.getTotal() / this.rows + 1; } } // 上一页,如果判断-1后>0,那么就可以进行上一页 public int getPreviousPage() { return this.page - 1 > 0 ? this.page - 1 : 1; } // 下一页,如果判断+1后>总页数,那么就不可以进行下一页 public int getNextPage() { return this.page + 1 > getTotalPage() ? getTotalPage() : this.page + 1; } }5.StudentDdao类,继承BaseDao\
package com.util; 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 java.util.Objects; import com.mysql.jdbc.StringUtils; import com.zking.reflect.Student; public class StudentDao extends BaseDao { public List<Student> getStudents02(String sname, PageBean pageBean) { String sql = "select * from t_student t "; List<Object> param = new ArrayList<>(); if (!StringUtils.isNullOrEmpty(sname)) { sql += "where sname like ?"; param.add(sname + "%"); } List<Student> list = this.query(sql, param.toArray(), pageBean, new IConvert<Student>() { @Override public List<Student> convert(ResultSet rs) throws SQLException { List<Student> list = new ArrayList<>(); while (rs.next()) { Student stu = new Student(); stu.setSid(rs.getInt("sid")); stu.setSname(rs.getString("sname")); stu.setScore(rs.getDouble("score")); stu.setClazz(rs.getString("class")); } return list; } }); return list; } public static void main(String[] args) { StudentDao dao = new StudentDao(); PageBean pageBean = new PageBean(); pageBean.setRows(5); List<Student> students = dao.getStudents02("张", new PageBean()); students.forEach(s -> System.out.println(s)); } }运行结果:
优化之后代码(封装成一个标签库):
1.编写tag类:
package com.zking.tag; import java.io.IOException; import java.util.Map; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import com.util.PageBean; public class PagingTag extends BodyTagSupport { private PageBean pageBean; public void setPageBean(PageBean pageBean) { this.pageBean = pageBean; } @Override public int doStartTag() { JspWriter out = this.pageContext.getOut(); try { out.print(buildHtml()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return SKIP_BODY; } // 动态生成分页html元素 private String buildHtml() { String pagingToll = "<div style=\"text-align: right; width: 98%;\">\r\n" + " 第" + pageBean.getPage() + "页 共" + pageBean.getTotalPage() + "条记录 \r\n" + " <a href=\"javascript:goPage(1)\">首页</a> <a\r\n" + " href=\"javascript:goPage(" + pageBean.getPreviousPage() + ")\">上页</a> \r\n" + " <a href=\"javascript:goPage(" + pageBean.getNextPage() + ")\">下页</a> \r\n" + " <a href=\"javascript:goPage(" + pageBean.getTotalPage() + ")\">尾页</a> \r\n" + " 第<input type=\"text\" size=\"2\" id=\"pageNumber\"\r\n" + " onkeyup=\"toPage(event,this.value)\" /> <a href=\"javascript:goPage(docment.getElementById('pageNumber').value)\">GO</a>" + " </div>"; // 用于隐藏表单,用于分页查询 String hiddenForm = "<form action=\"" + pageBean.getUrl() + " id=\"pagingForm\" method=\"post\"><form action=\"${pageBean.url}\" id=\"pagingForm\" method=\"post\">"; hiddenForm += "<input type=\" hidden\" name=\"page\" value=\"" + pageBean.getPage() + "\" />"; // 获取到所有的查询参数 Map<String, String[]> parameterMap = pageBean.getParameterMap(); // 数组就相当于你的爱好,那么爱好就包括,唱跳,rap,篮球。。。 for (Map.Entry<String, String[]> param : parameterMap.entrySet()) { // 获取所有的键、值 String paramName = param.getKey(); if ("page".equals(paramName)) continue; String[] values = param.getValue(); for (String val : values) { hiddenForm += "<input type=\" hidden\" name=\"" + paramName + "\" value=\"" + val + "\" />"; } hiddenForm += "</form>"; } String js = "<script type=\"text/javascript\">\r\n" + " function goPage(pageNum) {\r\n" + " let form = document.getElementById = (\"pagingForm\");\r\n" + " form.page.value = pageNum;\r\n" + " form.submit();\r\n" + " }\r\n" + " function toPage(e, pageNum) {\r\n" + " if (e.keyCode == 13) {\r\n" + " goPage(pageNum);\r\n" + " }\r\n" + " }\r\n" + " </script>"; return pagingToll + hiddenForm + js; } }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>/nlsy</uri> <tag> <name>out</name> <tag-class>com.zking.tag.OutTag</tag-class> <body-content>empty</body-content> <attribute> <name>val</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <description>out标签val属性,用于输出val的值</description> </attribute> <attribute> <name>defaultVal</name> <required>false</required> <rtexprvalue>false</rtexprvalue> <description>用于定义默认值</description> </attribute> </tag> <tag> <name>if</name> <tag-class>com.zking.tag.IfTag</tag-class> <body-content>jsp</body-content> <attribute> <name>test</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <description>if标签</description> </attribute> </tag> <tag> <name>foreach</name> <tag-class>com.zking.tag.ForeachTag</tag-class> <body-content>jsp</body-content> <attribute> <name>items</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>var</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag> <tag> <name>paging</name> <tag-class>com.zking.tag.PagingTag</tag-class> <body-content>empty</body-content> <description>分页标签</description> <attribute> <name>pageBean</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>3.在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="n" uri="/nlsy"%> <!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>Insert title here</title> </head> <body> <h1>学生信息</h1> <form action="<%=request.getContextPath()%>/students" method="post"> <input type="text" name="sname"> <input type="submit" value="查询"> </form> <table border="1" style="width: 98%;"> <tr> <td>学号</td> <td>姓名</td> <td>年龄</td> <td>备注</td> </tr> <c:forEach items="${students}" var="student"> <tr> <td>${student.sid}</td> <td>${student.sname}</td> <td>${student.age}</td> <td>${student.remark}</td> </tr> </c:forEach> </table> <n:paging pageBean="${pageBean }"/> </body> </html>运行结果:
边栏推荐
- Notification设置的小图标显示的是小方块
- 向下扎根,向上生长,探寻华为云AI的“根”力量
- The difference between overloading and rewriting
- Force deduction solution summary 919 complete binary tree inserter
- [PMP learning notes] Chapter 1 Introduction to PMP System
- AI chief architect 12 AICA industrial landing analysis under the industrial production process optimization scenario
- Ribbon execution logic source code analysis
- Sichuan cuisine menu (I)
- QT operation to solve large amount of duplicate data
- JS makes elements get or lose focus
猜你喜欢

Deep recursion, deep search DFS, backtracking, paper cutting learning.
![[literature reading] - HRL -[hrl with universal policies for multi step robotic control]](/img/34/06d5ba3af4e6e775a335324c020161.png)
[literature reading] - HRL -[hrl with universal policies for multi step robotic control]

The new media operation strategy (taking xiaohongshu as an example) helps you quickly master the creative method of popular models
![[natural language processing] [vector representation] augsbert: improve the data enhancement method of Bi encoders for paired sentence scoring tasks](/img/9a/9bb00abf7804d61d3408143e5e4bda.png)
[natural language processing] [vector representation] augsbert: improve the data enhancement method of Bi encoders for paired sentence scoring tasks

Opencv compile and call GPU version

Extended configuration of static routing in the second experiment

【接口性能优化】索引失效的原因以及如何进行SQL优化

recyclerview计算滑动距离之computeHorizontalScrollExtent-computeHorizontalScrollRange-computeHorizontalScrol

连续三年成为云AI服务领导者,亚马逊云科技做对了什么?

Hcie is finally in hand, and the road begins
随机推荐
[PMP learning notes] Chapter 1 Introduction to PMP System
Websocket summary
We media people must have four material websites, and don't worry about finding materials anymore
recyclerview计算滑动距离之computeHorizontalScrollExtent-computeHorizontalScrollRange-computeHorizontalScrol
为啥谷歌的内部工具不适合你?
Express framework
栈与Stack类
JD quick navigation box
Sichuan cuisine menu (I)
Stack simulation queue
Summary of traversal methods of six sets list, set, map, queue, deque and stack
内存分页与调优,内核与用户空间
自媒体人必备的4个资源工具,每一个都很实用
Rental experience post
[文献阅读] - HRL -[HRL with Universal Policies for Multi-Step Robotic Manipulation]
invalid syntax
IPFs of Internet Protocol
JVM memory area
Summary of common methods of string:
Recommend short videos every week: more and more smart devices need collaboration, posing a greater challenge to the development of the Internet of things?

