springmvc+Mybatis 分页查询的简单实现

本文详细介绍了一种基于修改SQL实现的分页技术,包括分页类Page的定义与使用方法,以及如何结合MyBatis和Spring MVC框架实现动态分页功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目前较常用的分页实现办法有两种:
 
  1.每次翻页都修改SQL,向SQL传入相关参数去 数据库实时查出该页的数据并显示。
 
  2.查出数据库某张表的全部数据,再通过在业务逻辑里面进行处理去取得某些数据并显示。
 
  对于数据量并不大的简单的管理系统而言,第一种实现方法相对来说容易使用较少的代码实现分页这一功能,本文也正是为大家介绍这种方法:
 
代码片段:
1,Page.java
[java]  view plain  copy
  1. package com.cm.contract.common;  
  2.   
  3. import org.apache.commons.lang.StringUtils;  
  4. import org.apache.commons.lang.builder.ToStringBuilder;  
  5.   
  6.   
  7.   
  8. /**分页类 
  9.  * @author FENGWEI 
  10.  * @date 2016-5-23 
  11.  */  
  12. public class Page implements java.io.Serializable{  
  13.       
  14.     private static final long serialVersionUID = 1L;  
  15.     //前一页  
  16.     private Boolean hasPrePage;  
  17.     //后一页  
  18.     private Boolean hasNextPage;  
  19.     //每页显示多少条:默认20条  
  20.     private Long everyPage = 20L;  
  21.     //总页数  
  22.     private Long totalPage;  
  23.     //当前第多少页:默认第1页  
  24.     private Long currentPage = 1L;  
  25.     //开始下标  
  26.     private Long beginIndex;  
  27.     //结束下标  
  28.     private Long endinIndex;  
  29.     //总共多少条  
  30.     private Long totalCount;      
  31.     //排序列名  
  32.     private String sortName;      
  33.     //排序状态  
  34.     private String sortState;     
  35.     //排序信息  
  36.     private String sortInfo;  
  37.     //是否排序  
  38.     private Boolean sort = false;  
  39.     private String defaultInfo = "  ";  
  40.       
  41.       
  42.       
  43.     public String getDefaultInfo() {  
  44.         return defaultInfo;  
  45.     }  
  46.   
  47.     public void setDefaultInfo(String defaultInfo) {  
  48.         this.defaultInfo = defaultInfo;  
  49.     }  
  50.   
  51.     public String getSortInfo() {  
  52.         return sortInfo;  
  53.     }  
  54.   
  55.     public void setSortInfo(String sortInfo) {  
  56.         this.sortInfo = sortInfo;  
  57.     }  
  58.   
  59.     public String getSortName() {  
  60.         return sortName;  
  61.     }  
  62.   
  63.     public void setSortName(String sortName) {  
  64.         setPageSortState(sortName);       
  65.     }  
  66.   
  67.     public String getSortState() {  
  68.         return sortState;  
  69.     }  
  70.   
  71.     public void setSortState(String sortState) {  
  72.         this.sortState = sortState;  
  73.     }  
  74.   
  75.       
  76.     public Page() {  
  77.     }  
  78.   
  79.     /** 
  80.      * 常用,用于计算分页 
  81.      * */  
  82.     public Page(Long totalRecords){       
  83.         this.totalCount = totalRecords;  
  84.         setTotalPage(getTotalPage(totalRecords));       
  85.     }  
  86.       
  87.     /** 
  88.      * 设置每页显示多少条时使用 
  89.      * */  
  90.     public Page(Long everyPage,Long totalRecords){    
  91.         this.everyPage = everyPage;  
  92.         this.totalCount = totalRecords;  
  93.         setTotalPage(getTotalPage(totalRecords));       
  94.     }  
  95.       
  96.     /** 
  97.      * @param state   状态码 
  98.      * @param value   到第多少页或者设置每页显示多少条或者为排序列名 
  99.      */  
  100.     public void pageState(int  index,String value) {                  
  101.         sort = false;  
  102.         switch (index) {  
  103.         case 0 :setEveryPage(Long.parseLong(value));break;  
  104.         case 1 :first();break;  
  105.         case 2: previous();break;  
  106.         case 3: next();break;  
  107.         case 4: last();break;  
  108.         case 5: sort = true;sort(value);break;  
  109.         case 6 ://到指定第多少页  
  110.             setCurrentPage(Long.parseLong(value));  
  111.             break;            
  112.         }  
  113.     }  
  114.   
  115.     /** 
  116.      * 最前一页 
  117.      */  
  118.     private void first() {  
  119.         currentPage = 1L;  
  120.     }  
  121.   
  122.     private void previous() {  
  123.         currentPage--;  
  124.     }  
  125.   
  126.     private void next() {  
  127.         currentPage++;  
  128.     }  
  129.   
  130.     private void last() {  
  131.         currentPage = totalPage;  
  132.     }  
  133.   
  134.     private void sort(String sortName) {          
  135.         //设置排序状态  
  136.         setPageSortState(sortName);       
  137.     }  
  138.           
  139.       
  140.       
  141.     /** 
  142.      * 计算总页数 
  143.      * */  
  144.     private Long getTotalPage(Long totalRecords) {  
  145.          Long totalPage = 0L;      
  146.          everyPage = everyPage == null ? 10L : everyPage;  
  147.          if (totalRecords % everyPage == 0)  
  148.            totalPage = totalRecords / everyPage;  
  149.          else {  
  150.            totalPage = totalRecords / everyPage + 1;  
  151.          }  
  152.          return totalPage;  
  153.     }     
  154.       
  155.   
  156.     public Long getBeginIndex() {  
  157.         this.beginIndex = (currentPage - 1) * everyPage;  
  158.         return this.beginIndex;  
  159.     }  
  160.   
  161.     public void setBeginIndex(Long beginIndex) {  
  162.         this.beginIndex = beginIndex;  
  163.     }  
  164.   
  165.     public Long getCurrentPage() {  
  166.         this.currentPage = currentPage == 0 ? 1 : currentPage;  
  167.         return this.currentPage;  
  168.     }  
  169.   
  170.     public void setCurrentPage(Long currentPage) {  
  171.         if(0 == currentPage){  
  172.             currentPage = 1L;  
  173.         }  
  174.         this.currentPage = currentPage;  
  175.     }  
  176.   
  177.     public Long getEveryPage() {  
  178.         this.everyPage = everyPage == 0 ? 10 : everyPage;  
  179.         return this.everyPage;  
  180.     }  
  181.   
  182.     public void setEveryPage(Long everyPage) {        
  183.         this.everyPage = everyPage;  
  184.     }  
  185.   
  186.     public Boolean getHasNextPage() {  
  187.         this.hasNextPage = (currentPage != totalPage) && (totalPage != 0);  
  188.         return this.hasNextPage;  
  189.     }  
  190.   
  191.     public void setHasNextPage(Boolean hasNextPage) {  
  192.         this.hasNextPage = hasNextPage;  
  193.     }  
  194.   
  195.     public Boolean getHasPrePage() {  
  196.         this.hasPrePage = currentPage != 1;  
  197.         return this.hasPrePage;  
  198.     }  
  199.   
  200.     public void setHasPrePage(Boolean hasPrePage) {  
  201.         this.hasPrePage = hasPrePage;  
  202.     }  
  203.   
  204.     public Long getTotalPage() {  
  205.         return this.totalPage;  
  206.     }  
  207.   
  208.     public void setTotalPage(Long totalPage) {  
  209.         if(this.currentPage > totalPage){  
  210.             this.currentPage = totalPage;  
  211.         }  
  212.         this.totalPage = totalPage;  
  213.     }  
  214.   
  215.     public Long getTotalCount() {  
  216.         return this.totalCount;  
  217.     }  
  218.   
  219.     public void setTotalCount(Long totalCount) {  
  220.         setTotalPage(getTotalPage(totalCount));    
  221.         this.totalCount = totalCount;  
  222.     }  
  223.   
  224.     @Override  
  225.     public String toString() {  
  226.         return ToStringBuilder.reflectionToString(this);  
  227.     }  
  228.       
  229.     /** 
  230.      * 设置排序状态 
  231.      * */  
  232.     private void setPageSortState(String newPageSortName){        
  233.         //判断之前的排序字段是否为空  
  234.         if(StringUtils.isEmpty(sortName)){  
  235.             //默认排序为升序  
  236.             this.sortState = PageUtil.ASC;        
  237.             this.sortInfo = PageUtil.PAGE_ASC;                        
  238.         }else{  
  239.             if(StringUtils.equalsIgnoreCase(newPageSortName, sortName)){  
  240.                 //判断sortState排序状态值  
  241.                 if(StringUtils.equalsIgnoreCase(sortState, PageUtil.ASC)){  
  242.                     this.sortState = PageUtil.DESC;  
  243.                     this.sortInfo = PageUtil.PAGE_DESC;                               
  244.                 }else{  
  245.                     this.sortState = PageUtil.ASC;  
  246.                     this.sortInfo = PageUtil.PAGE_ASC;                    
  247.                 }                 
  248.             }else{  
  249.                 //默认  
  250.                 this.sortState = PageUtil.ASC;        
  251.                 this.sortInfo = PageUtil.PAGE_ASC;  
  252.             }  
  253.         }  
  254.         sortName = newPageSortName.toLowerCase();             
  255.     }  
  256.   
  257.     public Boolean isSort() {  
  258.         return sort;  
  259.     }  
  260.   
  261.     public void setSort(Boolean sort) {  
  262.         this.sort = sort;  
  263.     }  
  264.   
  265.   
  266.     public Long getEndinIndex() {  
  267.         this.endinIndex = (currentPage) * everyPage;  
  268.         return endinIndex;  
  269.     }  
  270.   
  271.     public void setEndinIndex(Long endinIndex) {  
  272.         this.endinIndex = endinIndex;  
  273.     }     
  274. }  
