牛掰分页心得--编写通用分页类

1.通用类编写的案例

   采用泛型编写的分页类,达到想使哪个数据库中的表分页就传入哪个表对应的javabean实体这种通用的思想。分页的全部过程和判断全部封装在该类中,在action或servlet直接调用分页类即可达到分页效果。

文章来自:点击打开链接

Action中调用代码只需一行,当然要封装该类实体的属性,并生成相应的set和get方法:

pagination =new Pagination<Admin>(Admin.class,pagination.getNowPage());

package www.csdn.utils;

 

importjava.util.ArrayList;

importjava.util.List;

 

/***

 *

 *@author 杨凯

 *

 *        通用分页工具类

 */

public class Pagination<T> extendsBaseHibernateDao {

 

       //每页显示的记录数

       privatestatic final int PAGESIZE = 5;

       //总页数

       privateInteger countPage;

       //当前页

       privateInteger nowPage;

       //总记录数

       privateInteger countRecond;

       //当前页数据

       privateList<T> entities;

 

       /**

        * 默认构造器用来实例化改类的私有化变量,必有构造器,不写会报错

        */

       publicPagination() {

       }

 

       /**

        * 传参构造器用来对外提供该分页类封装的分页方法

        */

       publicPagination(Class<T> className, int nowPage) {

              this.countRecond= getCountRecord(className);

              this.countPage= this.countRecond % PAGESIZE == 0 ? this.countRecond

                            /PAGESIZE : this.countRecond / PAGESIZE + 1;

              //对当前页的处理

              if(nowPage <= 1) {

                     this.nowPage= 1;

              }else {

                     if(nowPage >= this.countPage) {

                            this.nowPage= this.countPage;

                     }else {

                            this.nowPage= nowPage;

                     }

              }

              //这里传过去的值一定要是全局的nowPage不能是参数nowPage,否则下一页的判读就不起作用了

              this.entities= getNowPageInfor(this.nowPage, className);

       }

 

       publicvoid setCountPage(Integer countPage) {

              this.countPage= countPage;

       }

 

       publicvoid setNowPage(Integer nowPage) {

              this.nowPage= nowPage;

       }

 

       publicvoid setCountRecond(Integer countRecond) {

              this.countRecond= countRecond;

       }

 

       publicvoid setEntities(List<T> entities) {

              this.entities= entities;

       }

 

       publicInteger getCountPage() {

              returncountPage;

       }

 

       publicInteger getNowPage() {

              returnnowPage;

       }

 

       publicInteger getCountRecond() {

              returncountRecond;

       }

 

       publicList<T> getEntities() {

              returnentities;

       }

 

       /**

        * 从数据库获取总记录数的方法

        *

        * @param className

        * @return 方法说明:不直接放回值,通过先声明一个变量的方式,测试出错的时候不会再出现空指针异常;

        *        query的uniqueResult()方法返回一个long类型的值,所以这里要强转成Integer型的;

        *        这里巧妙的借助toString()方法来完成强转要求,这个方法只适合用记录较少的情况;

        *        记录数庞大的时候可以直接将上面分页用到的变量都声明成long型的

        */

 

       publicInteger getCountRecord(Class<T> className) {

              inti = 0;

              try{

                     //千万记住引号内聚合函数的书写,from后跟var前都有空格,没有会出错;这里var是随意起的变量临时名

                     i= Integer.parseInt(this

                                   .getSession()

                                   .createQuery(

                                                 "selectcount(var) from " + className.getName()

                                                               +" var").uniqueResult().toString());

                     i= Integer.parseInt(this

                                   .getSession()

                                   .createQuery(

                                                 "selectcount(var) from " + className.getName()

                                                               +" var").uniqueResult().toString());

              }catch (Exception e) {

                     thrownew RuntimeException(e);

              }finally {

                     HibernateSessionFactory.closeSession();

              }

              returni;

       }

 

       /**

        *

        * 分页方法

        *

        * @param nowPage

        * @param className

        * @return

        */

       @SuppressWarnings("unchecked")

