springmvc4+hibernate4分頁查詢功能

CortneyHume 8年前發布 | 65K 次閱讀 Hibernate Spring MVC Web框架

來自: http://www.cnblogs.com/luihengk/p/5248041.html

Springmvc+hibernate成為現在很多人用的框架整合,最近自己也在學習摸索,由于我們在開發項目中很多項目都用到列表分頁功能,在此參考網上一些資料,以springmvc4+hibnerate4邊學邊總結,得出分頁功能代碼,雖然不一定通用,對于初學者來說有參考價值。

分頁實現的基本過程:

一、分頁工具類

思路:

  1. 編寫Page類,定義屬性,應該包括:查詢結果集合、查詢記錄總數、每頁顯示記錄數、當前第幾頁等屬性。
  2. 編寫Page類,定義方法,應該包括:總頁數、當前頁開始記錄、首頁、下一頁、上一頁、末頁等方法

代碼如下:

package cn.myic.model;

import java.util.List;

public class Page<E> { // 結果集 private List<E> list;

// 查詢記錄總數
private int totalRecords;

// 每頁多少條記錄
private int pageSize;

// 第幾頁
private int pageNo;

/**
 * @return 總頁數
 * */
public int getTotalPages(){
    return (totalRecords+pageSize-1)/pageSize;
}

/**
 * 計算當前頁開始記錄
 * @param pageSize 每頁記錄數
 * @param currentPage 當前第幾頁
 * @return 當前頁開始記錄號
 */
public int countOffset(int currentPage,int pageSize){
    int offset = pageSize*(currentPage-1);
    return offset;
}

/**
 * @return 首頁
 * */
public int getTopPageNo(){
    return 1;
}

/**
 * @return 上一頁
 * */
public int getPreviousPageNo(){
    if(pageNo<=1){
        return 1;
    }
    return pageNo-1;
}

/**
 * @return 下一頁
 * */
public int getNextPageNo(){
    if(pageNo>=getBottomPageNo()){
        return getBottomPageNo();
    }
    return pageNo+1;
}

/**
 * @return 尾頁
 * */
public int getBottomPageNo(){
    return getTotalPages();
}


public List<E> getList() {
    return list;
}

public void setList(List<E> list) {
    this.list = list;
}

public int getTotalRecords() {
    return totalRecords;
}

public void setTotalRecords(int totalRecords) {
    this.totalRecords = totalRecords;
}

public int getPageSize() {
    return pageSize;
}

public void setPageSize(int pageSize) {
    this.pageSize = pageSize;
}

public int getPageNo() {
    return pageNo;
}

public void setPageNo(int pageNo) {
    this.pageNo = pageNo;
}

}</pre>

二、Dao層方法

思路:定義一個分頁查詢的方法,設置參數:當頁頁號和每頁顯示多少條記錄

代碼如下:

/**

  * 分頁查詢
  * @param hql 查詢的條件
  * @param offset 開始記錄
  * @param length 一次查詢幾條記錄
  * @return 返回查詢記錄集合
  */
@SuppressWarnings("unchecked")
@Override
public List<Course> queryForPage(int offset, int length) {
    // TODO Auto-generated method stub
    List<Course> entitylist=null;
    try{
        Query query = getSession().createQuery("from Course");
        query.setFirstResult(offset);
        query.setMaxResults(length);
        entitylist = query.list();

    }catch(RuntimeException re){
        throw re;
    }

    return entitylist;
}</pre> 

三、Service層方法

思路:

  1. 定義一個分頁查詢的方法,設置參數:當頁頁號和每頁顯示多少條記錄,返回查詢結果的分頁類對象(Page)
  2. 通過Dao層,獲取查詢實體的總記錄數
  3. 獲取當前頁開始記錄數
  4. 通過Dao層,獲取分頁查詢結果集
  5. Set入page對象

代碼如下:

/**

 * 分頁查詢 
 * @param currentPage 當前頁號:現在顯示的頁數
 * @param pageSize 每頁顯示的記錄條數
 * @return 封閉了分頁信息(包括記錄集list)的Bean
 * */
@SuppressWarnings("unchecked")
@Override
public Page queryForPage(int currentPage,int pageSize) {
    // TODO Auto-generated method stub

    Page page = new Page();        
    //總記錄數
    int allRow = courseDao.getAllRowCount();
    //當前頁開始記錄
    int offset = page.countOffset(currentPage,pageSize);  
    //分頁查詢結果集
    List<Course> list = courseDao.queryForPage(offset, pageSize); 

    page.setPageNo(currentPage);
    page.setPageSize(pageSize);
    page.setTotalRecords(allRow);
    page.setList(list);

    return page;
}</pre> 

四、Controller層方法

Controller層的設計,操作翻頁查詢時,只需要傳遞當前頁號參數即可。

代碼如下:

@RequestMapping(value = "/showAll.do")
    public String findAllCourse(HttpServletRequest request,
            HttpServletResponse response) {
        try {
            String pageNo = request.getParameter("pageNo");
            if (pageNo == null) {
                pageNo = "1";
            }
            Page page = courseService.queryForPage(Integer.valueOf(pageNo), 10);
            request.setAttribute("page", page);
            List<Course> course = page.getList();
            request.setAttribute("courses", course);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "course/course_list";
    }

五、 View 層jsp展示

jsp頁面分頁的幾個按鈕,根據當前頁號的判斷顯示。

代碼如下:

<tr>
            <td colspan="6" align="center" bgcolor="#5BA8DE">共${page.totalRecords}條記錄 共${page.totalPages}頁 當前第${page.pageNo}頁<br>

            <a href="${path}/course/showAll.do?pageNo=${page.topPageNo }"><input type="button" name="fristPage" value="首頁" /></a>
            <c:choose>
              <c:when test="${page.pageNo!=1}">

                  <a href="${path}/course/showAll.do?pageNo=${page.previousPageNo }"><input type="button" name="previousPage" value="上一頁" /></a>

              </c:when>
              <c:otherwise>

                  <input type="button" disabled="disabled" name="previousPage" value="上一頁" />

              </c:otherwise>
            </c:choose>
            <c:choose>
              <c:when test="${page.pageNo != page.totalPages}">
                <a href="${path}/course/showAll.do?pageNo=${page.nextPageNo }"><input type="button" name="nextPage" value="下一頁" /></a>
              </c:when>
              <c:otherwise>

                  <input type="button" disabled="disabled" name="nextPage" value="下一頁" />

              </c:otherwise>
            </c:choose>
            <a href="${path}/course/showAll.do?pageNo=${page.bottomPageNo }"><input type="button" name="lastPage" value="尾頁" /></a>
        </td>
    </tr></pre> 

頁面效果:

</div>

 本文由用戶 CortneyHume 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!