2.PageState.java
[java]  view plain  copy
  1. package com.cm.contract.common;  
  2.   
  3. import org.apache.commons.lang.StringUtils;  
  4.   
  5.   
  6.   
  7.   
  8. /**分页状态类 
  9.  * @author FENGWEI 
  10.  * @date 2016-5-23 
  11.  */  
  12. public enum PageState {  
  13.       
  14.     /** 
  15.      * 设置每页显示多少条 
  16.      * */  
  17.     SETPAGE,  
  18.     /** 
  19.      * 首页 
  20.      * */  
  21.     FIRST,   
  22.     /** 
  23.      * 向前一页 
  24.      * */  
  25.     PREVIOUS,   
  26.     /** 
  27.      * 向后一页 
  28.      * */  
  29.     NEXT,   
  30.     /** 
  31.      * 末页 
  32.      * */  
  33.     LAST,   
  34.     /** 
  35.      * 排序 
  36.      * */  
  37.     SORT,  
  38.     /** 
  39.      * 到第多少页 
  40.      * */  
  41.     GOPAGE;  
  42.   
  43.       
  44.     /** 
  45.      * @param value 索引名称 
  46.      * @return 返回索引下标 
  47.      */  
  48.     public static int getOrdinal(String value) {  
  49.         int index = -1;  
  50.         if (StringUtils.isEmpty(value)) {  
  51.             return index;  
  52.         }  
  53.         String newValue = StringUtils.trim(value).toUpperCase();  
  54.         try {  
  55.             index = valueOf(newValue).ordinal();  
  56.         } catch (IllegalArgumentException e) {}  
  57.         return index;  
  58.     }  
  59. }  

