当前位置:网站首页>General paging function

General paging function

2022-07-25 23:06:00 A Nara Senyu

Catalog

General idea :

Code before optimization :

1. First write an entity class :

2.DButil class , Used to connect to the database

3.PageBean class

4.BaseDao class

5.StudentDdao class , Inherit BaseDao\

Running results :

After optimization, the code ( Encapsulated into a tag library ):

1. To write tag class :

2. To write tld file :

3. stay jsp page , Call run


General idea :


1)  In order to improve query performance and save network traffic , Query only the specified number of records at a time , Not all of them ,
 It is very useful when the quantity is large 
2) When clicking on the next page or the data of the specified page , Will bring all the query conditions , Execute the query again 

Code before optimization :


1. First write an entity class :

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(" Load in jvm in !");
	}

	public Student() {
		super();
		System.out.println(" Call the parameterless constructor to create a student object ");
	}

	public Student(int sid) {
		super();
		this.sid = sid;
		System.out.println(" Calling the constructor with one parameter creates a student object ");
	}

	@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(" Call the constructor with two parameters to create a student object ");
	}

	@SuppressWarnings("unused")
	private Student(Integer age) {
		System.out.println(" call Student Class private constructor to create a student object ");
		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(" Hello ! I am a " + this.sname);
	}

	public void hello(String name) {
		System.out.println(name + " Hello ! I am a " + this.sname);
	}

	@SuppressWarnings("unused")
	private Integer add(Integer a, Integer b) {
		return new Integer(a.intValue() + b.intValue());
	}
}

2.DButil class , Used to connect to the database

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 class

package com.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.mysql.jdbc.StringUtils;

public class PageBean {

	/**
	 *  Page number 
	 */
	private int page = 1;

	/**
	 *  Number of records per page 
	 */
	private int rows = 10;

	/**
	 *  Total number of records 
	 */
	private int total = 0;

	/**
	 *  Pagination or not 
	 */
	private boolean pagination = true;

	/**
	 *  Record the inquiry url, So that it can be used again when clicking paging 
	 */
	private String url;

	/**
	 *  Store request parameters , Used to generate elements in hidden fields 
	 */
	private Map<String, String[]> parameterMap;

	/**
	 *  Based on the incoming Request Initialize paging object 
	 * 
	 * @param request
	 */
	public void setRequest(HttpServletRequest request) {
		// Get the page number for each query 
		if (!StringUtils.isNullOrEmpty(request.getParameter("page"))) {
			this.page = Integer.valueOf(request.getParameter("page"));
		}
		// Number of display bars per page 
		if (!StringUtils.isNullOrEmpty(request.getParameter("rows"))) {
			this.rows = Integer.valueOf(request.getParameter("rows"));
		}
		// Pagination or not 
		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;
	}
	
	//  Calculate the starting page number , from 0 Start , Each page shows 10 Data 
	//0--9  (1-1)*10
	//10--19	(2-1)*10
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	//  Get total pages , If you judge !=0( There is remainder ), Then a line will be added to show the excess number 
	public int getTotalPage() { 
		if (this.getTotal() % this.rows == 0) {
			return this.getTotal() / this.rows;
		} else {
			return this.getTotal() / this.rows + 1;
		}
	}

	//  The previous page , If you judge -1 after >0, Then you can go to the previous page 
	public int getPreviousPage() {
		return this.page - 1 > 0 ? this.page - 1 : 1;
	}

	//  The next page , If you judge +1 after > Total number of pages , Then you can't go to the next page 
	public int getNextPage() {
		return this.page + 1 > getTotalPage() ? getTotalPage() : this.page + 1;
	}

}

4.BaseDao class

package com.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.mysql.jdbc.StringUtils;

public class PageBean {

	/**
	 *  Page number 
	 */
	private int page = 1;

	/**
	 *  Number of records per page 
	 */
	private int rows = 10;

	/**
	 *  Total number of records 
	 */
	private int total = 0;

	/**
	 *  Pagination or not 
	 */
	private boolean pagination = true;

	/**
	 *  Record the inquiry url, So that it can be used again when clicking paging 
	 */
	private String url;

