当前位置:网站首页>通用分页功能
通用分页功能
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>运行结果:
边栏推荐
- [tensorflow] about seed
- 新媒体运营策略(以小红书为例)帮助你快速掌握爆款创作方法
- 【自然语言处理】【向量表示】AugSBERT:改善用于成对句子评分任务的Bi-Encoders的数据增强方法
- The difference between "rewrite" and "overload"
- We media people must have four resource tools, each of which is very practical
- Interview question 17.11. word distance ●●
- Anaconda~Upload did not complete.
- Network Security Learning (16)
- Understanding of forward proxy and reverse proxy
- Deploy flash based websites using Google cloud
猜你喜欢

AI chief architect 12 AICA industrial landing analysis under the industrial production process optimization scenario
![[文献阅读] - HRL -[HRL with Universal Policies for Multi-Step Robotic Manipulation]](/img/34/06d5ba3af4e6e775a335324c020161.png)
[文献阅读] - HRL -[HRL with Universal Policies for Multi-Step Robotic Manipulation]

Qt5.12 installation error prompt: c:\qt5.12.11\vcredist\vcredist_ msvc2019_ x86.exe /norestart /q

Hcie is finally in hand, and the road begins

MySQL data type

内存分页与调优,内核与用户空间

Deep recursion, deep search DFS, backtracking, paper cutting learning.

How to obtain the cash flow data of advertising services to help analyze the advertising effect?

Matrixcube unveils the complete distributed storage system matrixkv implemented in 102-300 lines

驱动板网线直连电脑共享网络配置
随机推荐
Express framework
Day 3 experiment
access-list vs ip access-list
Understanding of forward proxy and reverse proxy
Hj7 take approximate value
Circle detection and line detection of PCL
面试题 17.11. 单词距离 ●●
单模型常识推理首超人类!HFL登顶OpenBookQA挑战赛
Use of qvariant
每周推荐短视频:需要协同的智能设备越来越多,给物联网开发提出更大挑战?
How painful is it to write unit tests?
[PTA] 7-24 minimum fraction (15 points)
Hcie is finally in hand, and the road begins
连续三年成为云AI服务领导者,亚马逊云科技做对了什么?
CUDA environment construction
互联网协议之 IPFS
MathType installation and solution cannot solve the problem of crtl+v
QT operation to solve large amount of duplicate data
Simple setting of drop-down triangle
Vs2017 compilation encountered the error HResult e returned by the call of COM component_ FAIL

