当前位置:网站首页>General paging implementation
General paging implementation
2022-07-23 17:08:00 【Bugxiu_ fu】
Why universal paging ?
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
Final effect display :

The illustration

Effect display

Realize the idea :( understand )
How to encapsulate a general paging query method , Write a query first sql sentence , Put the query criteria and paging entities as parameters of the method .
Determine if pagination is needed
1. No paging , Direct inquiry , First traversal , And then return the result set
2. Pagination , Total pages of query , If the total record is 0, Directly return an empty result set , If not for 0, First write the number of pages that need to be displayed sql sentence , Then query the data of the current page , Returns the result set of the current page (1~10 page ).
Encapsulate a paging information entity , Because we need to use its properties later
package com.zking.utils;
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 = false;
/**
* 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 line number
public int getStartIndex() {
if(this.page > this.getTotalPage()) {
this.page = this.getTotalPage();
}
if(this.page < 1) {
this.page = 1;
}
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;
}
}
Version of a
public List<Book> queryBook(String bname,PageBean pb){
String sql="select * from t_book";
if(!StringUtils.isNullOrEmpty(bname)) {
sql+=" where bname like ?";
}
List<Book> list=new ArrayList<>();
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
//false || true perhaps , One is true is true , No more calculations in the future , An expression on the right of false recalculation .
//true && true And , First calculate the left , If the left one is not satisfied , It will not be calculated later ; If meet , You must meet two requirements
if(pb ==null || !pb.isPagination()) {// No paging
try {
con=DBUtil.getConection();
ps=con.prepareStatement(sql);
/**
* because mysql The database is automatically added as follows sql
* select * from t_book where bname like '%strName%';
* So there is no need to escape "%";
*/
if(!StringUtils.isNullOrEmpty(bname)) {
ps.setObject(1, "%"+bname+"%");
}
rs=ps.executeQuery();
while (rs.next()) {
Book b=new Book();
b.setBid(rs.getInt(1));
b.setBname(rs.getString(2));
b.setPrice(rs.getDouble(3));
list.add(b);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
}else {
try{// Paging required
// Main page
String countsql="select count(*) from ("+sql+") p";
con=DBUtil.getConection();
ps=con.prepareStatement(countsql);
if(!StringUtils.isNullOrEmpty(bname)) {
ps.setObject(1, bname+"%");
}
rs=ps.executeQuery();
if(rs.next()) {
pb.setTotal(rs.getInt(1));
}
if(pb.getTotal()<=0) {// No record
return list;
}
// Query the data of the current page
String pageql=sql+" limit "+pb.getStartIndex()+","+pb.getRows();
ps=con.prepareStatement(pageql);
if(!StringUtils.isNullOrEmpty(bname)) {
ps.setObject(1, bname+"%");
}
rs=ps.executeQuery();
while (rs.next()) {
Book b=new Book();
b.setBid(rs.getInt(1));
b.setBname(rs.getString(2));
b.setPrice(rs.getDouble(3));
list.add(b);
}
}catch(Exception e){
e.printStackTrace();
}finally {
DBUtil.closeDB(rs, ps, con);
}
}
return list;
}Version 2 :
General query ideas
take sql sentence , Parameters , Paging object , The converter passes this method as a parameter , Determine if pagination is needed ,
if necessary , To write sql( Number of display bars ) Query the data of the current page , Convert the data result set into an object , Show current page ;
If you don't need to , Execute the query , Directly return the result set .
public class BaseDao {
/*
* Adapter :
* I don't know how to convert the database result set into an object , I need it covert This interface helps me convert .
*
*/
public interface IConvert<T>{
public List<T> convert(ResultSet rs) throws SQLException;
}
public final <T> List<T> query(
String sql,//sql
Object[] params,// Parameters
PageBean pb,// Paging object
IConvert<T> convert// converter
){
List<T> list=new ArrayList<>();
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
/**
* || Condition or As long as the first condition is met , The latter conditions are no longer judged
* && Conditions and To meet the first condition and the second condition
*/
if(pb ==null || !pb.isPagination()) {// No paging
try {
con=DBUtil.getConection();
ps=con.prepareStatement(sql);
/*
* loop Object[] Array , Put the parameters one by one sql
*/
int i=1;
for (Object param : params) {
ps.setObject(i, param);
i++;
}
rs=ps.executeQuery();
// Convert the result set of query to database into object
list=convert.convert(rs);
return list;
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.closeDB(rs, ps, con);
}
}else {
try{// Paging required
// Main page
String countsql="select count(*) from ("+sql+") p";
con=DBUtil.getConection();
ps=con.prepareStatement(countsql);
int i=1;
for (Object param : params) {
ps.setObject(i, param);
i++;
}
rs=ps.executeQuery();
if(rs.next()) {
pb.setTotal(rs.getInt(1));
}
if(pb.getTotal()<=0) {// No record
return list;
}
// Query the data of the current page
String pageql=sql+" limit "+pb.getStartIndex()+","+pb.getRows();
ps=con.prepareStatement(pageql);
int j=1;
for (Object param : params) {
ps.setObject(j, param);
j++;
}
rs=ps.executeQuery();
list=convert.convert(rs);
}catch(Exception e){
e.printStackTrace();
}finally {
DBUtil.closeDB(rs, ps, con);
}
}
return list;
}
}Test class
public class Bookdao extends BaseDao{
/**
* @param bname Search keywords
* @param pb Paging object
* @return
*/
public List<Book> getbook(String bname,PageBean pb){
String sql="select * from t_book";
List<Object> params=new ArrayList<>();
if(!StringUtils.isNullOrEmpty(bname)) {// A method to determine whether the string is an empty reference or the value is empty
sql+=" where bname like ?";
params.add(bname+"%");// Add query criteria
}
//params.toArray() When using Arraylist Array , You can get an actual array
/**
* After the subclass inherits the parent class ,this The meaning expressed by the object , It mainly depends on this What kind of method is called . If you specify a parent method , It means calling the parent method
* If you specify a subclass method , It means calling subclass methods
*/
List<Book> list=this.query(sql, params.toArray(), pb, new IConvert<Book>() {
@Override
public List<Book> convert(ResultSet rs) throws SQLException {
List<Book> list = new ArrayList<>();
while (rs.next()) {
Book b=new Book();
b.setBid(rs.getInt(1));
b.setBname(rs.getString(2));
b.setPrice(rs.getDouble(3));
list.add(b);
}
return list;
}
});
return list;
}
public static void main(String[] args) {
Bookdao bs=new Bookdao();
PageBean pageBean = new PageBean();
System.out.println(pageBean.isPagination());// result :flase
pageBean.setPagination(true);
List<Book> queryBook = bs.getbook("",pageBean );
System.out.println(queryBook);
}
}matters needing attention :
|| Condition or As long as the first condition is met , The latter conditions are no longer judged
&& Conditions and To meet the first condition and the second conditionAdapter :
effect : I don't know how to convert the database result set into an object , I need it covert This interface helps me convert .
Code display
public interface IConvert<T>{ public List<T> convert(ResultSet rs) throws SQLException; } public final <T> List<T> query( String sql,//sql Object[] params,// Parameters PageBean pb,// Paging object IConvert<T> convert// converter ){ // Convert the result set of query to database into object list=convert.convert(rs); }this object
public class Bookdao extends BaseDao{ /** * * @param bname Search keywords * @param pb Paging object * @return */ public List<Book> getbook(String bname,PageBean pb){ String sql="select * from t_book"; List<Object> params=new ArrayList<>(); if(!StringUtils.isNullOrEmpty(bname)) {// A method to determine whether the string is an empty reference or the value is empty sql+=" where bname like ?"; params.add(bname+"%");// Add query criteria } //params.toArray() When using Arraylist Array , You can get an actual array List<Book> list=this.query(sql, params.toArray(), pb, new IConvert<Book>() { @Override public List<Book> convert(ResultSet rs) throws SQLException { return list; } }); return list; }this After the subclass inherits the parent class ,this The meaning expressed by the object , It mainly depends on this What kind of method is called . If you specify a parent method , It means calling the parent method ; If you specify a subclass method , It means calling subclass methods .
Common code
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
Book page
<h2> Student information </h2>
<form action="<%=request.getContextPath()%>/BookServlet" method="post">
<input type="text" name="bname"> <input type="submit"
value=" Inquire about ">
</form>
<!-- If the collection is empty , will servlet Data is loaded into the page -->
<c:if test="${empty list }">
<jsp:forward page="/BookServlet"></jsp:forward>
</c:if>
<table border="1" style="width: 100%" >
<tr>
<td> Number </td>
<td> Title </td>
<td> Price </td>
</tr>
<c:forEach items="${list }" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
</tr>
</c:forEach>
</table>
<div style="text-align: right; width:98%;">
The first ${pageBean.page} page
common ${pageBean.totalPage} Bar record
<a href="javascript:goPage(1)"> home page </a>
<a href="javascript:goPage(${pageBean.previousPage })"> page-up key </a>
<a href="javascript:goPage(${pageBean.nextPage })"> next page </a>
<a href="javascript:goPage(${pageBean.totalPage })"> Tail page </a>
The first <input type="text" size="2" id="pageNumber" onkeyup="toPage(event,this.value)" />
<a href="#">GO</a>
</div>
<!-- Hidden form for paging -->
<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="bname" value="<%=request.getParameter("bname")%>"/>
</form>
<script type="text/javascript">
function goPage(pageNum){
let form=document.getElementById("pagingForm");
form.page.value=pageNum;
form.submit();
}
/**
* Keyboard click event
*event Event object
*/
function toPage(e,pageNumber){
if(e.keyCode == 13){// The Astor value of the Enter key
goPage(pageNumber);
}
}
</script> Interactive with database BookServlet
@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PageBean pb=new PageBean();
pb.setRows(5);
pb.setPagination(true);
pb.setRequest(request);//PageBean The saved
String bname=request.getParameter("bname");
Bookdao b=new Bookdao();
List<Book> list = b.query1Book(bname,pb);
request.setAttribute("list", list);
request.getRequestDispatcher("Book.jsp").forward(request, response);
}
}
边栏推荐
- Priyanka Sharma, general manager of CNCF Foundation: read CNCF operation mechanism
- 排序-介绍,代码思路,使用建议,代码实现-1
- [web vulnerability exploration] SQL injection vulnerability
- Lake Shore - empx-h2 low temperature probe station
- IE盒模型和标准盒模型
- 【Flutter -- 布局】弹性布局(Flex 和 Expanded)
- TOPSIS法(MATLAB)
- Object.defineProperty方法、数据代理
- 二十四节气之大暑
- 泰山OFFICE技术讲座:段落边框的布局绘制分析
猜你喜欢
随机推荐
合宙ESP32C3基于VSCode PIO Arduino开发框架初探教程
How to set up the router correctly
串的初步认识
PWN entry (3) heap
TOPSIS法(MATLAB)
Weisfeiler Lehman graph isomorphism test and others
Fundamentals of C language -- the data type meaning of 2-4 pointers and the analysis of forced type conversion
How does MySQL query data that is not in the database?
微信小程序wx.hideLoading()会关闭toast提示框
What are the principal guaranteed financial products with an annual interest rate of about 6%?
Object.defineProperty方法、数据代理
Function secondary development / plug-in development of JMeter (detailed version)
AutoCAD基本操作
灰色关联分析(MATLAB)
拼多多APP商品详情接口获取activity_id值(拼多多activity_id接口)
CNCF基金会总经理Priyanka Sharma:一文读懂CNCF运作机制
NodeJs实现token登录注册(KOA2)
英特尔nuc能代替主机吗_终于圆满了!最新款的Intel NUC迷你主机上线
JS之闭包
YOLOV7

![[31. Maze walking (BFS)]](/img/9b/1c1e991ca3e99923dab888a214efb3.png)