	/**
	 *  Store request parameters , Used to generate elements in hidden fields 
	 */
	private Map<String, String[]> parameterMap;

	/**
	 *  Based on the incoming Request Initialize paging object 
	 * 
	 * @param request
	 */
	public void setRequest(HttpServletRequest request) {
		// Get the page number for each query 
		if (!StringUtils.isNullOrEmpty(request.getParameter("page"))) {
			this.page = Integer.valueOf(request.getParameter("page"));
		}
		// Number of display bars per page 
		if (!StringUtils.isNullOrEmpty(request.getParameter("rows"))) {
			this.rows = Integer.valueOf(request.getParameter("rows"));
		}
		// Pagination or not 
		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;
	}
	
	//  Calculate the starting page number , from 0 Start , Each page shows 10 Data 
	//0--9  (1-1)*10
	//10--19	(2-1)*10
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	//  Get total pages , If you judge !=0( There is remainder ), Then a line will be added to show the excess number 
	public int getTotalPage() { 
		if (this.getTotal() % this.rows == 0) {
			return this.getTotal() / this.rows;
		} else {
			return this.getTotal() / this.rows + 1;
		}
	}

	//  The previous page , If you judge -1 after >0, Then you can go to the previous page 
	public int getPreviousPage() {
		return this.page - 1 > 0 ? this.page - 1 : 1;
	}

	//  The next page , If you judge +1 after > Total number of pages , Then you can't go to the next page 
	public int getNextPage() {
		return this.page + 1 > getTotalPage() ? getTotalPage() : this.page + 1;
	}

}

5.StudentDdao class , Inherit 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(" Zhang ", new PageBean());
		students.forEach(s -> System.out.println(s));
	}

}

Running results :

 

After optimization, the code ( Encapsulated into a tag library ):


1. To write tag class :

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;

	}

	//  Dynamically generate paging html Elements 
	private String buildHtml() {

		String pagingToll = "<div style=\"text-align: right; width: 98%;\">\r\n" + "		 The first " + pageBean.getPage()
				+ " page &nbsp;&nbsp;&nbsp;  common " + pageBean.getTotalPage() + " Bar record &nbsp;&nbsp;&nbsp;\r\n"
				+ "		<a href=\"javascript:goPage(1)\"> home page </a>&nbsp;&nbsp;&nbsp; <a\r\n"
				+ "			href=\"javascript:goPage(" + pageBean.getPreviousPage() + ")\"> page-up key </a>&nbsp;&nbsp;&nbsp;\r\n"
				+ "		<a href=\"javascript:goPage(" + pageBean.getNextPage() + ")\"> next page </a>&nbsp;&nbsp;&nbsp;\r\n"
				+ "		<a href=\"javascript:goPage(" + pageBean.getTotalPage() + ")\"> Tail page </a>&nbsp;&nbsp;&nbsp;\r\n"
				+ "		 The first <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>";
		//  Used to hide forms , Used for paging queries 
		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() + "\" />";
		//  Get all the query parameters 
		Map<String, String[]> parameterMap = pageBean.getParameterMap();
		//  Arrays are your hobby , Then hobbies include , Singing and dancing ,rap, Basketball ...
		for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
			//  Get all keys 、 value 
			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. To write tld file :

<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
   "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<!--  Tag library descriptor  -->
<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 label val attribute , For output val Value </description>
		</attribute>
		<attribute>
			<name>defaultVal</name>
			<required>false</required>
			<rtexprvalue>false</rtexprvalue>
			<description> Used to define default values </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 label </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> Pagination label </description>
	<attribute>
		<name>pageBean</name>
		<required>true</required>
		<rtexprvalue>true</rtexprvalue>
	</attribute>
	</tag>
</taglib>

3. stay jsp page , Call run

<%@ 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> Student information </h1>

	<form action="<%=request.getContextPath()%>/students" method="post">
		<input type="text" name="sname"> <input type="submit"
			value=" Inquire about ">
	</form>

	<table border="1" style="width: 98%;">

		<tr>
			<td> Student number </td>
			<td> full name </td>
			<td> Age </td>
			<td> remarks </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>

Running results :

 

 

原网站

版权声明
本文为[A Nara Senyu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/206/202207252302009065.html