JSFでdataTableの行番号を表示する方法
JSF dataTableには、現在選択されている行番号を表示するメソッドは含まれていません。ただし、
javax.faces.model.DataModel
クラスをハックすると、現在選択されている行番号を返すgetRowIndex()** メソッドがあります。
JSF + DataModel
ここでは、現在選択されている行番号を返すためにDataModelを使用する方法を示すJSF 2.0の例を示します。
1.マネージドBean
「person」という名前のマネージドBean。Personオブジェクトのリストを保持するためのDataModelの使用を示します。
package com.mkyong;
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> person = new ArrayDataModel<Person>(personList);
public DataModel<Person> 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ページ
JSPページを使用して、現在選択されている行番号の0-インデックスを返すためのデータモデル ”
row Index
“の使用を示します。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<h:head>
<h:outputStylesheet library="css" name="table-style.css" />
</h:head>
<h:body>
<h1>Display dataTable row numbers in JSF</h1>
<h:dataTable value="#{person.personList}" var="p"
styleClass="person-table"
headerClass="person-table-header"
rowClasses="person-table-odd-row,person-table-even-row"
>
<h:column>
<!-- display currently selected row number -->
<f:facet name="header">No</f:facet>
#{person.personList.rowIndex + 1}
</h:column>
<h:column>
<f:facet name="header">First Name</f:facet>
#{p.firstName}
</h:column>
<h:column>
<f:facet name="header">Last Name</f:facet>
#{p.lastName}
</h:column>
<h:column>
<f:facet name="header">Age</f:facet>
#{p.age}
</h:column>
</h:dataTable>
</h:body>
</html>
デモ

ソースコードをダウンロードする
ダウンロード – リンク://wp-content/uploads/2010/10/JSF-2-DataTable-RowNumbers-Example.zip[JSF-2-DataTable-RowNumbers-Example.zip](10KB)
リファレンス
データモデルJavaDoc]。
https://javaserverfaces.dev.java.net/nonav/docs/2.0/javadocs/javax/faces/model/ArrayDataModel.html
[JSF
ArrayDataModel JavaDoc]