To get started, you need to add one or two additional query parameters to the JSP: firstrow and (optionally) rowcount . The number of rowcount can also be omitted and completely determined on the server side.
Then add a bunch of paging buttons to the JSP: the next button should instruct the Servlet to increase the firstrow value with the rowcount value. The previous button, obviously, should firstrow value firstrow by rowcount value. Remember to handle negative values ββand overflows correctly! You can do this with SELECT count(id) .
Then fire a specific SQL query to get a list of results. However, the exact syntax of SQL depends on the database used. In MySQL and PostgreSQL, this is easy with the LIMIT and OFFSET clauses:
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);
In Oracle, you need a subquery with a rownum , which should look like this:
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; }
In DB2, you need the OLAP function row_number() for this:
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; }
I do not do MSSQL, but it is syntactically similar to DB2. Also see this topic .
Finally, just submit the sublist on the JSP page in the usual way using JSTL 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>
Note that some may suggest that you select SELECT entire table and keep the List<Contact> in the scope of the session and use List#subList() for List#subList() on the page. But it is far from efficient for memory with thousands of lines and several simultaneous users.
For those interested in a similar answer in the context of JSF / MySQL using the h:dataTable , this article may be useful. It also contains some useful language-independent math expressions that make it easy to work with Google-like pagination.