You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PrimeFaces 6.2中<p:dataGrid>组件的分页问题咨询

PrimeFaces DataGrid Pagination: Common Fixes & Best Practices

Hey there! Let's break down everything you need to get pagination working smoothly with your <p:dataGrid> setup, since you already have the basic backing bean and component in place.


1. Verify Your Component Configuration

First, double-check that your dataGrid has all the necessary pagination attributes. You already have paginator="true" and rows="10", but adding a few more will make pagination more user-friendly and ensure it behaves as expected:

<p:dataGrid id="employeeList" var="employee" rowIndexVar="rowIndex" 
            value="#{sampleController.employeeRecords}" columns="1" layout="grid" 
            rows="10" paginator="true"
            <!-- Customize the paginator's control layout -->
            paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
            <!-- Let users adjust rows per page -->
            rowsPerPageTemplate="5,10,20"
            emptyMessage="No items to display..." >
  <!-- Your employee record content goes here -->
</p:dataGrid>

The paginatorTemplate defines which navigation controls appear, and rowsPerPageTemplate adds a dropdown for users to tweak how many records show per page.


2. Fix Bean Scope (Critical for Pagination)

This is the #1 cause of broken pagination! If your SampleController uses @RequestScoped, every time a user clicks a pagination link, the bean gets recreated from scratch. That means your employeeRecords list reloads, and pagination resets to the first page.

Use @ViewScoped instead (it's the ideal scope for stateful JSF components like paginators):

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
// For CDI users: replace with @Named + @ViewScoped (JSF 2.3+)
import java.io.Serializable;
import java.util.List;

@ManagedBean
@ViewScoped
public class SampleController implements Serializable {
    private List<EmployeeVo> employeeRecords;

    // Lazy load data ONLY when it's first needed
    public List<EmployeeVo> getEmployeeRecords() {
        if (employeeRecords == null) {
            loadEmployeeData();
        }
        return employeeRecords;
    }

    private void loadEmployeeData() {
        // Replace with your actual service/repository call
        employeeRecords = yourEmployeeService.getAllEmployees();
    }

    // Setter (only needed if you need to overwrite the list externally)
    public void setEmployeeRecords(List<EmployeeVo> employeeRecords) {
        this.employeeRecords = employeeRecords;
    }
}

Pro Tip: Never load data directly in the getter without checking for null first—this prevents redundant database calls every time the getter is invoked (which happens frequently in JSF).


3. Lazy Loading for Large Datasets

If you're dealing with hundreds or thousands of employee records, loading all data at once will hurt performance. PrimeFaces' LazyDataModel lets you fetch only the data needed for the current page, which is way more efficient.

Step 1: Update Your Backing Bean

Replace your List<EmployeeVo> with a LazyDataModel<EmployeeVo>:

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

@ManagedBean
@ViewScoped
public class SampleController implements Serializable {
    private LazyDataModel<EmployeeVo> employeeRecords;

    @PostConstruct
    public void init() {
        employeeRecords = new LazyDataModel<EmployeeVo>() {
            @Override
            public List<EmployeeVo> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
                // first = starting index of the current page
                // pageSize = number of records per page (matches your dataGrid's rows attribute)
                List<EmployeeVo> paginatedEmployees = yourEmployeeService.getPaginatedEmployees(first, pageSize);
                
                // Set total record count so the paginator knows how many pages exist
                this.setRowCount(yourEmployeeService.getTotalEmployeeCount());
                
                return paginatedEmployees;
            }
        };
    }

    public LazyDataModel<EmployeeVo> getEmployeeRecords() {
        return employeeRecords;
    }
}

Step 2: No Changes Needed to the DataGrid

Your existing dataGrid will work with LazyDataModel out of the box—PrimeFaces automatically calls the load() method whenever the user navigates to a new page.


4. Troubleshooting Common Pagination Issues

Here are quick fixes for the most frequent problems:

  • Pagination links do nothing/reset to page 1: Switch your bean from @RequestScoped to @ViewScoped.
  • No data shows on pages after the first: Ensure your LazyDataModel's setRowCount() is set to the total number of records (not just the current page's count).
  • Rows per page dropdown doesn't update: Make sure rowsPerPageTemplate is set on the dataGrid, and your bean is in a stateful scope (ViewScoped).
  • Paginator doesn't appear at all: Check that rows is set to a value greater than 0, and that your employeeRecords list isn't empty (the emptyMessage will show if there's no data).

内容的提问来源于stack exchange,提问作者Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:27:51