【问题标题】:DataTable .rowIndex always returns 0DataTable .rowIndex 总是返回 0
【发布时间】:2015-07-12 13:34:59
【问题描述】:

我做错了什么?

@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 始终返回 0。请有人帮我指出我做错了什么

【问题讨论】:

    标签: jsf datatable jsf-2.2


    【解决方案1】:

    我做错了什么?

    在 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 开始的索引。

    另见:

    【讨论】:

    • 感谢@BalusC,您的第二个建议似乎是一个完美的建议,我正在查看链接并将很快恢复
    • WoooW 这与绑定方法工作得很好。但是请@BalusC 表格对象来自哪里?我没有在任何地方定义它,但它具有 rowIndex 以及它可能具有哪些其他属性?
    • 单击我对 javadoc 的回答中的 UIData 链接。所有getXxx() 方法也可以通过这种方式在EL 中使用。我还添加了第三个“另见”链接来解释 binding 属性。
    • 再次感谢@BalusC 这些链接非常有用
    猜你喜欢
    • 1970-01-01
    • 2015-09-27
    • 2014-03-20
    • 2013-04-13
    • 2013-03-30
    • 2016-07-13
    • 2023-04-09
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多