       publicList<T> getNowPageInfor(Integer nowPage, Class<T> className) {

              List<T> entities = newArrayList<T>();

              try {

                     entities= this.getSession().createCriteria(className)

                                   .setFirstResult((nowPage- 1) * PAGESIZE)

                                   .setMaxResults(PAGESIZE).list();

              }catch (Exception e) {

                     thrownew RuntimeException(e);

              }finally {

                     HibernateSessionFactory.closeSession();

              }

              returnentities;

       }

}

 

2.struts2标签编写的分页实现界面

<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%>

<%@taglib uri="/struts-tags"prefix="s"%>

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>index</title>

 

</head>

 

<body>

   <div align="center">

      <h3>显示所有用户的信息</h3>

      <table border="1px"cellpadding="0"cellspacing="0">

         <thead>

           <tralign="center"bgcolor="#FAFAF1"height="24">

               <th width="7%">选择</th>

               <th width="7%">ID</th>

               <th width="20%">用户名</th>

               <th width="20%">密码</th>

               <th width="40%">操作</th>

           </tr>

         </thead>

 

         <tbody>

           <s:iterator var="entity" value="pagination.entities">

               <tr>

                  <td><s:checkboxname="ids"theme="simple"/></td>

                  <td><s:propertyvalue="#entity.adminId"/></td>

                  <td><s:propertyvalue="#entity.adminName"/></td>

                  <td><s:propertyvalue="#entity.adminPassword"/></td>

 

                  <td><s:ahref="../save.jsp">添加用户</s:a>|<s:url id="idQuery"

                        namespace="/csdn"action="adminAction_adminFind">

                        <s:param name="id">

                           <s:property value="#entity.adminId"/>

                        </s:param>

                     </s:url><s:a href="%{idQuery}">根据id查询</s:a>|<s:url id="idDelete"

                        namespace="/csdn"action="adminAction_adminDelete">

                        <s:param name="id">

                           <s:property value="#entity.adminId"/>

                        </s:param>

                     </s:url><s:a href="%{idDelete}">删除用户</s:a></td>

               </tr>

           </s:iterator>

         </tbody>

      </table>

 

      <!-- struts2分页标签 -->

      <div>

         <!-- 首页 -->

         <s:url action="adminAction_adminTagList"namespace="/csdn"

           id="firstPage">

           <s:param name="pagination.nowPage">1</s:param>

         </s:url>

         <s:a href="%{firstPage}">首页</s:a>

         <!-- 上一页 -->

         <s:url action="adminAction_adminTagList"namespace="/csdn"

           id="backPage">

           <s:param name="pagination.nowPage">

               <s:property value="pagination.nowPage-1" />

           </s:param>

         </s:url>

         <s:a href="%{backPage}">上一页</s:a>

        

         <!-- 下一页 -->

         <s:url action="adminAction_adminTagList"namespace="/csdn"id="nextPage">

               <s:param name="pagination.nowPage">

                  <s:property value="pagination.nowPage+1" />

               </s:param>

           </s:url>

           <s:a href="%{nextPage}">下一页</s:a>

           

         <!-- 末页 -->

         <s:url action="adminAction_adminTagList"namespace="/csdn"

           id="lastPage">

           <s:param name="pagination.nowPage">

               <s:property value="pagination.countPage" />

           </s:param>

         </s:url>

         <s:a href="%{lastPage}">末页</s:a>

 

         <span><s:propertyvalue="pagination.countRecond"/>记录,共 <s:property

               value="pagination.countPage"/>页.</span>

      </div>

   </div>

</body>

</html>

 

 

注意:

在Action中  我们通过get方法传递过来的属性值:

可以直接在界面总: 直接获取 ,或可以你采用#request.获取,只有这两种方法,其他额获取不到get方法传过来的值

 在struts2标签中可以进行简单的表达式运算。比如:<s:propertyvalue="pagination.nowPage-1"/>

 

