Pagination is in fact easy. You just have to keep passing one or two parameters around: firstrow
and optionally rowcount
(which can also be kept in the server side). When the enduser clicks Next, you just increment the value of firstrow
with the value of rowcount
. When the enduser clicks Back, you just decrement the value of firstrow
with the value of rowcount
. You only need to check if it doesn't exceed the borders of 0
and totalrows
and alter accordingly.
Then, based on the desired firstrow
and rowcount
, you know exactly which data to display. If all the data is already in some List
in Java's memory, then you just use List#subList()
to obtain a sublist from it for display. It is however not efficient to duplicate the entire database table into Java's memory. It may not harm when it's only 100 rows, but when it's much more than that and/or you're duplicating it for every single user, then the application will run out of memory very soon.
In that case you'd rather like to paginate at DB level. In for example MySQL you can use LIMIT
clause to obtain a subset of results from the DB. JPA/Hibernate even provides ways using setFirstResult()
and setMaxResults()
methods of Query
and Criteria
respectively. You can find examples in this and this answer.
You can find a basic JSF 1.2 targeted kickoff example of Google-like pagination (and sorting) in this article. It uses Tomahawk components, but in JSF 2.0 you can just leave them away by making the bean @ViewScoped
(replaces t:saveState
) and using ui:repeat
(replaces t:dataList
).
Last but not least, there are lot of component libraries which does all the works in a single component. For example RichFaces <rich:datascroller>
and PrimeFaces <p:dataTable paginator="true">
(can also be done ajaxical).