这里构建一个最简单的分页实现,也就是说通过查询结果的列表来构建页对象,这种情况是存在的:比如本次要显示的结果不是直接从数据库查询得到的,而是通过过滤某次数据库查询得到的,总之就是一个包含所有数据的结果集合。
不知道有没有说清楚,这里直接给出一个参考实现: package treeroot.util; import java.util.List;
/** * @author treerot * @version 1.0 * @since 2004-9-30 */ public class ListPage extends AbstractPage implements Pageable { private List list;
/** * 通过一个结果列表来初始化 * @param list * @throws PageException */ public ListPage(List list) throws PageException { this(list, 1, Pageable.DEFAULT_PAGESIZE); } /** * 通过一个结果列表来初始化,指定当前页 * @param list * @param currentPage * @throws PageException */ public ListPage(List list, int currentPage) throws PageException { this(list, currentPage, Pageable.DEFAULT_PAGESIZE); } /** * 通过一个结果列表来初始化,指定当前页和页大小 * @param list * @param currentPage * @param pageSize * @throws PageException */ public ListPage(List list, int currentPage, int pageSize) throws PageException { super(currentPage, pageSize); //这里为了达到fail-fast,直接抛出异常,不是必须的。 if(list==null) throw new NullPointerException(); this.list = list; init(); }
protected void init() throws PageException { this.count = list.size(); checkPage(this.getCurrentPage()); int fromIndex = (this.getCurrentPage() - 1) * this.getPageSize(); int toIndex = Math.min(fromIndex + this.getPageSize(), this.count); this.result = list.subList(fromIndex, toIndex); }
}
是不是觉得很简单,看一下怎么应用吧,假如你有一个方法就是获得查询结果,那么你就可以这样用了。
在Servlet或者Action中: int currentPage=1; String str=request.getParameter("currentPage"); if(str!=null){ try{ currentPage=Integer.parseInt(str); } catch(NumberFormatException e){} }
List list= .... //这里获得所有结果,可能是直接获得数据库查询结果,也可能经过处理。 Pageable pg =null; try{ pg= new ListPage(list,currentPage); //或者通过Dao pg=(new Dao()).getResutl(currentPage); 返回类型为Pageable } catch(PageException e) { pg=null; } request.setAttribute("page",pg); //转发给一个JSP页面显示。
是不是觉得很简洁?当然这里没有给出具体的的数据获取方法,但是在JSP显示页面就会觉得很舒服了,这里简单写一个JSP。 <% Pageable pg=(Pageable)request.getAttribute("page"); %> <table> <tr> <th>学号</th> <th>姓名</th> </tr> <% if(pg!=null){ List list=pg.getResult(); for(int i=0;i<list.size();i++){ Student stu=(Student)list.get(i); %> <tr> <td><%=stu.getNumber()%></td> <td><%=stu.getName()%></td> </tr> <% } %>
<tr> <td colspan="2"> 总纪录:<%=pg.getCount()%> 每页显示:<%=pg.getPageSize()%>   页次:<%=pg.getCurrentPage%>/<%=pg.getPages()%> <a href="#" onClick="gotoPage(<%=currentPage-1%>)">上一页</a> <a href="#" onClick="gotoPage(<%=currentPage+1%>)">上一页</a> </td> </tr>
<% } else{ %> <tr> <td colspan="2">指定的页不存在</td> </tr> <% } %> 这里只是简单得描述了一下,gotoPage是一个javascript函数,就是提交一个表单,指定当前页码。这里有些问题都没有处理:比如页码越界(可以在客户端也可以在服务器端验证,可以报错也可以自动纠正)。 
|