Scrolling Through the Data

Adding the ability to scroll through the data requires similar changes. The main pieces of information we need to control are the index of the first row to display and how many rows to display. The <h:dataTable> action element provides attributes for these values:

<h:dataTable value="#{reportHandler.sortedReportsModel}" var="report"
  first="#{reportHandler.firstRowIndex}"
  rows="#{reportHandler.noOfRows}">
  ...
</h:dataTable>

Binding these attributes to properties of the ReportHandler makes it easy to adjust their values programmatically when the scrolling buttons are clicked. Here’s how the properties are implemented:

package com.mycompany.expense;
...
public class ReportHandler {
    private int noOfRows = 5;
    private int firstRowIndex = 0;
    ...
    public int getNoOfRows( ) {
        return noOfRows;
    }

    public void setNoOfRows(int noOfRows) {
        this.noOfRows = noOfRows;
    }

    public int getFirstRowIndex( ) {
        return firstRowIndex;
    }

The noOfRows property is implemented as a read/write property, i.e., with both a getter and a setter method, while the firstRowIndex property is implemented as a read-only property (its value can only be changed indirectly by clicking the scrolling buttons, not directly by the user).

Four action methods support scrolling through the rows:

 public String scrollFirst( ) { firstRowIndex = 0; return "success"; } public String scrollPrevious( ) { firstRowIndex -= noOfRows; if (firstRowIndex < 0) { firstRowIndex = 0; } return "success"; } public String scrollNext( ...

Get JavaServer Faces now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.