3.PageUtil.java
[java]  view plain  copy
  1. /** 
  2.  * 分页工具类 
  3.  * @author FENGWEI 
  4.  * @date 2016-5-23 
  5.  */  
  6. public class PageUtil {  
  7.       
  8.     public static final String ASC = "asc";  
  9.     public static final String DESC = "desc";  
  10.     public static final String PAGE_DESC = "↓";  
  11.     public static final String PAGE_ASC = "↑";  
  12.     public static final String PAGE_NULL = "  ";    
  13.     public static final String SESSION_PAGE_KEY = "page";     
  14.       
  15.       
  16.     /** 
  17.      * 初始化分页类 
  18.      * @param initPageSql  未分页的查询SQL 
  19.      * @param totalCount   总行数 
  20.      * @param index        分页状态 
  21.      * @param value        只有在设置每页显示多少条时,值不会NULL,其它为NULL 
  22.      */  
  23.     public  static Page inintPage(Long totalCount,Integer index,String value,Page sessionPage){   
  24.         Page page = null;  
  25.         if(index < 0){  
  26.              page = new Page(totalCount);  
  27.         }else{  
  28.              /**每页显示多少条*/  
  29.              Long everPage = null == value ? 10 : Long.parseLong(value);  
  30.              /**获取Session中的分页类,方便保存页面分页状态*/  
  31.              page = sessionPage;               
  32.              page.setEveryPage(everPage);  
  33.              page.setTotalCount(totalCount);              
  34.         }     
  35.         return page;          
  36.     }  
  37.       
  38.       
  39.   
  40.       
  41.     /** 
  42.      * 当页点击:首页,前一页,后一页,末页,排序,到第多少页时进行分页操作 
  43.      * @param index 分页状态 
  44.      * @param value 排序字段名或者到第多少页 
  45.      */  
  46.     public static Page execPage(int  index,String value,Page sessionPage){    
  47.         Page page = sessionPage;              
  48.         /**调用方法进行分页计算*/  
  49.         page.pageState(index,value);          
  50.         return page;          
  51.     }  
  52.   
  53. }  

