ホームページ php教程 PHP开发 springmvc ページングクエリの簡単な実装例コード

springmvc ページングクエリの簡単な実装例コード

Jan 07, 2017 am 10:19 AM

現在一般的に使用されているページング実装方法は 2 つあります:

1. ページがめくられるたびに SQL を変更し、関連するパラメータを SQL に渡して、データベース内のページのデータをリアルタイムで確認して表示します。 。

2. データベース内の特定のテーブル内のすべてのデータを検索し、ビジネス ロジックで処理して特定のデータを取得して表示します。

データ量が少ない単純な管理システムの場合、最初の実装方法は、少ないコードでページング機能を実装するのが比較的簡単です。この記事では、この方法を紹介します:

コード スニペット:

1, Page.java

package com.cm.contract.common; 
  
import org.apache.commons.lang.StringUtils; 
import org.apache.commons.lang.builder.ToStringBuilder; 
  
  
  
/**分页类 
 * @author FENGWEI 
 * @date 2016-5-23 
 */
public class Page implements java.io.Serializable{ 
    
  private static final long serialVersionUID = 1L; 
  //前一页 
  private Boolean hasPrePage; 
  //后一页 
  private Boolean hasNextPage; 
  //每页显示多少条:默认20条 
  private Long everyPage = 20L; 
  //总页数 
  private Long totalPage; 
  //当前第多少页:默认第1页 
  private Long currentPage = 1L; 
  //开始下标 
  private Long beginIndex; 
  //结束下标 
  private Long endinIndex; 
  //总共多少条 
  private Long totalCount;   
  //排序列名 
  private String sortName;   
  //排序状态 
  private String sortState;   
  //排序信息 
  private String sortInfo; 
  //是否排序 
  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() { 
  } 
  
  /** 
   * 常用,用于计算分页 
   * */
  public Page(Long totalRecords){    
    this.totalCount = totalRecords; 
    setTotalPage(getTotalPage(totalRecords));    
  } 
    
  /** 
   * 设置每页显示多少条时使用 
   * */
  public Page(Long everyPage,Long totalRecords){  
    this.everyPage = everyPage; 
    this.totalCount = totalRecords; 
    setTotalPage(getTotalPage(totalRecords));    
  } 
    
