How do I convert Resultset object to a paginated view on a JSP?
For example, this is my query and result set:
pst = con.prepareStatement("select userName, job, place from contact");
rs = pst.executeQuery();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To start, you need to add one or two extra request parameters to the JSP:
firstrowand (optionally)rowcount. Therowcountcan also be left away and definied entirely in the server side.Then add a bunch of paging buttons to the JSP: the next button should instruct the
Servletto increment the value offirstrowwith the value ofrowcount. The previous button should obviously decrement the value offirstrowwith the value ofrowcount. Don’t forget to handle negative values and overflows correctly! You can do it with help ofSELECT count(id).Then fire a specific SQL query to retrieve a sublist of the results. The exact SQL syntax however depends on the DB used. In MySQL and PostgreSQL it is easy with
LIMITandOFFSETclauses:In Oracle you need a subquery with
rownumclause which should look like:In DB2 you need the OLAP function
row_number()for this:I don’t do MSSQL, but it’s syntactically similar to DB2. Also see this topic.
Finally just present the sublist in the JSP page the usual way with JSTL
c:forEach.Note that some may suggest that you need to
SELECTthe entire table and save theList<Contact>in the session scope and make use ofList#subList()to paginate. But this is far from memory-efficient with thousands rows and multiple concurrent users.For ones who are interested in similar answer in JSF/MySQL context using
h:dataTablecomponent, you may find this article useful. It also contains some useful language-agnostic maths to get the “Google-like” pagination nicely to work.