小编典典

结果集到分页

jsp

如何将Resultset对象转换为JSP上的分页视图?

例如,这是我的查询和结果集:

pst = con.prepareStatement("select userName, job, place from contact");
rs = pst.executeQuery();

阅读 313

收藏
2020-06-08

共1个答案

小编典典

首先,您需要向JSP中添加一个或两个额外的请求参数:firstrow和(可选)rowcount。该rowcount也可以留下,距离完全在服务器端definied。

然后在JSP中添加一堆分页按钮: 下一个 按钮应指示将Servlet的值递增firstrowrowcount。在 前面的
按钮应该明显递减的价值firstrow与价值rowcount。不要忘记处理负值并正确溢出!您可以在的帮助下完成此操作SELECT count(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”分页能够很好地工作。

2020-06-08