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

General paging function

2022-07-23 16:46:00 I don't want this brain anymore

Catalog

Paging information entity (PageBean)

Background paging data query

1. Processing flow

2. Realization

restructure - Extract common method

Pagination label

1. Prepare one Servlet

2. Filter to solve the problem of Chinese garbled

3. Add paging function

Encapsulate paging labels


Preface : In the previous articles, I wrote xml,java The reflex mechanism , Customize jsp label , In this article, I will use the knowledge of the previous articles to write a general paging function . 

Paging information entity (PageBean)

  Used to store and pass paging parameters , The main contents are as follows :

  • Page number , Pass it from the page
  • Number of lines per page , It can also be passed from
  • Total number of records , Statistics from the database
  • Pagination or not , If false, Then query all records
  • Query parameters , When clicking on the previous or next page, you need to carry all the query parameters entered by the user
  • In addition, the previous page , next page , Total pages, etc

Reference code :

package com.zking.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) {
		
		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;
	}

	// Calculate the starting page number 
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}
	
	// Get total pages 
	public int getTotalPage() {
		if (this.getTotal() % this.rows == 0) {
			return this.getTotal() / this.rows;
		} else {
			return this.getTotal() / this.rows + 1;
		}
	}

	// The previous page 
	public int getPreviousPage() {
		return this.page - 1 > 0 ? this.page - 1 : 1;
	}
	
	// The next page 
	public int getNextPage() {
		return this.page + 1 > getTotalPage() ? getTotalPage() : this.page + 1;
	}
	
}

Background paging data query

1. Processing flow

  1.   The total number of records that meet the query criteria
  2.   Query the data of the current page that meets the conditions
  3.   The query conditions of the above two steps should be consistent

flow chart :

2. Realization

1. To simplify the database (mysql) operation , Need one DBUtil Tool class .

package com.zking.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {

	// Get the drive 
	private static String DRIVER_NAME = "com.mysql.jdbc.Driver";

	// Connection statement 
	private static String DB_URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";

	// user name 
	private static String DB_USER = "root";

	// password 
	private static String DB_PASSWORD = "910814";

	private DBUtil() {
	}

	static {
		// The driver only needs to be loaded once, so it is placed in the static code block 
		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();
		}
	}

}

2. And then write a Student Entity classes are examples , And the corresponding database table .

 

  You guys should pay attention to , Column names in my database class In my entity class is clazz, This is what I forgot when I wrote my name class stay java Is the keyword 〒▽〒, But I'm too lazy to change (.・ω・.), Make do with it .

package com.zking.model;

public class Student {

	private Integer sid;
	
	private String sname;
	
	private Integer score;
	
	private String clazz;


	public Integer getSid() {
		return sid;
	}

	public void setSid(Integer sid) {
		this.sid = sid;
	}

	public String getSname() {
		return sname;
	}

	public void setSname(String sname) {
		this.sname = sname;
	}

	public Integer getScore() {
		return score;
	}

	public void setScore(Integer score) {
		this.score = score;
	}

	
	public String getClazz() {
		return clazz;
	}

	public void setClazz(String clazz) {
		this.clazz = clazz;
	}
	
	@Override
	public String toString() {
		return "Student [sid=" + sid + ", sname=" + sname + ", score=" + score + ", clazz=" + clazz + "]";
	}
}

3. Paging query function ( Write a StudentDao)

package com.zking.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.zking.model.Student;
import com.zking.util.BaseDao.ICovent;

public class StudentDao {