4.DefaultController.java  此部分可以灵活使用
[java]  view plain  copy
  1. package com.cm.contract.common;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5. import javax.servlet.http.HttpSession;  
  6.   
  7. import org.springframework.web.bind.annotation.ModelAttribute;  
  8.   
  9. /** 
  10.  * 提取公用的request和response Title:DefaultController Descrption: 
  11.  *  
  12.  * @author FENGWEI 
  13.  * @date 2016-5-6下午3:30:32 
  14.  */  
  15. public class DefaultController  {  
  16.   
  17.     /** 
  18.      * oracel的三层分页语句 子类在展现数据前,进行分页计算! 
  19.      *  
  20.      * @param querySql 
  21.      *            查询的SQL语句,未进行分页 
  22.      * @param totalCount 
  23.      *            根据查询SQL获取的总条数 
  24.      * @param columnNameDescOrAsc 
  25.      *            列名+排序方式 : ID DESC or ASC 
  26.      */  
  27.     protected Page executePage(HttpServletRequest request, Long totalCount) {  
  28.         if (null == totalCount) {  
  29.             totalCount = 0L;  
  30.         }  
  31.         /** 页面状态,这个状态是分页自带的,与业务无关 */  
  32.         String pageAction = request.getParameter("pageAction");  
  33.         String value = request.getParameter("pageKey");  
  34.   
  35.         /** 获取下标判断分页状态 */  
  36.         int index = PageState.getOrdinal(pageAction);  
  37.   
  38.         Page page = null;  
  39.         /** 
  40.          * index < 1 只有二种状态 1 当首次调用时,分页状态类中没有值为 NULL 返回 -1 2 当页面设置每页显示多少条: 
  41.          * index=0,当每页显示多少条时,分页类要重新计算 
  42.          * */  
  43.         Page sessionPage = getPage(request);  
  44.   
  45.         if (index < 1) {  
  46.             page = PageUtil.inintPage(totalCount, index, value, sessionPage);  
  47.         } else {  
  48.             page = PageUtil.execPage(index, value, sessionPage);  
  49.         }  
  50.         setSession(request, page);  
  51.         return page;  
  52.     }  
  53.   
  54.     private Page getPage(HttpServletRequest request) {  
  55.         Page page = (Page) request.getSession().getAttribute(  
  56.                 PageUtil.SESSION_PAGE_KEY);  
  57.         if (page == null) {  
  58.             page = new Page();  
  59.         }  
  60.         return page;  
  61.     }  
  62.   
  63.     private void setSession(HttpServletRequest request, Page page) {  
  64.         request.getSession().setAttribute(PageUtil.SESSION_PAGE_KEY, page);  
  65.     }  
  66. }  

