Simple implementation of springmvc paging query sample code


Currently, there are two commonly used pagination implementation methods:

1. Modify SQL every time you turn a page, and pass relevant parameters to SQL to check the data of this page in the database in real time and display it.

2. Check all the data of a table in the database, and then get some data and display them through processing 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 realize the pagination 1 function. This article is also to introduce this method for you:

Code snippet:

1, Page java

package com.cm.contract.common;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;



/** Paging class
 * @author FENGWEI
 * @date 2016-5-23
 */
public class Page implements java.io.Serializable{

  private static final long serialVersionUID = 1L;
  // before 1 page
  private Boolean hasPrePage;
  // after 1 page
  private Boolean hasNextPage;
  // How many items are displayed per page : The default 20 article
  private Long everyPage = 20L;
  // Total number of pages
  private Long totalPage;
  // Current page number : By default the first 1 page
  private Long currentPage = 1L;
  // Start the subscript
  private Long beginIndex;
  // The end of the subscript
  private Long endinIndex;
  // How many pieces altogether
  private Long totalCount;
  // Sort the column name
  private String sortName;
  // Order status
  private String sortState;
  // Ordering information
  private String sortInfo;
  // Whether the sorting
  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() {
  }

  /**
   *  The commonly used , For calculating paging
   * */
  public Page(Long totalRecords){
    this.totalCount = totalRecords;
    setTotalPage(getTotalPage(totalRecords));
  }

  /**
   *  Use when setting how many bars to display per page
   * */
  public Page(Long everyPage,Long totalRecords){
    this.everyPage = everyPage;
    this.totalCount = totalRecords;
    setTotalPage(getTotalPage(totalRecords));
  }

  /**
   * @param state   Status code
   * @param value   Go to page number or set how many columns to display per page or sort column names
   */
  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 number of pages
      setCurrentPage(Long.parseLong(value));
      break;
    }
  }

  /**
   *  The former 1 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 sort state
    setPageSortState(sortName);
  }



  /**
   *  Total page count
   * */
  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 sort state
   * */
  private void setPageSortState(String newPageSortName){
    // Determines if the previous sort field is empty
    if(StringUtils.isEmpty(sortName)){
      // The default sort is ascending
      this.sortState = PageUtil.ASC;
      this.sortInfo = PageUtil.PAGE_ASC;
    }else{
      if(StringUtils.equalsIgnoreCase(newPageSortName, sortName)){
        // judge sortState Sort state 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{
        // The 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;




/** Paging state class
 * @author FENGWEI
 * @date 2016-5-23
 */
public enum PageState {

  /**
   *  Set how many bars to display per page
   * */
  SETPAGE,
  /**
   *  Home page
   * */
  FIRST,
  /**
   *  forward 1 page
   * */
  PREVIOUS,
  /**
   *  backward 1 page
   * */
  NEXT,
  /**
   *  At the end of the page
   * */
  LAST,
  /**
   *  The sorting
   * */
  SORT,
  /**
   *  To page one
   * */
  GOPAGE;


  /**
   * @param value  The index name
   * @return  Returns the 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

/**
 *  Paging utility 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 = " left ";
  public static final String PAGE_ASC = " write ";
  public static final String PAGE_NULL = " ";
  public static final String SESSION_PAGE_KEY = "page";


  /**
   *  Initializes the split page class
   * @param initPageSql  Non-paged queries SQL
   * @param totalCount   Total number of rows
   * @param index     Paging state
   * @param value     Only when you set how many bars to display per page , Values are not NULL, For the other 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 items are displayed per page */
       Long everPage = null == value ? 10 : Long.parseLong(value);
       /** To obtain Session The paging class in , Easy to save page paging state */
       page = sessionPage;
       page.setEveryPage(everPage);
       page.setTotalCount(totalCount);
    }
    return page;
  }




  /**
   *  When page click: home page , before 1 page , after 1 page , At the end of the page , The sorting , Paging to the number of pages
   * @param index  Paging state
   * @param value  Sort the field name or to page number
   */
  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 common request and response Title:DefaultController Descrption:
 *
 * @author FENGWEI
 * @date 2016-5-6 In the afternoon 3:30:32
 */
public class DefaultController {

  /**
   * oracel the 3 Layer paging statement   Subclasses before presenting the data , Do paging computation !
   *
   * @param querySql
   *       Of the query SQL statements , No paging
   * @param totalCount
   *       According to the query SQL The total number of bars obtained
   * @param columnNameDescOrAsc
   *       The column name + The sorting way  : ID DESC or ASC
   */
  protected Page executePage(HttpServletRequest request, Long totalCount) {
    if (null == totalCount) {
      totalCount = 0L;
    }
    /**  Page state , This state is native to paging , Nothing to do with business  */
    String pageAction = request.getParameter("pageAction");
    String value = request.getParameter("pageKey");

    /**  Gets subscripts to determine the paging state  */
    int index = PageState.getOrdinal(pageAction);

    Page page = null;
    /**
     * index < 1  only 2 Kind of state  1  When first invoked , There is no value of zero in the paging state class  NULL  return  -1 2  When the page sets how many bars to display per page :
     * index=0, When how many items are displayed per page , The paging class is 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);
  }
}

Usage:

5,Controller.java

/**
   * model  Added paging conditions
   * executePage  The method is written in the utility 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);
    //  Paging display
    Page 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();
    //  Paging query
    logList = logService.pageList(model);
    mv.addObject("logList", logList);
    mv.setViewName("/jsp/log");
    return mv;
  }}

6. Several query statements in maybatis

// Paging 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 != ''">
        <!--
          Special remind 1 Next,  $ It's just string concatenation,   So be very careful sql Injection problem.
          Used at development time : $, Convenient debugging sql, Post time use : #
        -->
        and username like '%${username}%'
      </if>
       <if test="type != null and type != ''">
        <!--
          Special remind 1 Next,  $ It's just string concatenation,   So be very careful sql Injection problem.
          Used at development time : $, Convenient debugging sql, Post time 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 it to the page layout div
  //username  For the condition
  // <jsp:param name="url" value="/log/index.do?"/>     No strings attached   The question mark has to be there
<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

  <%@ 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 }
     A total of ${page.totalCount} records   A total of ${page.totalPage} page   Each page shows ${page.everyPage} article
     The current first ${page.currentPage} page
    <c:choose>
      <c:when test="${page.hasPrePage eq false}">
        << Home page  < On the page
      </c:when>
      <c:otherwise>
        <a href="${pathurl}&pageAction=first${urlParams}"><< Home page  </a>
        <a href="${pathurl}&pageAction=previous${urlParams}" />< on 1 page </a>
      </c:otherwise>
    </c:choose>
     ||
    <c:choose>
      <c:when test="${page.hasNextPage eq false}">
          On the next page >  back >>
      </c:when>
      <c:otherwise>
        <a href="${pathurl}&pageAction=next${urlParams}"> Under the 1 page > </a>
        <a href="${pathurl}&pageAction=last${urlParams}"> At the end of the 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" : ""}>
           The first ${index} page
        </option>
      </c:forEach>
    </SELECT>

     Each page shows :<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} article
            </option>
          </c:forEach>
        </select>
  </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>