Struts+Hibernate開発実践ページングの実現

7222 ワード

Webアプリケーションの開発を行う際によくページング処理を行い、ページング処理の質問をする人をよく見かけますが、今は自分の処理方法をここに書いて、ページング処理が必要な友達に役に立つことを望んでいます.一、strutsでページを分けるには2つの構造があります.    1.アクションではDAOによってすべてのレコードがクエリされ、セッションまたはrequestオブジェクトに追加され、クライアントに転送され、JSPによってページングされます.       この方法はデータ量が少ない場合に便利で、速度にも影響しません.    2.Actionでは、DAOによって1ページ分のレコードのみがクエリされ、JSPページに渡される.      この構造はデータ量の大きいプログラムにはよいが,データ量が小さい場合にはサーバへの要求を増やし,サーバの負荷を増大させる.二、Hibernateクエリー    Hibernateではデータベースの定点を定量的に検索する方法が直接提供されているので、私は2つ目の方法を採用しています.例えば、1万件目から100件の記録を取り出す

三、具体的な実現1.Pager類
package com.jpcf.db.helper; import java.math.*; public class Pager {  private int totalRows;//総行数  private int pageSize=10;//各ページに表示される行数  private int currentPage;//現在のページ番号  private int totalPages;//総ページ数  private int startRow;//現在のページのデータベースの開始行  public Pager() {  }   public Pager(int _totalRows) {    totalRows = _totalRows;    totalPages=totalRows/pageSize;    int mod=totalRows%pageSize;    if(mod>0){      totalPages++;    }    currentPage = 1;    startRow = 0;  }   public int getStartRow() {    return startRow;  }   public int getTotalPages() {    return totalPages;  }   public int getCurrentPage() {    return currentPage;  }   public int getPageSize() {    return pageSize;  }   public void setTotalRows(int totalRows) {    this.totalRows = totalRows;  }   public void setStartRow(int startRow) {    this.startRow = startRow;  }   public void setTotalPages(int totalPages) {    this.totalPages = totalPages;  }   public void setCurrentPage(int currentPage) {    this.currentPage = currentPage;  }   public void setPageSize(int pageSize) {    this.pageSize = pageSize;  }   public int getTotalRows() {    return totalRows;  }   public void first() { //トップページ    currentPage = 1;    startRow = 0;  }   public void previous() { //前のページ    if (currentPage == 1) {      return;    }    currentPage--;    startRow = (currentPage - 1) * pageSize;  }   public void next() {  //次のページ    if (currentPage < totalPages) {      currentPage++;    }    startRow = (currentPage - 1) * pageSize;  }   public void last() { //末尾ページ    currentPage = totalPages;    startRow = (currentPage - 1) * pageSize;  }   public void refresh(int _currentPage) {    currentPage = _currentPage;    if (currentPage > totalPages) {      last();    }  }

Pagerクラスは、最初のページ、前のページ、次のページ、最後のページのデータベース内の開始行、現在のページ番号を計算するために使用されます.2.PagerHelpクラス
package com.jpcf.db.helper; import javax.servlet.http.*; public class PagerHelper {   public static Pager getPager(HttpServletRequest httpServletRequest,                               int totalRows) {    //ページに転送するpagerオブジェクトの定義    Pager pager = new Pager(totalRows);    //Requestオブジェクトから現在のページ番号を取得    String currentPage = httpServletRequest.getParameter("currentPage");    //現在のページ番号が空の場合は、最初のクエリーとして表示されます.   //空でない場合はpagerオブジェクトをリフレッシュし、現在のページ番号などの情報を入力します.    if (currentPage != null) {      pager.refresh(Integer.parseInt(currentPage));    }    //現在実行されているメソッド、トップページ、前ページ、後ページ、後ページを取得します.    String pagerMethod = httpServletRequest.getParameter("pageMethod");

PageHelperというクラスは、言うまでもなく何に使われているのか知っているはずです3.DAOクラス
package com.jpcf.db.dao; import com.jpcf.db.model.*;import com.jpcf.db.helper.HibernateUtil;import net.sf.hibernate.*;import java.util.*;import com.jpcf.db.controller.*; public class VehiclePropertyDAO {   public Collection findWithPage(int pageSize, int startRow) throws      HibernateException {    Collection vehicleList = null;    Transaction tx = null;    try {      Session session = HibernateUtil.currentSession();      tx = session.beginTransaction();      Query q = session.createQuery("from VehicleProperty vp");      q.setFirstResult(startRow);      q.setMaxResults(pageSize);      vehicleList = q.list();      tx.commit();    } catch (HibernateException he) {      if (tx != null) {        tx.rollback();      }      throw he;    } finally {      HibernateUtil.closeSession();    }    return vehicleList;  }   public int getRows(String query) throws      HibernateException {    int totalRows = 0;    Transaction tx = null;    try {      Session session = HibernateUtil.currentSession();      tx = session.beginTransaction();      totalRows = ((Integer) session.iterate(query).next()).                  intValue();      tx.commit();    } catch (HibernateException he) {      if (tx != null) {        tx.rollback();      }      throw he;    } finally {      HibernateUtil.closeSession();    }     return totalRows;  }

DAOクラス私はこれらのページングに必要なコードを貼ります.「from VehicleProperty vp」もパラメータで渡すことができます.興味のある人は自分で変更しましょう.4.Actionの下にActionで使うコードがあります./
 

    Collection clInfos = null;//用于输出到页面的记录集合

    int totalRows;//记录总行数

    VehiclePropertyDAO vehicleDAO = new VehiclePropertyDAO();

    //取得当前表中的总行数
    try {
      totalRows = vehicleDAO.getRows("select count(*) from VehicleProperty");
    } catch (Exception ex) {
      servlet.log(ex.toString());
      return actionMapping.findForward(Constants.FAILURE);
    }

    //通过PagerHelper类来获取用于输出到页面的pager对象
    Pager pager=PagerHelper.getPager(httpServletRequest,totalRows);

    //取出从startRow开始的pageSize行记录
    try {
      clInfos = vehicleDAO.findWithPage(pager.getPageSize(), pager.getStartRow());
    } catch (Exception ex) {
      servlet.log(ex.toString());
      return actionMapping.findForward(Constants.FAILURE);
    }

    //把输出的记录集和pager对象保存到request对象中
    httpServletRequest.setAttribute("CLINFOS", clInfos);
    httpServletRequest.setAttribute("PAGER", pager);


 
クエリ文select count(*)from VehiclePropertyは、必要な任意の条件(select count(*)from VehicleProperty where.)5.JSPページで次のように使用できます.

この行を説明します."/bussiness/clInfo/queryWithPage.do?method=queryWithPage&pageMethod=firstmethod=queryWithPageは私のActionが引き継いだDispatchActionのためです.methodパラメータpageMethod=firstが必要です.PageHelperクラスでどの操作を実行するかを判断するために使用されます.4、私がしたことをまとめるのも参考になります.まだ実現していないものがたくさんあります.例えばgoを追加して直接nページ目までの機能です.実は肝心なのは、現在のページ番号と実行する機能(前のページ、次のページ)のパラメータをページから転送し、Actionではこの2つのパラメータに基づいて次のページに表示されるレコードセットを取り出すことができます.