使用方法:
5,Controller.java 
[java]  view plain  copy
  1. /** 
  2.      * model 添加的分页条件 
  3.      *  executePage 方法写在工具类中 
  4.      * @param model 
  5.      */  
  6. @Controller  
  7. public class CMLogController extends DefaultController {  
  8. @RequestMapping("index.do")  
  9.     public ModelAndView userInto(ModelMap model, String username) {  
  10.         nameStr = username;  
  11.         model.addAttribute("username", nameStr);  
  12.         // 分页数  
  13.         Long totalCount = logService.pageCounts(model);  
  14.         // 分页显示  
  15.         Page page = executePage(request, totalCount);  
  16.         if (page.isSort()) {  
  17.             model.put("orderName", page.getSortName());  
  18.             model.put("descAsc", page.getSortState());  
  19.         } else {  
  20.             model.put("orderName""logtime");  
  21.             model.put("descAsc""desc");  
  22.         }  
  23.         model.put("startIndex", page.getBeginIndex());  
  24.         model.put("endIndex", page.getEndinIndex());  
  25.         ModelAndView mv = new ModelAndView();  
  26.         // 分页查询  
  27.         logList = logService.pageList(model);  
  28.         mv.addObject("logList", logList);  
  29.         mv.setViewName("/jsp/log");  
  30.         return mv;  
  31.     }}  
6.maybatis中几条查询语句
[html]  view plain  copy
  1. //分页查询  
  2. <select id="pageList" parameterType="map"  resultMap="BaseResultMap">     
  3.          
  4.        select ttt.* from(select tt.*,rownum rn from(select * from CM_LOG  
  5.         <where>            
  6.            <if test="username != null and username != ''">  
  7.                <!--   
  8.                   特别提醒一下, $只是字符串拼接, 所以要特别小心sql注入问题。  
  9.                   在开发时使用: $,方便调试sql,发布时使用: #  
  10.                -->  
  11.                and username like '%${username}%'                     
  12.            </if>  
  13.              <if test="type != null and type != ''">  
  14.                <!--   
  15.                   特别提醒一下, $只是字符串拼接, 所以要特别小心sql注入问题。  
  16.                   在开发时使用: $,方便调试sql,发布时使用: #  
  17.                -->  
  18.                AND TYPE = #{type,jdbcType=VARCHAR}       
  19.            </if>  
  20.          </where>    
  21.          order by ${orderName} ${descAsc} )tt)ttt  
  22.          <where>   
  23.            <if test="startIndex != null and startIndex != ''">  
  24.                rn > ${startIndex}                     
  25.            </if>    
  26.             <if test="endIndex != null and endIndex != ''">                
  27.                  <![CDATA[ and rn <= ${endIndex}  ]]>                               
  28.             </if>      
  29.          </where>            
  30. </select>  
  31. // 分页数  
  32.   <select id="pageCounts" parameterType="map" resultType="long">     
  33.    select count(*) from CM_LOG   
  34.    <where>   
  35.    <if test="username != null and username != ''">  
  36.         and username like '%${username}%'                    
  37.    </if>    
  38.    </where>    
  39. </select>  