	public List<Student> getStudents(String sname, PageBean pageBean) {

		//  To write sql sentence 
		String sql = "select * from student ";
		if (!Objects.isNull(sname) && sname.length() > 0) {
			sql += " where sname like ?";
		}

		List<Student> students = new ArrayList<>();

		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		//  No paging 
		if (pageBean == null || !pageBean.isPagination()) {
			try {
				con = DBUtil.getConection();
				ps = con.prepareStatement(sql);

				//  Set query parameters 
				if (sname != null) {
					ps.setObject(1, sname);
				}
				rs = ps.executeQuery();
				while (rs.next()) {
					Student stu = new Student();
					stu.setSid(rs.getInt("sid"));
					stu.setSname(rs.getString("sname"));
					stu.setScore(rs.getInt("score"));
					stu.setClazz(rs.getString("class"));
					students.add(stu);
				}

			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				DBUtil.closeDB(rs, ps, con);
			}
		} else {
			//  Paging is required 
			String countSql = "SELECT COUNT(*) FROM (" + sql + ")tmp";
			try {
				con = DBUtil.getConection();
				ps = con.prepareStatement(sql);

				//  Set query parameters 
				if (sname != null) {
					ps.setObject(1, sname);
				}

				rs = ps.executeQuery();

				if (rs.next()) {
					Integer total = rs.getInt(1);
					pageBean.setTotal(total);
				}

				//  Judge whether the total number of records is greater than 0, If it is greater than 0 It means there are records , You need to query the current record 
				//  If not, go straight back to 
				if (pageBean.getTotal() <= 0) {
					return students;
				}
				//  Query the data of the current page 
				String pagingSql = sql + "limit" + pageBean.getStartIndex() + "," + pageBean.getRows();
				//  Set query parameters 
				if (sname != null) {
					ps.setObject(1, sname);
				}
				rs = ps.executeQuery();
				while (rs.next()) {
					Student stu = new Student();
					stu.setSid(rs.getInt("sid"));
					stu.setSname(rs.getString("sname"));
					stu.setScore(rs.getInt("score"));
					stu.setClazz(rs.getString("class"));
					students.add(stu);
				}

			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				DBUtil.closeDB(rs, ps, con);
			}
		}

		return students;
	}

	
	
	public static void main(String[] args) {
		StudentDao dao = new StudentDao();
		List<Student> students = dao.getStudents(null, new PageBean());
		students.forEach(t-> System.out.println(t));
	}
}

restructure - Extract common method

(1) In order to extract public methods , We need to find out the common parts in the above internship , And differentiation .

  • As long as it is paging , The total number of records will be counted , The statistics of total records are in business sql There is a select count(*) There are rules to follow , Can be used in general

  • As long as it is paging , Then encapsulate paging sql There are also rules to follow ( In the business sql After add limit Clause is enough ), Can be used in general

  • Because the business entity corresponding to each query ( The model ) Different , therefore ORM The mapping part cannot be general

(2) Common method encapsulation ideas

  • Encapsulate the universal part into the template

  • Differentiation part ( That is, the non universal part ), You can define a processing interface , In order to pass in the personalized implementation part through parameters

(3) Concrete realization
General paging query template class :

package com.zking.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;


public final class BaseDao {
	
private BaseDao() {}
	
	// Callback function interface 
	public static interface ICovent<T> {
		List<T> convent(ResultSet rs) throws SQLException;
	}
	
	public static <T> List<T> query(String sql, 
			List<Object> paramList, 
			PageBean pageBean,
			ICovent<T> covent
			) {
		
		Object[] params = paramList.toArray();
		
		List<T> students = new ArrayList<>();
		
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		if(pageBean == null || !pageBean.isPagination()) {
			try {
				con = DBUtil.getConection();
				ps = con.prepareStatement(sql);
				
				// Set query parameters 
				int i = 1;
				for(Object param: params) {
					ps.setObject(i, param);
					i++;
				}
				
				rs = ps.executeQuery();
				
				// Through the callback function passed in by the user , Perform conversion 
				students = covent.convent(rs);
				
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				DBUtil.closeDB(rs, ps, con);
			}
		} else {
			// Paging is required 
			String countSql = "select COUNT(*) from (" + sql + ") tmp";
			
			try {
				con = DBUtil.getConection();
				ps = con.prepareStatement(countSql);
				// Set query parameters 
				int i = 1;
				for(Object param: params) {
					ps.setObject(i, param);
					i++;
				}
				
				rs = ps.executeQuery();
				if(rs.next()) {
					Integer total = rs.getInt(1);
					pageBean.setTotal(total);
				}
				
				// Judge whether the total number of records is greater than 0, If it is greater than zero, it means there is a record , Need to query the current record 
				// If not, go straight back to 
				if(pageBean.getTotal() <= 0) {
					return students;
				}
				
				// Query the data of the current industry 
				String pagingSql = sql + " limit " + pageBean.getStartIndex() + ", " + pageBean.getRows();
				ps = con.prepareStatement(pagingSql);
				// Set query parameters 
				int j = 1;
				for(Object param: params) {
					ps.setObject(j, param);
					j++;
				}
				rs = ps.executeQuery();
				
				// Change part 
				students = covent.convent(rs);
				
			} catch (SQLException e) {
				e.printStackTrace();
			}  finally {
				DBUtil.closeDB(rs, ps, con);
			}
			
		}
		
		return students;
	}
}

After encapsulating the common method , Remember to StudentDao Code modification

package com.zking.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.zking.model.Student;
import com.zking.util.BaseDao.ICovent;

