你的位置:首页 > Java教程

[Java教程]Java Web 开发中如何进行分页


*分页:

    摘要:所用框架为:Hibernate+Spring+Struts2,以分页显示后台用户列表为例

    1.设计实体:页面类PageBean

        1.1 分析:

            当前页:currentPage(请求数据)

            总记录数:recordCount(查数据库:count(*))

            页面大小:pageSize(配置文件设置值)

            本页的数据列表:recordList(查询数据库:select *)

 

            总页数:pageCount(计算)=(recordCount+pageSize-1)/pageSize;

            开始索引:beginPageIndex(计算)

            结束索引:endPageIndex(计算)

        1.2 代码,这里以显示10个页码索引为例:

            public class PageBean{

 

                private int currentPage;

                private int recordCount;

                private int pageSize;

                private List recordList;

 

                private int pageCount;

                private int beginPageIndex;

                private int endPageIndex;

 

                public PageBean(int currentPage,int recordCount,int pageSize,int recordList){

                    //当前页

                    this.currentPage=currentPage;

                    //总记录数

                    this.recordCount=recordCount;

                    //页面大小

                    this.pageSize=pageSize;

                    //当前页的总记录列表

                    this.recordList=recordList;

 

                    //计算pageCount:总记录数

                    //这里可以用逻辑判断,如:

                    /*

                    *if(recordCount%pageSize==0){

                    *    pageCount=recordCount/pageSize;    

                    *}else{

                    *    pageCount=recordCount/pageSize+1;

                    *}

                    */

                    //或则用算法,自己琢磨

                    pageCount=(recordCount+pageSize-1)/pageSize;

                    

                    //这里以显示十个页码索引为例,设置开始页码索引和结束页码索引

                    //当页面总数小于10个时

                    if(pageCount<=10){

                        beginPageIndex=1;

                        endPageIndex=pageCount;

                    }else{

                        //当页面总素大于10个时

                        beginPageIndex=currentPage-4;

                        endPageIndex=currentPage+5;

 

                        if(beginPageIndex<1){

                            beginPageIndex=1;

                            endPageIndex=10;

                        }

                        else if(endPageIndex>pageCount){

                            beginPageIndex=pageCount-9;

                            endPageIndex=pageCount;

                        }

                    }

                }

                

                //Setter和Getter

                set...

                get...

            }

    2.设置实体工具类:HqlHelper

        2.1 分析

        2.2 代码

            public class HqlHelper{

                //from子句

                private String fromClause;

                //where子句

                private String whereClause;

                //排序子句

                private String orderClause;

                

                //参数集合,Hql语句中where子句中用到的参数对象

                private List<Object> parameters=new ArrayList<Object>();

                

                //构造函数设置fromClause,默认别名为"o"

                public HqlHelper(Class clazz){

                    this.fromClause="FROM "+clazz.getSimpleName+" o";

                }

                //自定义别名

                public HqlHelper(Class clazz,String alias){

                    this.fromClause="FROM "+clazz.getSimpleName+alias;

                }

                

                //设置where子句的,以及用到的参数对象,这就是查询条件

                public HqlHelper addCondition(String condition,Object... params){

                    if(whereClause.length()==0){

                        whereClause=" WHERE "+condition;

                    }else{

                        where+=" AND "+condition;

                    }

                    

                    if(params!=null && params.length>0){

                        for(Object o:params){

                            parameters.add(0);

                        }

                    }

                    return this;

                }

                //设置是否追加,这个接口留给用户,到时方便用户开发

                public HqlHelper addCondition(boolean append,String condition,Object... params){

                    if(append){

                        addCondition(condition,params);

                    }

                    return this;

                    

                }

                

                //设置排序条件子句

                public HqlHelper addOrder(String propertityName,boolean isAsc){

                    if(orderClause!=null && orderClause.length()>0){

                        orderClause=" ORDER BY "+propertityName+(isAsc?" ASC":" DESC");

                    }else{

                        orderClause+=", "+popertityName+(isAsc?" ASC":" DESC");

                    }

                    

                    return this;

                }

                //这个增加了是否追加排序条件子句

                public HqlHelper addOrder(boolean append ,String propertityName,boolean isAsc){

                    if(append){

                        addOrder(propertityName,isAsc);

                    }

                    return this;

                }

                

                //得到查询子句hql

                public String getQueryListHql(){

                    return fromClause+whereClause+orderClause;

                }

 

                //计数hql

                public String getCountHql(){

                    return "SELECT COUNT(*) "+fromClause+whereClause;

                }

                

                //参数集合get接口,供外部访问

                public List<Object> getParameters(){

                    return parameters;

                }

                

//这里只要两个参数,跳转的页面,和继承了BaseDao(自己抽取的接口,//很有用的)的service

                public HqlHelper buildPageBeanForStruts2(int pageNum,BaseDao<?> service){

                    

                    PageBean pageBean=service.getBean(pageNum,this);

                    ActionContext.getContext.getValueStack.push(pageBean);

                    return this;

                }

            }

    3.设计service,这里把方法放到BaseDao中,service继承即可:

        3.1 代码

            //事物注解(许在Spring中配置,TransactionManager)

            @Transactional

            public class BaseDaoImpl<T> implements BaseDao<T>{

                //这里需要配置SessionFactory在Spring容器中,自己配不难

                //这个是注解,相当于Setter

                @Resource

                private SessionFactory sessionFactory;

                //实体类型

                protected Class<T> clazz;

 

                //在构造函数中进行初始化clazz

                public BaseDaoImpl(){

                    ParameterirzedType pt=(ParameterizedType)this.getClass().getGenericSuperclass();

                    this.clazz=(Class)pt.getActualTypeArguments()[0];

                }

                

                //获取Session,方便操作数据库

                protected Session getSession(){

                    return sessionFactory.getCurrentSession();

                }

 

                public PageBean getBean(int pageNum,HqlHelper hqlHelper){

                    

                    //参数集合

                    private List<Object> parameters=hqlHelper.getParameters();

                    //配置的页面大小

                    private int pageSize=Configuration.getPageSize();

                    

                    //recordCount,总记录数

                    Query countQuery=getSession().createQuery(HqlHelper.getCountHql());

                    if(parameters!=null && parameters.size()>0){

                        for(int i=0;i<parameters.size();i++){

                            countQuery.setParameter(i,parameters.get(i));

                        }    

                    }                    

                    Long recordCount=(Long)countQuery.uniqueResult();

 

                    //recordList,当前页的记录列表

                    Query listQuery=getSession().createQuery(HqlHelper.getQueryListHql());

                    //设置查询参数

                    if(parameters!=null && parameters.size()>0){

                        for(int i=0;i<parameters.size;i++){

                            listQuery.setParameter(i,parameters.get(i));

                        }

                    }

                    //获取当前页的记录

                    listQuery.setFirstResutl(pageSize*(pageNum-1));

                    listQuery.setMaxResults(pageSize);

                    List recordList=listQuery.list();

                    

                    return new PageBean(pageNum,recordCount.intValue(),pageSize,recordList);

                }

            }

 

    4.设计Action:以UserAction为例

        4.1 代码:

            //顺带把配置加上,交给Spring容器管理

            @Controller

            @Scope("prototype")

            public class UserAction extends ActionSupport{

                

                private int pageNum;

                get... set...;

 

                @Resource

                private UserService userService;

 

                //用户数据列表,分页显示

                public String list(){

                    new HqlHelper(User.class,"u")//

                    .buildPageBeanForStruts2(pageNum,userService);

                }

            }

 

    5.页面:设计一个公共页面 pageView.jspf,通用的

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

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

 