7.前台页面index.jsp
[javascript]  view plain  copy
  1. //只需在页面布局添加该div  
  2.     //username 为条件   
  3.     //  <jsp:param name="url" value="/log/index.do?"/>        不带条件的方式 问号必须存在  
  4. <body >  
  5.     <div align="right" style="height: 20">  
  6.             <jsp:include page="/jsp/page.jsp">  
  7.                     <jsp:param name="url" value="/log/index.do?username=${username }"/>         
  8.   
  9.                 </jsp:include>  
  10.         </div>  
  11.   
  12.         </body >  

8,引用的Page.jsp
[javascript]  view plain  copy
  1.     <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  4. <c:set var="page" value="${sessionScope.page}" />  
  5. <c:set var="path" value="${pageContext.request.contextPath}" />  
  6. <c:set var="url" value="${param.url}" />  
  7. <c:set var="urlParams" value="${param.urlParams}" />  
  8. <c:set var="pathurl" value="${path}/${url}" />  
  9. <tr>  
  10.     <td colspan="5">  
  11.     ${urlParams }  
  12.         共${page.totalCount}条记录 共${page.totalPage}页 每页显示${page.everyPage}条  
  13.         当前第${page.currentPage}页   
  14.         <c:choose>  
  15.             <c:when test="${page.hasPrePage eq false}">  
  16.                 <<首页 <上页   
  17.             </c:when>  
  18.             <c:otherwise>  
  19.                 <a href="${pathurl}&pageAction=first${urlParams}"><<首页 </a>   
  20.                 <a href="${pathurl}&pageAction=previous${urlParams}" /><上一页</a>  
  21.             </c:otherwise>  
  22.         </c:choose>  
  23.          ||   
  24.         <c:choose>  
  25.             <c:when test="${page.hasNextPage eq false}">  
  26.                  下页> 尾页>>  
  27.             </c:when>  
  28.             <c:otherwise>  
  29.                 <a href="${pathurl}&pageAction=next${urlParams}">下一页> </a>   
  30.                 <a href="${pathurl}&pageAction=last${urlParams}">末页>></a>  
  31.             </c:otherwise>  
  32.         </c:choose>  
  33.            
  34.         <SELECT name="indexChange" id="indexChange"  
  35.             onchange="getCurrentPage(this.value);">  
  36.             <c:forEach var="index" begin="1" end="${page.totalPage}" step="1">  
  37.                 <option value="${index}" ${page.currentPage eq index ? "selected" : ""}>  
  38.                     第${index}页  
  39.                 </option>  
  40.             </c:forEach>  
  41.         </SELECT>  
  42.            
  43.         每页显示:<select name="everyPage" id="everyPage" onchange="setEveryPage(this.value);">  
  44.                    <c:forEach var="pageCount" begin="5" end="${page.totalCount}" step="5">                          
  45.                         <option value="${pageCount}" ${page.everyPage eq pageCount ? "selected" : ""}>  
  46.                             ${pageCount}条  
  47.                         </option>  
  48.                     </c:forEach>  
  49.                </select>  
  50.     </td>  
  51. </tr>  
  52. <div style='display: none'>  
  53.     <a class=listlink id="indexPageHref" href='#'></a>  
  54. </div>  
  55. <script>  
  56. function getCurrentPage(index){   
  57.     var a = document.getElementById("indexPageHref");     
  58.     a.href = '${pathurl}&pageAction=gopage&pageKey='+index+'${urlParams}';          
  59.     a.setAttribute("onclick",'');            
  60.     a.click("return false");     
  61. }  
  62. function setEveryPage(everyPage){     
  63.     var a = document.getElementById("indexPageHref");  
  64.     var currentPage = document.getElementById('indexChange').value;  
  65.     a.href = '${pathurl}&pageAction=setpage&pageKey='+everyPage+'${urlParams}';         
  66.     a.setAttribute("onclick",'');            
  67.     a.click("return false");     
  68. }  
  69. function sortPage(sortName){      
  70.     var a = document.getElementById("indexPageHref");     
  71.     a.href = '${pathurl}&pageAction=sort&pageKey='+sortName+'${urlParams}';        
  72.     a.setAttribute("onclick",'');        
  73.     a.click("return false");     
  74. }  
  75. </script>  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值