Details on implementation of javaWeb paging (simulating Baidu paging) and javaweb Paging

Source: Internet
Author: User
Tags tld

Details on implementation of javaWeb paging (simulating Baidu paging) and javaweb Paging


From http://blog.csdn.net/tjpu_lin/article/details/41050475

Recently, a project has many data display modules, so paging is required. Many paging examples are searched on the Internet. However, many implementation methods are highly coupled with their own code instances, as a result, it cannot be used directly.

As a result, you can only go through the page. The general logic of paging implementation is that the front-end needs to pass page parameters with the backend (such as the current page, page size, and total page size ), the background mainly accepts the pageNum passed by the foreground (current page number) for data query, and then returns the data to the foreground while returning the page to the foreground, this allows the foreground to highlight the current page in the paging style with CSS.


The steps can be roughly divided into the following steps.


1. When querying data in the background SQL statement (Mysql database is used at the underlying layer)

The foreground only needs to pass a pageNum, and then define a page size Constant in the background. I defined it in the Constant class and used it as a Constant.

/*** Paging page parameter */public static final Integer PAGESIZE = 10;

Constant. PAGESIZE is used for calling.

At this time, we need to understand the implementation of mysql paging SQL as follows:

In mysql, we use limit to query paging data. limit A and B indicate that the number of B is counted from.

For us, the first page is the 10 records 0-9 (the index of mysql records starts from 0), so the SQL statement corresponding to the data obtained on the first page is limit; and so on. The second page is limit 10, and the third page is limit 20, 10 ......

The initial index value requires us to perform a simple calculation, Integer startIndex = (pageNum-1) * 10, don't understand the value of pageNum into think about it to know.

Limit startIndex and PAGESIZE are always placed at the end of the query, that is, the preceding where, group by, and order by are all written and then connected to limit.


2. Build the pageVo class in the background

Because the front-end needs a lot of background data, we encapsulate them into a pageVo object.

The following is the definition of my pageVo class.