public class StudentDao {
	
	
	public List<Student> getStudents(String sname, PageBean pageBean) {
		// structure sql sentence      Change part 
		String sql = "select * from student ";
		List<Object> param = new ArrayList<>();
		if (!Objects.isNull(sname) && sname.length() > 0) {
			sql += " where sname like ?";
			param.add("%"+sname+"%");
		}
		List<Student> list = BaseDao.query(sql, param, pageBean, new ICovent<Student> () {
			
			public List<Student> convent(ResultSet rs) throws SQLException {
				List<Student> students = new ArrayList<>();
				while(rs.next()) {
					Student stu = new Student();
					stu.setSid(rs.getInt("sid"));
					stu.setSname(rs.getString("sname"));
					stu.setScore(rs.getInt("score"));
					stu.setClazz(rs.getString("class"));
					students.add(stu);
				}
				return students;
			}
			
		});
		return list;
	}
	
	
	public static void main(String[] args) {
		StudentDao dao = new StudentDao();
		List<Student> students = dao.getStudents(null, new PageBean());
		students.forEach(t-> System.out.println(t));
	}
}

Pagination label

1. Prepare one Servlet

Prepare one servlet Used to process requests , Get the data in the database , And forward to the result display page .

package com.zking.servlet;

import java.io.IOException;
import java.util.List;

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.zking.model.Student;
import com.zking.util.PageBean;
import com.zking.util.StudentDao;

@WebServlet("/students")
public class StudentServlet extends HttpServlet{

	private StudentDao dao = new StudentDao();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		PageBean pageBean = new PageBean();
		pageBean.setRequest(req);
		
		String sname =req.getParameter("sname");
		List<Student> students = dao.getStudents(sname, pageBean);
		req.setAttribute("students", students);

		req.getRequestDispatcher("/student.jsp").forward(req, resp);
	}
	
}

2. Filter to solve the problem of Chinese garbled

package com.zking.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *  Jumble handling 
 * @author zjjt
 *
 */
public class EncodingFiter implements Filter{

	private String encoding = "UTF-8";//  Default character set 

	public EncodingFiter() {
		super();
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		//  Chinese processing must be put into  chain.doFilter(request, response) Method front 
		res.setContentType("text/html;charset=" + this.encoding);
		if (req.getMethod().equalsIgnoreCase("post")) {
			req.setCharacterEncoding(this.encoding);
		} else {
			Map map = req.getParameterMap();//  Save all parameter names = Parameter values ( Array ) Of Map aggregate 
			Set set = map.keySet();//  Take out all parameter names 
			Iterator it = set.iterator();
			while (it.hasNext()) {
				String name = (String) it.next();
				String[] values = (String[]) map.get(name);//  Take out the parameter value [ notes : The parameter value is an array ]
				for (int i = 0; i < values.length; i++) {
					values[i] = new String(values[i].getBytes("ISO-8859-1"),
							this.encoding);
				}
			}
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		String s = filterConfig.getInitParameter("encoding");//  Read web.xml The character set configured in the file 
		if (null != s && !s.trim().equals("")) {
			this.encoding = s.trim();
		}
	}

}

stay web.xml( The new project comes with xml file ) To configure

<filter>
  <filter-name>encodingFiter</filter-name>
  <filter-class>com.zking.util.EncodingFiter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>encodingFiter</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>

3. Add paging function

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!DOCTYPE html>
<html>
<head>
<meta 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> achievement </td>
			<td> class </td>
		</tr>

		<c:forEach items="${students}" var="student">
			<tr>
				<td>${student.sid}</td>
				<td>${student.sname}</td>
				<td>${student.score}</td>
				<td>${student.clazz}</td>
			</tr>
		</c:forEach>

	</table>

<div style="text-align: right; width:98%;">
		 The first ${pageBean.page} page &nbsp;&nbsp;&nbsp;
		 common ${pageBean.total} Bar record &nbsp;&nbsp;&nbsp;
		<a href="javascript: goPage(1);"> home page </a>&nbsp;&nbsp;&nbsp;
		<a href="javascript: goPage(${pageBean.previousPage});"> page-up key </a>&nbsp;&nbsp;&nbsp; 
		<a href="javascript: goPage(${pageBean.nextPage});"> next page </a>&nbsp;&nbsp;&nbsp; 
		<a href="javascript: goPage(${pageBean.totalPage});"> Tail page </a>&nbsp;&nbsp;&nbsp;
		 The first <input type="text" size="2" id="pageNumber" onkeypress="toPageNumber(event,this.value)"/> 
		<a href="javascript: goPage(document.getElementById('pageNumber').value);">GO</a>
	</div>
	
