This article originates from http://blog.csdn.net/tjpu_lin/article/details/41050475
Recently in the development of a project, the project has a very many data presentation module. So to use paging, the web search for a very many pages of the sample, but very many implementations of the method and its own code instance coupling is too high. Lead to direct use not at all.
So I can only personally, about the paging implementation of the general logic is the front desk and background to pass each other page parameters (such as the current page, page size. A total of pages, etc.), backstage mainly accept the foreground through the Pagenum (current page number), the data query, and then return to the foreground after the data returned to the front desk to return the page to the front desk. So that the foreground combined with CSS to highlight the current page in the pagination style.
Steps can be broadly divided into the next few steps.
1. Background SQL query data (the bottom I use MySQL database)
The front desk just needs to pass a pagenum, then define a page-size constant in the background, which I define in the constant class. Used as a constant.
/** * Paging page Count */ public static final Integer PAGESIZE = 10;
Use Constant.pagesize to invoke it.
This is where we need to understand the implementation of MySQL paging sql:
In MySQL, we use limit to implement paging data query, the limit A, a, A start from A, and then take the number of B.
For us, the first page is 0-9 of these 10 records (the MySQL record index starts from 0). So our first page of data the corresponding SQL is limit 0, 10. And so on the second page is limit 10, 10, and the third page is limit 20,10 ...
The starting index value requires a simple calculation. Integer StartIndex = (pageNum-1) *10, do not understand the value of pagenum to think about it.
Limit StartIndex. PageSize is always placed on the last side of the query. That's what's in front of all sorts of where. Group BY, order by all write and then connect limit
2. Construction of background Pagevo class
Because the foreground needs more data in the background, we encapsulate them in a Pagevo object.
Here is the definition of my Pagevo class
Package Com.bada.core.vo;import java.io.serializable;import java.util.map;/** * @author Kevin * Classes */public class Pag for pagination EVo implements Serializable {private int curpage;//current page private int pagesize;//per page size private int totalrows;//Total record number private int totalpages;//Total pages private String querycondition; Query criteria (string), the user put the query conditions into the foreground and then back to the private map<string,object> queryconditions; Query conditions, for multi-conditional public map<string, object> getqueryconditions () {return queryconditions; } public void Setqueryconditions (map<string, object> queryconditions) {this.queryconditions = QueryCondit Ions } public int Getcurpage () {return curpage;} public void setcurpage (int curpage) {this.curpage = Curpage;} public int getpagesize () {return pageSize;} public void setpagesize (int pageSize) {this.pagesize = pageSize;} public int gettotalrows () {return totalrows;} public void settotalrows (int totalrows) {this.totalrows = totalrows;} public int gettotalpages () {return totalpages;} Public Void settotalpages (int totalpages) {this.totalpages = TotalPages;} Public String getquerycondition () {return querycondition; } public void Setquerycondition (String querycondition) {this.querycondition = querycondition; } @Override Public String toString () {return "pagevo{" + "curpage=" + Curpage + ", pagesize=" + PageSize + ", totalrows=" + Totalrows + ", totalpages=" + totalpage S + ", querycondition= '" + querycondition + "\" + ", queryconditions=" + queryconditions + '}'; }}
The addition of the querycondition and queryconditions variables is about the page with the query criteria to deposit query conditions, upload to the foreground, and then click on the next page simultaneous to the background will not be loaded with missing query conditions of the data bit empty.
The background needs a new Pagevo object. Then set the corresponding number of parameters, Curpage is pagenum,pagesize is the page size. Here's something to watch out for. After the data query, we also need to make a count of all the records that satisfy the condition, to get the total value. General Select COUNT (ID) from * * Where **=**, generally do not count (*), query efficiency will be much lower, count (0) will be able to. Of course, the count (primary key) will be faster because the primary key is indexed.
Totalrows corresponding to the total number of queries just now. TotalPages also need us to count. Think for a second. Total number of pages required. Let's start with a few examples to examine, assuming there are 40 records, according to 1 pages is 10 records, then 4 pages. Let's say there are 38 records and 4 pages. is actually a total divided by the page size rounded up. We write a method to achieve.
public class Formatutils { /** * Rounding up For example: 30 data. Each page 8 article altogether 4 page * @param total * @param pageSize * @return * /public static int getpagetotal (int Total,int pageSize) { if (pageSize = = 0) {//denominator cannot be 0 return 0; } return (int) Math.ceil ((double) total/pagesize);} }
Java comes with a math.ceil to take the smallest integer greater than or equal to a number.
Suppose a query condition is set to querycondition, assuming that there are multiple packages to map and set to querycondtions inside, detailed reception how to take in the back NFPs,
3. The foreground jstl constructs the page element.
The beginning is written on the page a large string of JSTL code to generate HTML code, and then directly encapsulated in their own definition of the label to be more convenient. Let's show you how Jstl is written.
<div class= "page mg-auto" ><ul class= "pagination" > <c:if test= "${pagevo.totalpages > 0}" > <li><a href= "Javascript:onselectpage (${pagevo.curpage-1})" >«</a></li> <c:if test= "${pagevo.totalpages <=" > <c:foreach var= "i" begin= "1" end= "${pagevo.tota Lpages} "> <c:choose> <c:when test=" ${i = = pagevo.curpage} "&G T <li class= "Active" ><a href= "Javascript:onselectpage (${i})" >${i}</a></li> </c:when> <c:otherwise> <li><a href= "Java Script:onselectpage (${i}) ">${i}</a></li> </c:otherwise> </c:choose> </c:forEach> </c:if> <c:iF test= "${pagevo.totalpages > Ten" > <c:if test= "${pagevo.curpage < Ten}" > <c:foreach var= "I" begin= "1" end= "ten" > <c:choose> <c:when test= "${i = = Pagevo.curpage}" > <li class= "active" ><a href= "Javascript:onselectpage (${i})" >${i}</a></li> </c:when> <c:otherwise> <li><a href= "Javascript:onselectpage (${i} ) ">${i}</a></li> </c:otherwise> </c:choo se> </c:forEach> </c:if> <c:if test= "${page Vo.curpage >= "> <c:foreach var=" J "begin=" ${pagevo.curpage-5} "end=" ${pagevo.curpage+4 } "> <c:if test= "${j <= pagevo.totalpages}" > <c:choose> <c:when test= "${j = = Pagevo.curpage}" > <li class= "acti VE "><a href=" Javascript:onselectpage (${j}) ">${j}</a></li> </c:w hen> <c:otherwise> <li><a href = "Javascript:onselectpage (${j})" >${j}</a></li> </c:otherwise> </c:choose> </c:if> </C:FOREAC h> </c:if> </c:if> <li><a href= "Javascript:onsele Ctpage (${pagevo.curpage + 1}) ">»</a></li> </c:if></ul></div>
Later found that the above code can actually be implemented with their own definition of tags, the page on a line of code to be done. It's much more reusable.
。
Detailed implementation of the logic is to imitate Baidu's walk of the page,
The logic to be analyzed such as the following (step progressive):
1, no record, no page number. Infer whether the totalpages of Pagevo is greater than 0. If it's more than 0, just go to the raw page style.
2, if the total number of pages is less than 10, then write a loop, starting from 1. Loop to the total number of pages, showing n page (n is totalpages), the same time that the N page is displayed, according to the curpage inside the Pagevo to infer which page needs to be highlighted.
3, assume that the total number of pages is greater than 10, less than 10 of the partial display effect as above. More than 10, the highlighted page is always in the middle area, that is, the current page curpage as the condition. It shows 5 on the left and 4 on the right. (The detailed effect can see the bottom of Baidu search results)
Show up to 10 pages at once. Then highlight in the middle (page is greater than 10).
Each a tag is added with the JS function. When clicked, jump to the following function.
<c:if test= "${!empty Pagevo}" > <%--prevent the first entry to the page without Pagevo and out of JS error--%> <script type= "Text/javascript" > function onselectpage (curpage) { if (curpage>=1 && curpage<=${pagevo.totalpages}) { if (curpage! = ${pagevo.curpage}) {//Current page Click Disable Jump window.location.href= "${pagecontext.request.contextpath}/ Customer/queryallsalesshippers?pagenum= "+curpage;}} } </script></c:if>
Let's say we write this with the query condition.
Window.location.href= "${pagecontext.request.contextpath}/customer/querysalesshippercustomer?condition=${ Pagevo.querycondition}&pagenum= "+curpage;
Of course window.location.href= "" After the connection write your query data that the action path.
About the corresponding front-end style is the front-end to write, just need to have a highlighted style of pagination HTML code can, here I also posted CSS code OK.
Detailed look
/*------------------------------Paging tag defines-------------------------------*/.page{width:80%;text-align:center ; margin-top:80px;}. pagination {display:inline-block;padding-left:0;margin:20px 0;border-radius:2px;}. Pagination>li {Display:inline;}:before,: after {-webkit-box-sizing:border-box;-moz-box-sizing:border-box; Box-sizing:border-box;}:before,: After {-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing: Border-box;}. Pagination>li:first-child>a,. Pagination>li:first-child>span {margin-left:0;border-top-left-radius: 2px;border-bottom-left-radius:2px;}. Pagination>li>a,. Pagination>li>span {position:relative;float:left;padding:6px 12px;margin-left: -1px; Line-height:1.42857143;color: #428bca; Text-decoration:none;background-color: #fff; border:1px solid #ddd;} a {text-decoration:none;} a {background:0 0;}. Pagination>.active>a,. Pagination>.active>span,. Pagination>.active>a:hover,. Pagination>. Active>span: hover,. Pagination>.active>a:focus,. Pagination>.active>span:focus {color: #fff; cursor:default; Background-color: #428bca; Border-color: #428bca;}. Pagination>li>a:hover,. Pagination>li>span:hover,. Pagination>li>a:focus, .pagination>li> Span:focus {color: #2a6496; Background-color: #eee; Border-color: #ddd;}. Pagination>.active>a,. Pagination>.active>span,. Pagination>.active>a:hover,. Pagination>. Active>span:hover,. Pagination>.active>a:focus,. Pagination>.active>span:focus {color: #fff; cursor: Default;background-color: #428bca; Border-color: #428bca;}. Pagination>li>a,. Pagination>li>span {position:relative;float:left;padding:6px 12px;margin-left: -1px; Line-height:1.42857143;color: #428bca; Text-decoration:none;background-color: #fff; border:1px solid #ddd;}
I wrote the pagination, the simple step is 3 steps. Background Pagevo build, front desk jstl Raw Component page module. Then add a JS function to jump query
========================================================= I am the cutting line ================================================= =======
Here's a look at the implementation of your own definition label
The detailed idea is to use Java code to print out the HTML code. Just as the servlet prints the page with the output stream.
1. Build your own definition label class
Package Com.bada.biz.service;import Javax.servlet.jsp.jspexception;import Javax.servlet.jsp.jspwriter;import Javax.servlet.jsp.tagext.tagsupport;import com.bada.core.vo.pagevo;/** * Created by Kevin on 2014/11/2. * Pagevo's own definition Label class */public class Pagevotag extends TagSupport {private Pagevo Pagevo; @Override public int doStartTag () throws Jspexception {try {jspwriter out = This.pageContext.getOut (); if (Pagevo = = null) {return skip_body; } if (Pagevo.gettotalpages () > 0) {out.println ("<li><a href=\" javascript:onselectpa GE ("+ (Pagevo.getcurpage ()-1) +") \ ">«</a></li>"); if (Pagevo.gettotalpages () <=) {for (int i = 1; I <= pagevo.gettotalpages (); i++) { if (i = = Pagevo.getcurpage ()) {out.println ("<li class=\" active\ "><a HRE F=\ "Javascript:onselectpage (" +i+ ") \" > "+i+" </a></li> "); } else {out.println ("<li><a href=\" Javascript:onselectpage ("+i+") \ ">" +i+ "</a> ;</li> "); }}} if (Pagevo.gettotalpages () >) {if (Pagevo . Getcurpage () <) {for (int i = 1; i <=; i++) {if (i = = Pag Evo.getcurpage ()) {out.println ("<li class=\" current\ "><a href=\" Javascript:onsele Ctpage ("+i+") \ ">" +i+ "</a></li>"); } else {out.println ("<li><a href=\" Javascript:onselectpage ("+i+") \ ">" +i+ "</ A></li> "); }}} if (Pagevo.getcurpage () >= 10) { for (int j = pagevo.getcurpage () -5;j <= pagevo.getcurpaGE (+4); J + +) {if (J <= pagevo.gettotalpages ()) {if (j = = Pagevo.get Curpage ()) {out.println ("<li class=\" current\ "><a href=\" javascript:onselectpa GE ("+j+") \ ">" +j+ "</a></li>"); } else {out.println ("<li><a href=\" Javascript:onselectpage ("+j+") \ ">" +j+ "& Lt;/a></li> "); }}}}} out.println (" <li><a href=\ "Javascript:onselectpage (" + (Pagevo.getcurpage () +1) + ") \" >»</a></li> "); }} catch (Exception e) {throw new Jspexception (E.getmessage ()); } return skip_body; } @Override public int doendtag () throws jspexception {return eval_page; } @Override public void release () { Super.release (); This.pagevo = null; } public Pagevo Getpagevo () {return pagevo; } public void Setpagevo (Pagevo pagevo) {This.pagevo = Pagevo; }}
Can see. The code is significantly less than JSTL. It looks like the AVA code is so wow. This class may need to download the corresponding jar package, this self Baidu a bit.
2. Define your own label file named Pagevo.tld
<?xml version= "1.0" encoding= "UTF-8"?><taglib xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance " xsi:schemalocation=" Http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_ 0.xsd " version=" 2.0 "> <tlib-version>1.0</tlib-version> <short-name>cc</ short-name> <uri>/pageTaglib</uri> <tag> <name>showPaging</name> <tag-class>com.bada.biz.service.PageVoTag</tag-class> <body-content>empty</ body-content> <attribute> <name>pageVo</name> <required>true</ required> <rtexprvalue>true</rtexprvalue> </attribute> </tag></ Taglib>
Inside the corresponding Tag-class is the class that is written above, Pagevo for the incoming argument, then the foreground with ${pagevo} assigned this argument.
3.web.xml inside the configuration
<!--Configure your own definition labels- <jsp-config> <taglib> <taglib-uri>/pagetaglib</ taglib-uri> <taglib-location>/WEB-INF/tld/pageVo.tld</taglib-location> </taglib> </jsp-config>
Add in the Web-app label inside a level can be
4.jsp page Usage
Reference tag: URI is the URI defined above. prefix is the prefix name. Randomly taken.
<%@ taglib uri= "/pagetaglib" prefix= "PV"%>
Using labels
<div class= "page Mg-auto" > <ul class= "pagination" > <pv:showpaging pagevo= "${pagevo}"/> </ul> </div>
One line of code is done. You don't have to copy that big bunch of jstl code anymore.
At this point the paging module is done, the relevant file download http://download.csdn.net/detail/tro_picana/8151805
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Live Javaweb Paging implementation (simulation Baidu Home)