  /** 
   * @param state  状态码 
   * @param value  到第多少页或者设置每页显示多少条或者为排序列名 
   */
  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 ://到指定第多少页 
      setCurrentPage(Long.parseLong(value)); 
      break;      
    } 
  } 
  
  /** 
   * 最前一页 
   */
  private void first() { 
    currentPage = 1L; 
  } 
  
  private void previous() { 
    currentPage--; 
  } 
  
  private void next() { 
    currentPage++; 
  } 
  
  private void last() { 
    currentPage = totalPage; 
  } 
  
  private void sort(String sortName) {     
    //设置排序状态 
    setPageSortState(sortName);    
  } 
      
    
    
  /** 
   * 计算总页数 
   * */
  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); 
  } 
    
  /** 
   * 设置排序状态 
   * */
  private void setPageSortState(String newPageSortName){    
    //判断之前的排序字段是否为空 
    if(StringUtils.isEmpty(sortName)){ 
      //默认排序为升序 
      this.sortState = PageUtil.ASC;    
      this.sortInfo = PageUtil.PAGE_ASC;            
    }else{ 
      if(StringUtils.equalsIgnoreCase(newPageSortName, sortName)){ 
        //判断sortState排序状态值 
        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{ 
        //默认 
        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; 
  
  
  
  
/**分页状态类 
 * @author FENGWEI 
 * @date 2016-5-23 
 */
public enum PageState { 
    
  /** 
   * 设置每页显示多少条 
   * */
  SETPAGE, 
  /** 
   * 首页 
   * */
  FIRST,  
  /** 
   * 向前一页 
   * */
  PREVIOUS,  
  /** 
   * 向后一页 
   * */
  NEXT,  
  /** 
   * 末页 
   * */
  LAST,  
  /** 
   * 排序 
   * */
  SORT, 
  /** 
   * 到第多少页 
   * */
  GOPAGE; 
  
    
  /** 
   * @param value 索引名称 
   * @return 返回索引下标 
   */
  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

/** 
 * 分页工具类 
 * @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";   
    
    
  /** 
   * 初始化分页类 
   * @param initPageSql 未分页的查询SQL 
   * @param totalCount  总行数 
   * @param index    分页状态 
   * @param value    只有在设置每页显示多少条时,值不会NULL,其它为NULL 
   */
  public static Page inintPage(Long totalCount,Integer index,String value,Page sessionPage){  
    Page page = null; 
    if(index < 0){ 
       page = new Page(totalCount); 
    }else{ 
       /**每页显示多少条*/
       Long everPage = null == value ? 10 : Long.parseLong(value); 
       /**获取Session中的分页类,方便保存页面分页状态*/
       page = sessionPage;        
       page.setEveryPage(everPage); 
       page.setTotalCount(totalCount);       
    }   
    return page;     
  } 
    
    
  
    
  /** 
   * 当页点击:首页,前一页,后一页,末页,排序,到第多少页时进行分页操作 
   * @param index 分页状态 
   * @param value 排序字段名或者到第多少页 
   */
  public static Page execPage(int index,String value,Page sessionPage){  
    Page page = sessionPage;       
    /**调用方法进行分页计算*/
    page.pageState(index,value);     
    return page;     
  } 
  
}
ログイン後にコピー

4.DefaultController.java この部分は柔軟に使えます

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; 
  
/** 
 * 提取公用的request和response Title:DefaultController Descrption: 
 * 
 * @author FENGWEI 
 * @date 2016-5-6下午3:30:32 
 */
public class DefaultController { 
  
  /** 
   * oracel的三层分页语句 子类在展现数据前,进行分页计算! 
   * 
   * @param querySql 
   *      查询的SQL语句,未进行分页 
   * @param totalCount 
   *      根据查询SQL获取的总条数 
   * @param columnNameDescOrAsc 
   *      列名+排序方式 : ID DESC or ASC 
   */
  protected Page executePage(HttpServletRequest request, Long totalCount) { 
    if (null == totalCount) { 
      totalCount = 0L; 
    } 
    /** 页面状态,这个状态是分页自带的,与业务无关 */
    String pageAction = request.getParameter("pageAction"); 
    String value = request.getParameter("pageKey"); 
  
    /** 获取下标判断分页状态 */
    int index = PageState.getOrdinal(pageAction); 
  
    Page page = null; 
    /** 
     * index < 1 只有二种状态 1 当首次调用时,分页状态类中没有值为 NULL 返回 -1 2 当页面设置每页显示多少条: 
     * index=0,当每页显示多少条时,分页类要重新计算 
     * */
    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); 
  } 
}
ログイン後にコピー

使用方法:

5.Controller.java

/** 
   * model 添加的分页条件 
   * executePage 方法写在工具类中 
   * @param model 
   */
@Controller
public class CMLogController extends DefaultController { 
@RequestMapping("index.do") 
  public ModelAndView userInto(ModelMap model, String username) { 
    nameStr = username; 
    model.addAttribute("username", nameStr); 
    // 分页数 
    Long totalCount = logService.pageCounts(model); 
    // 分页显示 
    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(); 
    // 分页查询 
    logList = logService.pageList(model); 
    mv.addObject("logList", logList); 
    mv.setViewName("/jsp/log"); 
    return mv; 
  }}
ログイン後にコピー

6. Maybatis のいくつかのクエリ ステートメント

//分页查询 
<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 != &#39;&#39;"> 
        <!--  
         特别提醒一下, $只是字符串拼接, 所以要特别小心sql注入问题。 
         在开发时使用: $,方便调试sql,发布时使用: # 
        -->
        and username like &#39;%${username}%&#39;           
      </if> 
       <if test="type != null and type != &#39;&#39;"> 
        <!--  
         特别提醒一下, $只是字符串拼接, 所以要特别小心sql注入问题。 
         在开发时使用: $,方便调试sql,发布时使用: # 
        -->
        AND TYPE = #{type,jdbcType=VARCHAR}    
      </if> 
     </where>  
     order by ${orderName} ${descAsc} )tt)ttt 
     <where>  
      <if test="startIndex != null and startIndex != &#39;&#39;"> 
        rn > ${startIndex}           
      </if>  
      <if test="endIndex != null and endIndex != &#39;&#39;">        
         <![CDATA[ and rn <= ${endIndex} ]]>               
      </if>   
     </where>      
</select> 
// 分页数 
 <select id="pageCounts" parameterType="map" resultType="long">   
  select count(*) from CM_LOG  
  <where>  
  <if test="username != null and username != &#39;&#39;"> 
    and username like &#39;%${username}%&#39;          
  </if>  
  </where>  
</select>
ログイン後にコピー

7. フロント ページのindex.jsp

//只需在页面布局添加该div 
  //username 为条件  
  // <jsp:param name="url" value="/log/index.do?"/>    不带条件的方式 问号必须存在 
<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 } 
    共${page.totalCount}条记录 共${page.totalPage}页 每页显示${page.everyPage}条 
    当前第${page.currentPage}页  
    <c:choose> 
      <c:when test="${page.hasPrePage eq false}"> 
        <<首页 <上页  
      </c:when> 
      <c:otherwise> 
        <a href="${pathurl}&pageAction=first${urlParams}"><<首页 </a>  
        <a href="${pathurl}&pageAction=previous${urlParams}" /><上一页</a> 
      </c:otherwise> 
    </c:choose> 
     ||  
    <c:choose> 
      <c:when test="${page.hasNextPage eq false}"> 
         下页> 尾页>> 
      </c:when> 
      <c:otherwise> 
        <a href="${pathurl}&pageAction=next${urlParams}">下一页> </a>  
        <a href="${pathurl}&pageAction=last${urlParams}">末页>></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}页 
        </option> 
      </c:forEach> 
    </SELECT> 
       
    每页显示:<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}条 
            </option> 
          </c:forEach> 
        </select> 
  </td> 
