在网上看到不少提供web翻页技术的指导,不过,感觉参考价值不大,所以我总结一下别人的经验,重写一次.
大部分网站架构都是基于mvc,通常jsp作为显示层,或者用模板技术作为显示层,在此层将会显示查询记录总数,以及当前页,还有页面导航,以及显示改页的记录(model),.servlet通常作为控制层,用于收集查询条件,调用业务bean,,完成翻页查询,并将结果返回到显示层.对于分页来说,每层次的主要任务如下:
显示层:
取出记录总数,并显示出来;
指示当前在第几页
显示翻页导航条,如象google那样的翻页,或者象yahoo那样的翻页风格
取出记录集,并显示出来,通常,一页显示10-30条,并且,这是可以配置的
控制层:
查询的时候,将用户输入的查询条将,通常表现形式是queryvalue放入会话中,以便下次翻页的时候重新取出查询条件
如果是第一次查询,调用业务bean,需要查询记录总数,并查询出第一页的结果集,并传到显示层
如果是其后后的翻页,则需要调用业务bean查询指定范围内的结果集,并传到显示层
业务bean:
业务bean提供按照queryvalue查询出合乎条件总数
业务bean提供按照queryvalue,以及 范围(startindex,endindex)查询合乎条件的结果集
现在举个例子,分别从业务bean,控制层,显示层的具体实现来完成分页,我希望这个例子能被复制使用
业务bean:
public class businuessfacade
{
...........
public int querybooksize(bookqueryvalue qv) throws ....
{
}
public bookvalueobject querybooks(bookqueryvalue qv,int startindex,int endindex) throws....
{
}
}
public class bookqueryvalue
{
public string name;
public string isbn
............
}
控制层,用serlvet举例
public class bookqueryservelt
{
doget(httpservletrequest request, httpservletresponse response....
{
string offset = request.getparameter("pager.offset");
int startindex = 0;
int endindex=0;
bookqueryvalue qv = null;
httpsession session = request.getsession();
if(offset==null)
{
//第一次查询,需要查出记录总数
qv = createqueryvalue(request);
int size = facade.querybooksize(qv);
session.setattribute("resultsize",new integer(size));
session.setattribyte("queryvalue",qv);
startindex = 1;
endindex = consts.max_page_items;
if(endindex > size) endindex = size;
}
else
{
startindex = (new integer(offset)).intvalue() + 1;
int size = ((integer) session.getattribute("resultsize")).intvalue();
endindex = startindex + consts.max_page_items;
if(endindex > size) endindex = size;
qv = (bookqueryvalue)session.getattribute("queryvalue");
}
bookvalueobject[] vos = facade.querybooks(qv,startindex,endindex);
request.setattribute("result",vos);
gotoqueryresultpage(request);
}
}
显示层:上面俩层已经把数据准备好了,现在用pager tag(http://jsptags.com/tags/navigation/pager/download.jsp)来帮助完成分页的显示
<%
//初始化
string contextpath = request.getcontextpath();
int size = ((integer)session.getattribute("resultsize")).intvalue();
string actionpath = contextpath+"/bookqueryservlet";
%>
<pg:pager items="<%=size%>"
maxpageitems="<%=consts.max_page_items%>" //每页显示多少条记录
maxindexpages="<%=consts.max_index_page%>" //翻页导航条显示多少个页面
isoffset="<%= true %>"
url="<%= actionpath %>" //翻页时调用的servelt
export="offset,currentpagenumber=pagenumber"
scope="request"
>
<logic:iterate id="vo" name="result" type="org.simple.bookvalueobject" scope="request">
<tr>
<td align="center"><%=vo.name%></td>
<td align="center"><%=vo.isbn%></td>
</tr>
</logic:iterate>
<tr>
<td colspan="5"><div align="center">
<jsp:include page="/common/yahoopagestyle.jsp" flush="true"/></div></td>
<!-- 导航条 -->
</tr>
<tr>
<td colspan="5"></td>
</tr>
</pg:pager>
显示层用到struts的标记库,以及pager tag技术,你需要对此了解,也推荐你了解这些技术
闽公网安备 35060202000074号