	<!--  Hide expression , Save query parameters when paging with  -->
	<form action="${pageBean.url}" id="pagingForm" method="post">
		<input type="hidden" name="page" value="${pageBean.page}"/>
		<!--  First, only consider the query parameters of this function , No consideration of commonality ( Different functions have different parameters ) -->
		<input type="hidden" name="sname" value="<%=request.getParameter("sname")%>"/>
	</form>
	
</body>

<script>
function goPage(pageNum) {
	debugger;
	let form = document.getElementById("pagingForm");
	let lastPage = '${pageBean.totalPage}';
	if(pageNum > lastPage) pageNum = lastPage;
	if(pageNum < 1) pageNum = 1;
	form.page.value = pageNum;
	form.submit();
}

function toPageNumber(event,pn) {
	//debugger;
	if(event.keyCode ==  13) {
		let form = document.getElementById("pagingForm");
		form.page.value = pn;
		form.submit();
	}
}
</script>

</body>
</html>

So far, , The paging function has been realized .

But there are still a few problems :

  1. If other functions require paging , You need to copy a lot of code to reuse this function
  2. What if the system needs to modify the display style of the paging toolbar ?

In order to solve these problems, we need to encapsulate the paging label . 

Encapsulate paging labels

In order to facilitate code reuse , And maintainability , We encapsulate the paging function with a custom tag ( In fact, it is the code originally written in the page , By moving into the custom tag ), Developing custom tags is divided into three steps :

  • Write helper classes
  • Write label description file
  • Introduce the tag library on the page , And use

Write helper classes

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.zking.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.println(buildHtml());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return SKIP_BODY;
	}
	
	
	// Construct paged page output 
	private String buildHtml() {
		
		String pagingTool = "<div style=\"text-align: right; width:98%;\">\r\n" + 
				"		 The first "+pageBean.getPage()+" page &nbsp;&nbsp;&nbsp;\r\n" + 
				"		 common "+pageBean.getTotal()+" Bar record &nbsp;&nbsp;&nbsp;\r\n" + 
				"		<a href=\"javascript: goPage(1);\"> home page </a>&nbsp;&nbsp;&nbsp;\r\n" + 
				"		<a 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\" onkeypress=\"toPageNumber(event,this.value)\"/> \r\n" + 
				"		<a href=\"javascript: goPage(document.getElementById('pageNumber').value);\">GO</a>\r\n" + 
				"	</div>";
		
		String hiddenForm = "<form action='" + pageBean.getUrl() + "' id=\"pagingForm\" method=\"post\">"
				+ "<input type=\"hidden\" name=\"page\" />";
		Map<String, String[]> parameterMap = pageBean.getParameterMap();
		
		// Loop all parameters , And generate hidden forms for all parameters 
		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>\r\n" + 
				"function goPage(pageNum) {\r\n" + 
				"	debugger;\r\n" + 
				"	let form = document.getElementById(\"pagingForm\");\r\n" + 
				"	let lastPage = '"+pageBean.getTotalPage()+"';\r\n" + 
				"	if(pageNum > lastPage) pageNum = lastPage;\r\n" + 
				"	if(pageNum < 1) pageNum = 1;\r\n" + 
				"	form.page.value = pageNum;\r\n" + 
				"	form.submit();\r\n" + 
				"}\r\n" + 
				"\r\n" + 
				"function toPageNumber(event,pn) {\r\n" + 
				"	//debugger;\r\n" + 
				"	if(event.keyCode ==  13) {\r\n" + 
				"		let form = document.getElementById(\"pagingForm\");\r\n" + 
				"		form.page.value = pn;\r\n" + 
				"		form.submit();\r\n" + 
				"	}\r\n" + 
				"}\r\n" + 
				"</script>";
		
		return pagingTool+hiddenForm+js;
	}

	
}

   Tag library (mytag.xml) Add paging label

<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>

Use pagination labels

First, introduce tags into the page

<%@taglib prefix="z" uri="/zking" %>

The original paging function , Replace with a label

<z:paging pageBean="${pageBean}"/>

Reference code of the page : 

<%@ 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="z" uri="/zking" %>
<!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.score}</td>
				<td>${student.clazz}</td>
			</tr>
		</c:forEach>
		
	</table>
	
	<z:paging pageBean="${pageBean}"/>
</body>


</html>

Running results : 

 

原网站

版权声明
本文为[I don't want this brain anymore]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207231257344542.html