1.通用类编写的案例

   采用泛型编写的分页类,达到想使哪个数据库中的表分页就传入哪个表对应的javabean实体这种通用的思想。分页的全部过程和判断全部封装在该类中,在action或servlet直接调用分页类即可达到分页效果。

Action中调用代码只需一行,当然要封装该类实体的属性,并生成相应的set和get方法:

pagination =new Pagination<Admin>(Admin.class,pagination.getNowPage());

package www.csdn.utils;

 

importjava.util.ArrayList;

importjava.util.List;

 

/***

 *

 *@author 杨凯

 *

 *        通用分页工具类

 */

public class Pagination<T> extendsBaseHibernateDao {

 

       //每页显示的记录数

       privatestatic final int PAGESIZE = 5;

       //总页数

       privateInteger countPage;

       //当前页

       privateInteger nowPage;

       //总记录数

       privateInteger countRecond;

       //当前页数据

       privateList<T> entities;

 

       /**

        * 默认构造器用来实例化改类的私有化变量,必有构造器,不写会报错

        */

       publicPagination() {

       }

 

       /**

        * 传参构造器用来对外提供该分页类封装的分页方法

        */

       publicPagination(Class<T> className, int nowPage) {

              this.countRecond= getCountRecord(className);

              this.countPage= this.countRecond % PAGESIZE == 0 ? this.countRecond

                            /PAGESIZE : this.countRecond / PAGESIZE + 1;

              //对当前页的处理

              if(nowPage <= 1) {

                     this.nowPage= 1;

              }else {

                     if(nowPage >= this.countPage) {

                            this.nowPage= this.countPage;

                     }else {

                            this.nowPage= nowPage;

                     }

              }

              //这里传过去的值一定要是全局的nowPage不能是参数nowPage,否则下一页的判读就不起作用了

              this.entities= getNowPageInfor(this.nowPage, className);

       }

 

       publicvoid setCountPage(Integer countPage) {

              this.countPage= countPage;

       }

 

       publicvoid setNowPage(Integer nowPage) {

              this.nowPage= nowPage;

       }

 

       publicvoid setCountRecond(Integer countRecond) {

              this.countRecond= countRecond;

       }

 

       publicvoid setEntities(List<T> entities) {

              this.entities= entities;

       }

 

       publicInteger getCountPage() {

              returncountPage;

       }

 

       publicInteger getNowPage() {

              returnnowPage;

       }

 

       publicInteger getCountRecond() {

              returncountRecond;

       }

 

       publicList<T> getEntities() {

              returnentities;

       }

 

       /**

        * 从数据库获取总记录数的方法

        *

        * @param className

        * @return 方法说明:不直接放回值,通过先声明一个变量的方式,测试出错的时候不会再出现空指针异常;

        *        query的uniqueResult()方法返回一个long类型的值,所以这里要强转成Integer型的;

        *        这里巧妙的借助toString()方法来完成强转要求,这个方法只适合用记录较少的情况;

        *        记录数庞大的时候可以直接将上面分页用到的变量都声明成long型的

        */

 

       publicInteger getCountRecord(Class<T> className) {

              inti = 0;

              try{

                     //千万记住引号内聚合函数的书写,from后跟var前都有空格,没有会出错;这里var是随意起的变量临时名

                     i= Integer.parseInt(this

                                   .getSession()

                                   .createQuery(

                                                 "selectcount(var) from " + className.getName()

                                                               +" var").uniqueResult().toString());

                     i= Integer.parseInt(this

                                   .getSession()

                                   .createQuery(

                                                 "selectcount(var) from " + className.getName()

                                                               +" var").uniqueResult().toString());

              }catch (Exception e) {

                     thrownew RuntimeException(e);

              }finally {

                     HibernateSessionFactory.closeSession();

              }

              returni;

       }

 

       /**

        *

        * 分页方法

        *

        * @param nowPage

        * @param className

        * @return

        */

       @SuppressWarnings("unchecked")

