丄諦啲仇魜ヤ
          如 果 敵 人 讓 你 生 氣 , 那 說(shuō) 明 你 沒 有 勝 他 的 把 握!
          posts - 6,comments - 56,trackbacks - 1

            目的:

          學(xué)習(xí)使用struts+hibernate實(shí)現(xiàn)一個(gè)通用的分頁(yè)程序。

          內(nèi)容:

              分頁(yè)程序是網(wǎng)頁(yè)設(shè)計(jì)經(jīng)常需要實(shí)現(xiàn)的基本功能。但有的分頁(yè)程序直接嵌在jsp頁(yè)面上,不僅工作量較大,代碼也難以重用。本次試驗(yàn)將使用struts+hibernate來(lái)實(shí)現(xiàn)通用的分頁(yè)程序。不同功能的代碼盡量分離,以滿足通用性要求。

              首先需要建立一個(gè)表,如下Product,各字段設(shè)計(jì)如下(可自由更改):

              ID int primary key,

              Typeid varchar(20),

          Name   varchar(50),

          Price    varchar(20),

          Memo   varchar(100).

          步驟:

          建立web工程,名字為”Fenye”.

          2 添加hibernate,生成Product表的.hbm.xmlpojo類。這個(gè)很簡(jiǎn)單,不再贅述。

          3 接著寫數(shù)據(jù)訪問(wèn)層,我們將其分為DaoProDao兩個(gè)類。其中Dao是個(gè)公共的基類;ProDao繼承它,并與action通信取得參數(shù)。這樣設(shè)計(jì)的好處是:如果需要對(duì)User這個(gè)表進(jìn)行分頁(yè)顯示,只需添加一個(gè)UserDao類,并讓它繼承Dao類。

          Dao類的代碼如下,可以根據(jù)需要添加:頭文件自己導(dǎo)入。

          public class Dao {

                  private Session session=null;

                  public Dao() {

                     }

                    

                     public Session getSession()

                  {

                       session = HibernateSessionFactory.getSession();

                         return session;       

                  }

                    public int getCount(String pojo)

                  {

                       String sql="select count(*) from "+pojo ;

                       this.getSession();

                     try {

                     Query q = getSession().createQuery(sql);

                       List cc = q.list();

                       Integer rows = (Integer) cc.get(0);

                     return rows.intValue();

                     } catch (HibernateException ex) {

                         System.out.print("ex::"+ex.getMessage());

                         return 0;

                     }

                  }

                  public List getlist(Query query, String pojo,int pagesize,int currow) throws HibernateException

                 {

                       List list = null;

                       this.getSession();

                      query.setFirstResult(currow);

                       query.setMaxResults(pagesize);

                       list=query.list();

                       //session.flush();

                       if(session!=null)

                               session.close();     

                       return list;

                  }

                  public List getlist(Query query,int pagesize,int currow)

                        {                  

                                String[] str = query.getQueryString().split("from");       

                                String[] table =str[1].trim().split(" ");        

                                System.out.println("table:"+table[0]);

                                return getlist(query,table[0],pagesize,currow);         

                        }

          }

          ProDao類的代碼如下:

          public class PinfoDao extends Dao{

                 private Session session;

                 public PinfoDao() {

                        super();

              }

                 public List list(int pagesize,int currow)

                 {

                       

                        Query query =getSession().createQuery("from PInfo");

                        List li=getlist(query, pagesize, currow);

                        return li;

                       

                 }

                  public Session getSession()

                  {

                       // Configuration config=null;

                    

                       session = HibernateSessionFactory.getSession();

                         return session; 

                  }

                 public int getCount()

                 {

                        String sql="select count(*) from PInfo";

                        Query q = getSession().createQuery(sql);

                        List cc = q.list();

                        Integer a = (Integer) cc.get(0);    

                        System.out.println("count:"+a.intValue());

                        return a.intValue();

                 }    

          }

          4         下面寫頁(yè)面控制程序,同樣將代碼分離為兩個(gè)類Page類和Pagehelp類。

          Page類處理頁(yè)面相關(guān)的一些設(shè)置,如一頁(yè)顯示多少條記錄,計(jì)算共有多少頁(yè),共有多少記錄,當(dāng)前頁(yè)碼等。

          PageHelp類接收jsp頁(yè)面?zhèn)鱽?lái)的參數(shù),并調(diào)用Page類處理。

          Page類代碼:

          public class Page {

                  private int totalRows; //總行數(shù)

                     private int pageSize = 3; //每頁(yè)顯示的行數(shù)

                     private int currentPage; //當(dāng)前頁(yè)號(hào)

                     private int totalPages; //總頁(yè)數(shù)

                     private int startRow; //當(dāng)前頁(yè)在數(shù)據(jù)庫(kù)中的起始行

                     public Page(int totalRows1) {

                      totalRows = totalRows1;

                      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();

                      }

                    }

          }

          Pagehelp類代碼如下:

          public class Pagehelp {

                  public static Page getPager(HttpServletRequest httpServletRequest,int totalRows) {

                //定義pager對(duì)象,用于傳到頁(yè)面

                Page pager = new Page(totalRows);

                //Request對(duì)象中獲取當(dāng)前頁(yè)號(hào)

                String currentPage = httpServletRequest.getParameter("currentPage");

                //如果當(dāng)前頁(yè)號(hào)為空,表示為首次查詢?cè)擁?yè)

                //如果不為空,則刷新page對(duì)象,輸入當(dāng)前頁(yè)號(hào)等信息

                if (currentPage != null) {

                  pager.refresh(Integer.parseInt(currentPage));

                }

                //獲取當(dāng)前執(zhí)行的方法,首頁(yè),前一頁(yè),后一頁(yè),尾頁(yè)。

                String pagerMethod = httpServletRequest.getParameter("pageMethod");

                if (pagerMethod != null) {

                  if (pagerMethod.equals("first")) {

                    pager.first();

                  } else if (pagerMethod.equals("previous")) {

                    pager.previous();

                  } else if (pagerMethod.equals("next")) {

                    pager.next();

                  } else if (pagerMethod.equals("last")) {

                    pager.last();

                  }

                }

                return pager;

              }

          }

          5         一切準(zhǔn)備工作結(jié)束后,下面寫action來(lái)調(diào)用這些類。

          List list = null;//用于輸出到頁(yè)面的記錄集合

                         int totalRows;//記錄總行數(shù)

                         PinfoDao dao=new PinfoDao();

                         totalRows=dao.getCount();

                         System.out.print("總行數(shù)=="+totalRows);

                         Page page=Pagehelp.getPager(request,totalRows);

                         try {

                                list= dao.list(page.getPageSize(), page.getStartRow());

                         } catch (HibernateException ex) {

                             System.out.print("action里的錯(cuò)誤="+ex.getMessage());

                         }

                         request.setAttribute("page",page);

                         request.setAttribute("list",list);

                         return mapping.findForward("list");

          6         最后是顯示頁(yè)面plist。在struts-config.xml文件中添加forward語(yǔ)句,<forward name="list" path="/plist.jsp"></forward>。

          plist.jsp頁(yè)面部分代碼如下:

          <table align="center" border="1">

             <tr>

             <td>產(chǎn)品類別</td>

             <td>產(chǎn)品名稱</td>

             <td>產(chǎn)品價(jià)格</td>

             <td>產(chǎn)品備注</td>

             </tr>

          <!—下面打印list中的各屬性-->

                 <tr >

             <td colspan="4">

          <bean:write name="page" property="currentPage"/>頁(yè)

          <bean:write name="page" property="totalPages" />頁(yè)

          <html:link action="/page.do?pageMethod=first"

          paramName="page" paramProperty="currentPage"

          paramId="currentPage">首頁(yè)</html:link>

             <html:link action="/page.do?pageMethod=previous"

          paramName="page" paramProperty="currentPage"

          paramId="currentPage">上一頁(yè)</html:link>

             <html:link action="/page.do?pageMethod=next"

          paramName="page" paramProperty="currentPage"

          paramId="currentPage">下一頁(yè)</html:link>

             <html:link action="/page.do?pageMethod=last"

          paramName="page" paramProperty="currentPage"

          paramId="currentPage">尾頁(yè)</html:link>

          </td>

          </tr>        

          </table>

          7 測(cè)試:

          按照上述步驟完成后,在瀏覽器中輸入http://localhost:8080/Fenye/page.do查看頁(yè)面。

          posted on 2007-09-22 13:53 Crying 閱讀(1706) 評(píng)論(5)  編輯  收藏 所屬分類: 分頁(yè)

          FeedBack:
          # re: hibernate分頁(yè)1
          2008-10-15 16:26 | 456
          我用你的分面在PreDao類的 List li=getlist(query, pagesize, currow);
          報(bào)錯(cuò)。找不到方法。請(qǐng)問(wèn)怎么樣解決?  回復(fù)  更多評(píng)論
            
          # re: hibernate分頁(yè)1[未登錄]
          2008-10-19 11:21 | Crying
          @456
          在DAO類中啊  回復(fù)  更多評(píng)論
            
          # re: hibernate分頁(yè)1
          2008-10-20 15:09 | 456
          你好,上次是我沒有搞清楚,不好意思 。 但這次是真的報(bào)了個(gè)錯(cuò)。
          Integer a = (Integer) cc.get(0); 類型轉(zhuǎn)化不了。  回復(fù)  更多評(píng)論
            
          # re: hibernate分頁(yè)1
          2009-01-16 16:09 | Luck_Li
          不錯(cuò)的資源,實(shí)現(xiàn)了,很感謝wangsq,針對(duì)上面提出 的類型轉(zhuǎn)換可以改一下,我是這樣實(shí)現(xiàn)的:Integer rows = Integer.parseInt(cc.get(0).toString());

          希望可以幫到忙。  回復(fù)  更多評(píng)論
            
          # re: hibernate分頁(yè)1
          2012-12-14 18:41 | 婉兒
          對(duì)不上號(hào)啊,你的項(xiàng)目不全,我也出現(xiàn)以上錯(cuò)誤!!  回復(fù)  更多評(píng)論
            

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
          相關(guān)文章:
           
          主站蜘蛛池模板: 平和县| 博爱县| 祁门县| 卢氏县| 贵港市| 原阳县| 连云港市| 昌都县| 霞浦县| 隆子县| 婺源县| 宜章县| 北京市| 津南区| 安泽县| 台南县| 宣武区| 温泉县| 合川市| 广饶县| 邯郸市| 马关县| 潢川县| 乌拉特后旗| 渝北区| 东海县| 维西| 渝中区| 自贡市| 建昌县| 洛扎县| 建宁县| 独山县| 香河县| 长寿区| 松潘县| 滦平县| 隆化县| 江阴市| 阳春市| 平塘县|