JSF dataTable不包含任何显示当前选定行号的方法。 但是,您可以使用javax.faces.model.DataModel类对其进行修改,该类具有getRowIndex()方法以返回当前选择的行号。
JSF +数据模型
这是一个JSF 2.0示例,向您展示如何使用DataModel返回当前选择的行号。
1.托管豆
一个名为“ person”的托管bean,并显示使用DataModel来保存person对象的列表。
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页面显示使用DataModel“ rowIndex ”返回当前选定行号的0索引。
<?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>
3.演示
下载源代码
下载它– JSF-2-DataTable-RowNumbers-Example.zip (10KB)
参考
翻译自: https://mkyong.com/jsf2/how-to-display-datatable-row-numbers-in-jsf/