首先,您需要向JSP中添加一个或两个额外的请求参数:
firstrow和(可选)
rowcount。该
rowcount也可以留下,距离完全在服务器端definied。
然后在JSP中添加一堆分页按钮: 下一个 按钮应指示将
Servlet的值递增
firstrow为
rowcount。在 前面的
按钮应该明显递减的价值
firstrow与价值
rowcount。不要忘记处理负值并正确溢出!您可以在的帮助下完成此操作
SELECtcount(id)。
然后触发一个特定的SQL查询以检索结果的 子列表
。但是,确切的SQL语法取决于所使用的数据库。在MySQL和PostgreSQL中,使用
LIMITand
OFFSET子句很容易:
private static final String SQL_SUBLIST = "SELECT id, username, job, place FROM" + " contact ORDER BY id LIMIT %d OFFSET %d";public List<Contact> list(int firstrow, int rowcount) { String sql = String.format(SQL_SUBLIST, firstrow, rowcount); // Implement JDBC. return contacts;}在Oracle中,您需要一个带有
rownum子句的子查询,该子句应类似于:
private static final String SQL_SUBLIST = "SELECt id, username, job, place FROM" + " (SELECt id, username, job, place FROM contact ORDER BY id)" + " WHERe ROWNUM BETWEEN %d AND %d";public List<Contact> list(int firstrow, int rowcount) { String sql = String.format(SQL_SUBLIST, firstrow, firstrow + rowcount); // Implement JDBC. return contacts;}在DB2中,您需要OLAP函数
row_number():
private static final String SQL_SUBLIST = "SELECt id, username, job, place FROM" + " (SELECt row_number() OVER (ORDER BY id) AS row, id, username, job, place" + " FROM contact) AS temp WHERe row BETWEEN %d AND %d";public List<Contact> list(int firstrow, int rowcount) { String sql = String.format(SQL_SUBLIST, firstrow, firstrow + rowcount); // Implement JDBC. return contacts;}我不使用MSSQL,但是在语法上与DB2类似。。
最后,只需使用JSTL的常规方法在JSP页面中显示子列表即可
c:forEach。
<table> <c:forEach items="${contacts}" var="contact"> <tr> <td>${contact.username}</td> <td>${contact.job}</td> <td>${contact.place}</td> </tr> </c:forEach></table><form action="yourservlet" method="post"> <input type="hidden" name="firstrow" value="${firstrow}"> <input type="hidden" name="rowcount" value="${rowcount}"> <input type="submit" name="page" value="next"> <input type="submit" name="page" value="previous"></form>注意,有些人 可能
建议您需要
SELECT将整个表保存
List<Contact>在会话范围中并利用
List#subList()进行分页。但这
远不 及具有数千行和多个并发用户的内存效率。
对于对使用
h:dataTable组件在JSF /
MySQL上下文中的类似答案感兴趣的人,您可能会发现本文很有用。它还包含一些与语言无关的有用数学,以使“类Google”分页能够很好地工作。



