DataTable .rowIndex 总是 returns 0
DataTable .rowIndex always returns 0
我做错了什么?
@Named("utilityController")
@RequestScoped
public class UtilityController {
public DataModel<Result> getResultSample() {
Result[] resultSample = new Result[11];
//Populate the array
return new ArrayDataModel<>(resultSample);
}
}
在 JSF 中:
<h:dataTable id="sampleResult" value="#{utilityController.resultSample}" var="item" styleClass="table table-bordered table-striped table-hover table-condensed" >
<h:column>
<f:facet name="header">SN</f:facet>
#{utilityController.resultSample.rowIndex}
</h:column>
<h:column>
<f:facet name="header">Subject</f:facet>
#{item.subject.name}
</h:column>
....
</h:dataTable>
rowIndex 总是 returns 0,如上所示。请帮我指出我做错了什么
What am I not doing right?
在 getter 方法中创建模型。永远不要那样做。所有 getter 方法应如下所示:
public DataModel<Result> getResultSample() {
return resultSample;
}
getter 方法在每一轮迭代中被调用。您基本上是从上一轮迭代中清除模型并返回一个全新的模型,所有状态(例如当前行索引)都重置为默认值。
将该作业移至 bean 的 @PostConstruct
方法。
private DataModel<Result> resultSample;
@PostConstruct
public void init() {
Result[] results = new Result[11];
// ...
resultSample = new ArrayDataModel<Result>(results);
}
public DataModel<Result> getResultSample() {
return resultSample;
}
关于您的具体功能需求,您也可以只引用 UIData#getRowIndex()
而无需将值包装在 DataModel
.
public Result[] getResults() { // Consider List<Result> instead.
return results;
}
<h:dataTable binding="#{table}" value="#{bean.results}" var="result">
<h:column>#{table.rowIndex + 1}</h:column>
<h:column>#{result.subject.name}</h:column>
</h:dataTable>
请注意,我用 1 递增了它,因为它是从 0 开始的,而人类期望的是从 1 开始的索引。
另请参阅:
- How and when should I load the model from database for h:dataTable
- Why JSF calls getters multiple times
- How does the 'binding' attribute work in JSF? When and how should it be used?