JSFでdataTableの行番号を表示する方法

JSFでdataTableの行番号を表示する方法

JSF dataTableには、現在選択されている行番号を表示するメソッドは含まれていません。 ただし、現在選択されている行番号を返すgetRowIndex()メソッドを持つjavax.faces.model.DataModelクラスを使用してハッキングすることができます。

JSF + DataModel

以下は、DataModelを使用して現在選択されている行番号を返す方法を示すJSF 2.0の例です。

1. マネージドBean

「person」という名前の管理対象Bean。DataModelを使用してpersonオブジェクトのリストを保持します。

package com.example;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.ArrayDataModel;
import javax.faces.model.DataModel;

@ManagedBean(name="person")
@SessionScoped
public class PersonBean implements Serializable{

    private static final long serialVersionUID = 1L;

    private static final Person[] personList = new Person[]{

        new Person("Person", "A", 10),
        new Person("Person", "B", 20),
        new Person("Person", "C", 30),
        new Person("Person", "D", 40),
        new Person("Person", "E", 50)

    };

    /* To get the row numbers, use dataModel instead
    public Person[] getPersonList() {

        return personList;

    }
    */

    private DataModel person = new ArrayDataModel(personList);

    public DataModel getPersonList() {

        return person;

    }

    public static class Person{

        String firstName;
        String lastName;
        int age;

        public Person(String firstName, String lastName, int age) {
            super();
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
        }

        //getter and setter methods
    }
}

2. JSFページ

現在選択されている行番号の0インデックスを返すためのDataModel「rowIndex」の使用を示すJSPページ。



    
        
    
    

        

Display dataTable row numbers in JSF

No #{person.personList.rowIndex + 1} First Name #{p.firstName} Last Name #{p.lastName} Age #{p.age}

3. Demo

jsf2-dataTable-RowNumbers-Example

ソースコードをダウンロード

ダウンロード–JSF-2-DataTable-RowNumbers-Example.zip(10KB)