Package com. bada. core. vo; import java. io. serializable; import java. util. map;/*** @ author Kevin * The paging class */public class PageVo implements Serializable {private int curPage; // The private int pageSize of the current page; // size of each page private int totalRows; // total number of records private int totalPages; // total number of pages private String queryCondition; // query condition (String ), the user passes the query condition to the foreground and then transmits it back to the private Map <String, Object> queryConditions; // query condition. For the multi-condition public Map <String, Object> getQueryConditions () {return queryConditions;} public void setQueryConditions (Map <String, Object> queryConditions) {this. queryConditions = queryConditions;} 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 = "+ totalPages +", queryCondition = '"+ queryCondition +' \'' + ", queryConditions = "+ queryConditions + '}';}}

The queryCondition and queryConditions variables in the preceding statements are stored in the query conditions on pages with query conditions and uploaded to the foreground, then, when the next page is clicked, the data bit loaded due to missing query conditions will not be empty when it is uploaded to the background.

A new PageVo object needs to be created in the background, and then set the corresponding parameter value. curPage is pageNum, and pageSize is the page size. Note that after data query, you also need to count all records that meet the conditions to obtain the total number. In general, select count (ID) from ** where ** = **. Generally, do not count (*). The query efficiency is much lower. count (0) is enough, of course, count (primary key) is faster, because the primary key is indexed.

TotalRows corresponds to the total number of queries just now, and totalPages also need to be counted. Think about the number of pages required in total. Let's give a few examples to repeat it. If there are 40 records, there are 10 records on one page, and there are four pages, if there are 38 records and 4 pages, it is actually a total number divided by the page size and rounded up. Let's write a method to implement this.

Public class FormatUtils {/*** rounded up, for example, 30 data records, 8 entries per page, 4 pages * @ param total * @ param pageSize * @ return */public static int getPageTotal (int total, int pageSize) {if (pageSize = 0) {// The denominator cannot be 0 return 0;} return (int) Math. ceil (double) total/pageSize );}}
Java comes with Math. ceil to take the smallest integer greater than or equal to a certain number.

If there is a query condition, set it to queryCondition. If there are multiple query conditions, encapsulate them to map and then set them to queryCondtions. How can the specific front-end be followed by a complaint,

3. Foreground jstl build page elements.

The first step is to write a large string of jstl code on the page to generate html code. It is much more convenient to encapsulate the Code directly into custom tags. First, we will show 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 <= 10}">                    <c:forEach var="i" begin="1" end="${pageVo.totalPages}">                        <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:choose>                    </c:forEach>                </c:if>                <c:if test="${pageVo.totalPages > 10}">                    <c:if test="${pageVo.curPage < 10}">                        <c:forEach var="i" begin="1" end="10">                            <c:choose>                                <c:when test="${i == pageVo.curPage}">                                    <li class="current"><a href="javascript:onSelectPage(${i})">${i}</a></li>                                </c:when>                                <c:otherwise>                                    <li><a href="javascript:onSelectPage(${i})">${i}</a></li>                                </c:otherwise>                            </c:choose>                        </c:forEach>                    </c:if>                    <c:if test="${pageVo.curPage >= 10}">                        <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="current"><a href="javascript:onSelectPage(${j})">${j}</a></li>                                    </c:when>                                    <c:otherwise>                                        <li><a href="javascript:onSelectPage(${j})">${j}</a></li>                                    </c:otherwise>                                </c:choose>                            </c:if>                        </c:forEach>                    </c:if>                </c:if>                <li><a href="javascript:onSelectPage(${pageVo.curPage + 1})">»</a></li>            </c:if></ul></div>


 

Later, I found that the above Code can actually be implemented using custom tags, and the Code on the page will be done in a line, so the reusability is much higher ~ Let's talk about this later !!

The specific implementation logic imitates Baidu paging,

The analysis logic is as follows (step by step ):

1. No record exists and no page number is displayed. Determines whether pageVo's totalPages are greater than 0. If it is greater than 0, the pagination style is generated.

2. If the total number of pages is less than 10, write a loop from 1 to the total number of pages. N pages (N is totalPages) are displayed, determine which page needs to be highlighted Based on the curPage in pageVo.

3. If the total number of pages is greater than 10 and the number of pages smaller than 10 is shown as above, the highlighted page is always in the middle area, that is, the current page is used as the condition, 5 on the left and 4 on the right. (For more information, see the bottom of Baidu search results)

Up to 10 pages can be displayed at a time, and then highlighted in the middle (the page is greater than 10 ).

Each a tag requires a js function. When you click it, it jumps to the following function.

<C: if test = "$ {! Empty pageVo} "> <% -- prevent js errors when pageVo is not displayed for the first time -- %> <script type =" text/javascript "> function onSelectPage (curPage) {if (curPage> = 1 & curPage <=$ {pageVo. totalPages}) {if (curPage! =$ {PageVo. curPage}) {// click to disable redirect to window. location. href = "$ {pageContext. request. contextPath}/customer/queryAllSalesShippers? PageNum = "+ curPage ;}}</script> </c: if>
If you write data with query conditions

window.location.href="${pageContext.request.contextPath}/customer/querySalesShipperCustomer?condition=${pageVo.queryCondition}&pageNum="+curPage;

Of course, the connection after window. location. href = "" writes the action path of the data you query.


The corresponding front-end style is written by the front-end, as long as there is html code with a highlighted style pagination, here I also paste the css code.

Details


/* ------------------------------ 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> ,. pagination> li: first-child> span {margin-left: 0; border-top-left-radius: 2px; border-bottom-left-radius: 2px ;}. pagination> li> ,. 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> ,. 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> ,. 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> ,. 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 ;}


The simple step for paging I wrote is three steps. The pageVo page is built in the background. The jstl page module is generated in the foreground, and a js function is added for jump query.

========================================================== ==================================================================== ==========================================


The following describes the implementation of custom tags.

The specific idea is to use java code to print the html code, just like the servlet printing page with the output stream.

1. Build a custom 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 custom 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: onSelectPage ("+ (pageVo. getCurPage ()-1) + ") \"> «</a> </li> "); if (pageVo. getTotalPages () <= 10) {for (int I = 1; I <= pageVo. getTotalPages (); I ++) {if (I = pageVo. getCurPage () {out. println ("<li class = \" active \ "> <a href = \" javascript: onSelectPage ("+ I + ") \ ">" + I + "</a> </li>");} else {out. println ("<li> <a href = \" javascript: onSelectPage ("+ I + ") \ ">" + I + "</a> </li>") ;}} if (pageVo. getTotalPages ()> 10) {if (pageVo. getCurPage () <10) {for (int I = 1; I <= 10; I ++) {if (I = pageVo. getCurPage () {out. println ("<li class = \" current \ "> <a href = \" javascript: onSelectPage ("+ 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. getCurPage () {out. println ("<li class = \" current \ "> <a href = \" javascript: onSelectPage ("+ j + ") \ ">" + j + "</a> </li>");} else {out. println ("<li> <a href = \" javascript: onSelectPage ("+ j + ") \ ">" + j + "</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 ;}}

We can see that the code is much less than jstl, and it seems that the ava code is better. This class may need to download the corresponding jar package, Baidu.


2. Name the custom tag file 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>



The corresponding tag-class is the class written above. pageVo is the input parameter, and $ {pageVo} is assigned to the front-end.


3. configuration in web. xml

<! -- Configure custom tags --> <jsp-config> <taglib-uri>/pageTaglib </taglib-uri> <taglib-location>/WEB-INF/tld/pageVo. tld </taglib-location> </taglib> </jsp-config>

Add a level in the web-app tag.


4. jsp page usage

Reference tag: uri is the uri defined above. prefix is the prefix name.

<%@ taglib uri="/pageTaglib" prefix="pv"%>

Use tags

<div class="page mg-auto">            <ul class="pagination">                <pv:showPaging pageVo="${pageVo}" />            </ul>        </div>

One line of code .. You no longer need to copy that large string of jstl code.


So far the paging module done, the relevant file download http://download.csdn.net/detail/tro_picana/8151805

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.