<div id=PageSelectorBar>

    <div id=PageSelectorMemo>

        页次:${currentPage}/${pageCount}页 &nbsp; 每页显示:${pageSize}条 &nbsp; 总记录数:${recordCount}条

    </div>

    <div id=PageSelectorSelectorArea>

        

        <a href="javascript:gotoPage(1)" title="首页" style="cursor: hand;"> <img src="${pageContext.request.contextPath}/style/blue/images/pageSelector/firstPage.png" /> </a>

 

        <s:iterator begin="%{beginPageIndex}" end="%{endPageIndex}" var="num">

            <s:if test="currentPage==#num">

                <%--当前页 --%>

                <span class="PageSelectorNum PageSelectorSelected">${num}</span>

            </s:if>

            <s:else>

                <%--非当前页 --%>

                <span class="PageSelectorNum" style="cursor: hand;" onClick="gotoPage(${num});">${num}</span>

            </s:else>

        </s:iterator>

        <a href="javascript:gotoPage(${pageCount})" title="尾页" style="cursor: hand;"> <img

                src="${pageContext.request.contextPath}/style/blue/images/pageSelector/lastPage.png" /> </a> 转到:

        <select id="pn" onchange="gotoPage(this.value)">

            <s:iterator begin="1" end="%{pageCount}" var="num">

                <option value="${num}">

                    ${num}

                </option>

            </s:iterator>

        </select>

        <script type="text/javascript">

            //回显页码

            $("#pn").val(${currentPage});

        </script>

    </div>

</div>

 

 

<script type="text/javascript">

    function gotoPage(pageNum){

            //window.location.href="topicAction_show.action?id=${id}&pageNum="+pageNum;

            $(document.forms[0]).append("<input type='hidden' name='pageNum' value='"+pageNum+"'/>");

            document.forms[0].submit();//提交表单    

        }

</script>