There are two common paging implementation methods:
1. Modify SQL every time you turn the page, pass relevant parameters to SQL, and go to the database to find out the data of the page in real time and display it.
2. Find out all the data in a certain table in the database, and then obtain and display certain data by processing it in the business logic.
For a simple management system with a small amount of data, the first implementation method is relatively easy to use less code to implement the function of paging. This article also introduces this method to you:
Code snippet:
1. Page.java
package com.cm.contract.common; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; /**Pagination class* @author FENGWEI * @date 2016-5-23 */ public class Page implements java.io.Serializable{ private static final long serialVersionUID = 1L; //Previous page private Boolean hasPrePage; //The next page private Boolean hasNextPage; //How many items are displayed per page: default 20 private Long everyPage = 20L; //Total number of pages private Long totalPage; //The current page: Default page 1 private Long currentPage = 1L; //Start subscript private Long beginIndex; //End subscript private Long endinIndex; //How many private long totalCount; //Sorting column name private String sortName; //Sorting status private String sortState; //Sorting information private String sortInfo; //Sorting whether to sort private Boolean sort = false; private String defaultInfo = " "; public String getDefaultInfo() { return defaultInfo; } public void setDefaultInfo(String defaultInfo) { this.defaultInfo = defaultInfo; } public String getSortInfo() { return sortInfo; } public void setSortInfo(String sortInfo) { this.sortInfo = sortInfo; } public String getSortName() { return sortName; } public void setSortName(String sortName) { setPageSortState(sortName); } public String getSortState() { return sortState; } public void setSortState(String sortState) { this.sortState = sortState; } public Page() { } /** * Commonly used, used to calculate paging* */ public Page(Long totalRecords){ this.totalCount = totalRecords; setTotalPage(getTotalPage(totalRecords)); } /** * Use * when setting how many entries are displayed on each page * */ public Page(Long everyPage,Long totalRecords){ this.everyPage = everyPage; this.totalCount = totalRecords; setTotalPage(getTotalPage(totalRecords)); } /** * @param state status code* @param value How many pages to go to or set how many items to display per page or be sorted as a sorting column name*/ public void pageState(int index,String value) { sort = false; switch (index) { case 0 :setEveryPage(Long.parseLong(value));break; case 1 :first();break; case 2: previous();break; case 3: next();break; case 4: last();break; case 5: sort = true;sort(value);break; case 6 ://to the specified page setCurrentPage(Long.parseLong(value)); break; } } /** * Previous page*/ private void first() { currentPage = 1L; } private void previous() { currentPage--; } private void next() { currentPage++; } private void last() { currentPage = totalPage; } private void sort(String sortName) { //Set the sorting status setPageSortState(sortName); } /** * Calculate the total number of pages* */ private Long getTotalPage(Long totalRecords) { Long totalPage = 0L; everyPage = everyPage == null ? 10L : everyPage; if (totalRecords % everyPage == 0) totalPage = totalRecords / everyPage; else { totalPage = totalRecords / everyPage + 1; } return totalPage; } public Long getBeginIndex() { this.beginIndex = (currentPage - 1) * everyPage; return this.beginIndex; } public void setBeginIndex(Long beginIndex) { this.beginIndex = beginIndex; } public Long getCurrentPage() { this.currentPage = currentPage == 0 ? 1 : currentPage; return this.currentPage; } public void setCurrentPage(Long currentPage) { if(0 == currentPage){ currentPage = 1L; } this.currentPage = currentPage; } public Long getEveryPage() { this.everyPage = everyPage == 0 ? 10 : everyPage; return this.everyPage; } public void setEveryPage(Long everyPage) { this.everyPage = everyPage; } public Boolean getHasNextPage() { this.hasNextPage = (currentPage != totalPage) && (totalPage != 0); return this.hasNextPage; } public void setHasNextPage(Boolean hasNextPage) { this.hasNextPage = hasNextPage; } public Boolean getHasPrePage() { this.hasPrePage = currentPage != 1; return this.hasPrePage; } public void setHasPrePage(Boolean hasPrePage) { this.hasPrePage = hasPrePage; } public Long getTotalPage() { return this.totalPage; } public void setTotalPage(Long totalPage) { if(this.currentPage > totalPage){ this.currentPage = totalPage; } this.totalPage = totalPage; } public Long getTotalCount() { return this.totalCount; } public void setTotalCount(Long totalCount) { setTotalPage(getTotalPage(totalCount)); this.totalCount = totalCount; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } /** * Set the sorting status* */ private void setPageSortState(String newPageSortName) { //Judge whether the previous sorting field is empty if(StringUtils.isEmpty(sortName)){ //Default sorting is ascending order this.sortState = PageUtil.ASC; this.sortInfo = PageUtil.PAGE_ASC; }else{ if(StringUtils.equalsIgnoreCase(newPageSortName, sortName)){ //Judge the sortState sorting status value if(StringUtils.equalsIgnoreCase(sortState, PageUtil.ASC))){ this.sortState = PageUtil.DESC; this.sortInfo = PageUtil.PAGE_DESC; }else{ this.sortState = PageUtil.ASC; this.sortInfo = PageUtil.PAGE_ASC; } }else{ //Default this.sortState = PageUtil.ASC; this.sortInfo = PageUtil.PAGE_ASC; } } sortName = newPageSortName.toLowerCase(); } public Boolean isSort() { return sort; } public void setSort(Boolean sort) { this.sort = sort; } public Long getEndinIndex() { this.endinIndex = (currentPage) * everyPage; return endinIndex; } public void setEndinIndex(Long endinIndex) { this.endinIndex = endinIndex; } } 2.PageState.java
package com.cm.contract.common; import org.apache.commons.lang.StringUtils; /**Pagination status class* @author FENGWEI * @date 2016-5-23 */ public enum PageState { /** * Set how many pieces to display per page* */ SETPAGE, /** * Home page* */ FIRST, /** * Previous page* */ PREVIOUS, /** * Back page* */ NEXT, /** * Last page* */ LAST, /** * Sort* */ SORT, /** * How many pages to go* */ GOPAGE; /** * @param value Index name* @return Return index index index index index*/ public static int getOrdinal(String value) { int index = -1; if (StringUtils.isEmpty(value)) { return index; } String newValue = StringUtils.trim(value).toUpperCase(); try { index = valueOf(newValue).ordinal(); } catch (IllegalArgumentException e) {} return index; } } 3.PageUtil.java
/** * Pagination tool class* @author FENGWEI * @date 2016-5-23 */ public class PageUtil { public static final String ASC = "asc"; public static final String DESC = "desc"; public static final String PAGE_DESC = "↓"; public static final String PAGE_ASC = "↑"; public static final String PAGE_NULL = " "; public static final String SESSION_PAGE_KEY = "page"; /** * Initialize the paging class* @param initPageSql Unpatched query SQL * @param totalCount Total number of rows* @param index Paging status* @param value Only when setting how many pieces are displayed per page, the value will not be NULL, the others are NULL */ public static Page inintPage(Long totalCount,Integer index,String value,Page sessionPage){ Page page = null; if(index < 0){ page = new Page(totalCount); }else{ /**How many pieces are displayed per page*/ Long everPage = null == value ? 10: Long.parseLong(value); /** Get the paging class in Session to facilitate saving the page paging status*/ page = sessionPage; page.setEveryPage(everPage); page.setTotalCount(totalCount); } return page; } /** * When the page clicks: home page, previous page, next page, last page, sort, and the page is the first page* @param index paging status* @param value sort field name or page is the first page*/ public static Page execPage(int index,String value,Page sessionPage){ Page page = sessionPage; /** Call method for paging calculation*/ page.pageState(index,value); return page; } } 4.DefaultController.java This part can be used flexibly
package com.cm.contract.common; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.bind.annotation.ModelAttribute; /** * Extract public request and response Title:DefaultController Description: * * @author FENGWEI * @date 2016-5-6 3:30:32 pm */ public class DefaultController { /** * The three-layer pagination sentence class of oracel performs pagination calculation before displaying the data! * * @param querySql * The query SQL statement, not paginated* @param totalCount * The total number of entries obtained based on the query SQL* @param columnNameDescOrAsc * Column name + sorting method: ID DESC or ASC */ protected Page executePage(HttpServletRequest request, Long totalCount) { if (null == totalCount) { totalCount = 0L; } /** Page status, this status is built on page and has nothing to do with business*/ String pageAction = request.getParameter("pageAction"); String value = request.getParameter("pageKey"); /** Get index to judge the page status status */ int index = PageState.getOrdinal(pageAction); Page page = null; /** * index < 1 There are only two states 1 When the first call, there is no value in the page status class NULL Return -1 2 When the page sets how many pieces are displayed per page: * index=0, when there are many pieces displayed per page, the page class needs to be recalculated* */ Page sessionPage = getPage(request); if (index < 1) { page = PageUtil.inintPage(totalCount, index, value, sessionPage); } else { page = PageUtil.execPage(index, value, sessionPage); } setSession(request, page); return page; } private Page getPage(HttpServletRequest request) { Page page = (Page) request.getSession().getAttribute( PageUtil.SESSION_PAGE_KEY); if (page == null) { page = new Page(); } return page; } private void setSession(HttpServletRequest request, Page page) { request.getSession().setAttribute(PageUtil.SESSION_PAGE_KEY, page); } } How to use:
5. Controller.java
/** * Paging conditions added by model* executePage method is written in the tool class* @param model */ @Controller public class CMLogController extends DefaultController { @RequestMapping("index.do") public ModelAndView userInto(ModelMap model, String username) { nameStr = username; model.addAttribute("username", nameStr); // Number of pages Long totalCount = logService.pageCounts(model); // Page display page = executePage(request, totalCount); if (page.isSort()) { model.put("orderName", page.getSortName()); model.put("descAsc", page.getSortState()); } else { model.put("orderName", "logtime"); model.put("descAsc", "desc"); } model.put("startIndex", page.getBeginIndex()); model.put("endIndex", page.getEndinIndex()); ModelAndView mv = new ModelAndView(); // Pagination query logList = logService.pageList(model); mv.addObject("logList", logList); mv.setViewName("/jsp/log"); return mv; }} 6. Several query statements in maybatis
//Pagination query <select id="pageList" parameterType="map" resultMap="BaseResultMap"> select ttt.* from(select tt.*,rownum rn from(select * from CM_LOG <where> <if test="username != null and username != ''"> <!-- A special reminder is that $ is just a string splicing, so you should be particularly careful about SQL injection. Used during development: $, convenient for debugging sql, use it during release: # --> and username like '%${username}%' </if> <if test="type != null and type != ''"> <!-- A special reminder, $ is just a string splicing, so you should be particularly careful about SQL injection. Use: $ during development, convenient for debugging sql, use: # --> AND TYPE = #{type,jdbcType=VARCHAR} </if> </where> order by ${orderName} ${descAsc} )tt)ttt <where> <if test="startIndex != null and startIndex != ''"> rn > ${startIndex} </if> <if test="endIndex != null and endIndex != ''"> <![CDATA[ and rn <= ${endIndex} ]]> </if> </where> </select> // Number of pages<select id="pageCounts" parameterType="map" resultType="long"> select count(*) from CM_LOG <where> <if test="username != null and username != ''"> and username like '%${username}%' </if> </where> </select> 7. Front Desk Page index.jsp
//Simply add the div in the page layout //username as a condition // <jsp:param name="url" value="/log/index.do?"/> The question mark without condition must exist <body > <div align="right" style="height: 20"> <jsp:include page="/jsp/page.jsp"> <jsp:param name="url" value="/log/index.do?username=${username }"/> </jsp:include> </div> </body > 8. Page.jsp referenced
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <c:set var="page" value="${sessionScope.page}" /> <c:set var="path" value="${pageContext.request.contextPath}" /> <c:set var="url" value="${param.url}" /> <c:set var="urlParams" value="${param.urlParams}" /> <c:set var="pathurl" value="${path}/${url}" /> <tr> <td colspan="5"> ${urlParams } Total ${page.totalCount} records Total ${page.totalPage} pages per page show ${page.everyPage} currently the ${page.currentPage} page<c:choose> <c:when test="${page.hasPrePage eq false}"> <<Homepage<PrePage</c:when> <c:otherwise> <a href="${pathurl}&pageAction=first${urlParams}"><<Homepage</a> <a href="${pathurl}&pageAction=previous${urlParams}" /><Previous page</a> </c:otherwise> </c:choose> || <c:choose> <c:when test="${page.hasNextPage eq false}"> Next page> Last page>> </c:when> <c:otherwise> <a href="${pathurl}&pageAction=next${urlParams}">Next page> </a> <a href="${pathurl}&pageAction=last${urlParams}">Last page>></a> </c:otherwise> </c:choose> <SELECT name="indexChange" id="indexChange" onchange="getCurrentPage(this.value);"> <c:forEach var="index" begin="1" end="${page.totalPage}" step="1"> <option value="${index}" ${page.currentPage eq index ? "selected" : ""}> ${index} page</option> </c:forEach> </SELECT> Display per page:<select name="everyPage" id="everyPage" onchange="setEveryPage(this.value);"> <c:forEach var="pageCount" begin="5" end="${page.totalCount}" step="5"> <option value="${pageCount}" ${page.everyPage eq pageCount ? "selected" : ""}> ${pageCount}bar</option> </c:forEach> </select> </td> </td> </tr> <div style='display: none'> <a class=listlink id="indexPageHref" href='#'></a> </div> <script> function getCurrentPage(index){ var a = document.getElementById("indexPageHref"); a.href = '${pathurl}&pageAction=gopage&pageKey='+index+'${urlParams}'; a.setAttribute("onclick",''); a.click("return false"); } function setEveryPage(everyPage){ var a = document.getElementById("indexPageHref"); var currentPage = document.getElementById('indexChange').value; a.href = '${pathurl}&pageAction=setpage&pageKey='+everyPage+'${urlParams}'; a.setAttribute("onclick",''); a.click("return false"); } function sortPage(sortName){ var a = document.getElementById("indexPageHref"); a.href = '${pathurl}&pageAction=sort&pageKey='+sortName+'${urlParams}'; a.setAttribute("onclick",''); a.click("return false"); } </script>The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.