</tr> 
<div style=&#39;display: none&#39;> 
  <a class=listlink id="indexPageHref" href=&#39;#&#39;></a> 
</div> 
<script> 
function getCurrentPage(index){  
  var a = document.getElementById("indexPageHref");   
  a.href = &#39;${pathurl}&pageAction=gopage&pageKey=&#39;+index+&#39;${urlParams}&#39;;     
  a.setAttribute("onclick",&#39;&#39;);      
  a.click("return false");   
} 
function setEveryPage(everyPage){   
  var a = document.getElementById("indexPageHref"); 
  var currentPage = document.getElementById(&#39;indexChange&#39;).value; 
  a.href = &#39;${pathurl}&pageAction=setpage&pageKey=&#39;+everyPage+&#39;${urlParams}&#39;;     
  a.setAttribute("onclick",&#39;&#39;);      
  a.click("return false");   
} 
function sortPage(sortName){   
  var a = document.getElementById("indexPageHref");   
  a.href = &#39;${pathurl}&pageAction=sort&pageKey=&#39;+sortName+&#39;${urlParams}&#39;;    
  a.setAttribute("onclick",&#39;&#39;);    
  a.click("return false");   
} 
</script>
ログイン後にコピー

を引用しました。上記がこの記事の全内容です。皆様のお役に立てれば幸いです。学習は役に立ちます。皆さんも PHP 中国語 Web サイトをサポートしていただければ幸いです。

springmvc ページング クエリの簡単な実装サンプル コードに関連するその他の記事については、PHP 中国語 Web サイトに注目してください。


このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)