       publicList<T> getNowPageInfor(Integer nowPage, Class<T> className) {

              List<T> entities = newArrayList<T>();

              try {

                     entities= this.getSession().createCriteria(className)

                                   .setFirstResult((nowPage- 1) * PAGESIZE)

                                   .setMaxResults(PAGESIZE).list();

              }catch (Exception e) {

                     thrownew RuntimeException(e);

              }finally {

                     HibernateSessionFactory.closeSession();

              }

              returnentities;

       }

}

 

2.struts2标签编写的分页实现界面

<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%>

<%@taglib uri="/struts-tags"prefix="s"%>

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>index</title>

 

</head>

 

<body>

   <div align="center">

      <h3>显示所有用户的信息</h3>

      <table border="1px"cellpadding="0"cellspacing="0">

         <thead>

           <tralign="center"bgcolor="#FAFAF1"height="24">

               <th width="7%">选择</th>

               <th width="7%">ID</th>

               <th width="20%">用户名</th>

               <th width="20%">密码</th>

               <th width="40%">操作</th>

           </tr>

         </thead>

 

         <tbody>

           <s:iterator var="entity" value="pagination.entities">

               <tr>

                  <td><s:checkboxname="ids"theme="simple"/></td>

                  <td><s:propertyvalue="#entity.adminId"/></td>

                  <td><s:propertyvalue="#entity.adminName"/></td>

                  <td><s:propertyvalue="#entity.adminPassword"/></td>

 

                  <td><s:ahref="../save.jsp">添加用户</s:a>|<s:url id="idQuery"

                        namespace="/csdn"action="adminAction_adminFind">

                        <s:param name="id">

                           <s:property value="#entity.adminId"/>

                        </s:param>

                     </s:url><s:a href="%{idQuery}">根据id查询</s:a>|<s:url id="idDelete"

                        namespace="/csdn"action="adminAction_adminDelete">

                        <s:param name="id">

                           <s:property value="#entity.adminId"/>

                        </s:param>

                     </s:url><s:a href="%{idDelete}">删除用户</s:a></td>

               </tr>

           </s:iterator>

         </tbody>

      </table>

 

      <!-- struts2分页标签 -->

      <div>

         <!-- 首页 -->

         <s:url action="adminAction_adminTagList"namespace="/csdn"

           id="firstPage">

           <s:param name="pagination.nowPage">1</s:param>

         </s:url>

         <s:a href="%{firstPage}">首页</s:a>

         <!-- 上一页 -->

         <s:url action="adminAction_adminTagList"namespace="/csdn"

           id="backPage">

           <s:param name="pagination.nowPage">

               <s:property value="pagination.nowPage-1" />

           </s:param>

         </s:url>

         <s:a href="%{backPage}">上一页</s:a>

        

         <!-- 下一页 -->

         <s:url action="adminAction_adminTagList"namespace="/csdn"id="nextPage">

               <s:param name="pagination.nowPage">

                  <s:property value="pagination.nowPage+1" />

               </s:param>

           </s:url>

           <s:a href="%{nextPage}">下一页</s:a>

           

         <!-- 末页 -->

         <s:url action="adminAction_adminTagList"namespace="/csdn"

           id="lastPage">

           <s:param name="pagination.nowPage">

               <s:property value="pagination.countPage" />

           </s:param>

         </s:url>

         <s:a href="%{lastPage}">末页</s:a>

 

         <span><s:propertyvalue="pagination.countRecond"/>记录,共 <s:property

               value="pagination.countPage"/>页.</span>

      </div>

   </div>

</body>

</html>

 

 

注意:

在Action中  我们通过get方法传递过来的属性值:

可以直接在界面总: 直接获取 ,或可以你采用#request.获取,只有这两种方法,其他额获取不到get方法传过来的值

 在struts2标签中可以进行简单的表达式运算。比如:<s:propertyvalue="pagination.nowPage-1"/>

  如需转载,请指明出处:http://www.csdn.net/tianyazaiheruan,尊重别人的知识产权和劳动成果

 

posted @ 2013-03-08 13:47  yangkai_keven  阅读(415)  评论(0编辑  收藏  举报