如何在JSF数据表中获取选定的行索引?


问题内容

我在index.xhtml上有数据打包

<h:dataTable style="border: solid 2px black;"
    value="#{IndexBean.bookList}" var="item"
    binding="#{IndexBean.datatableBooks}">

    <h:column>
        <h:commandButton value="Edit" actionListener="#{IndexBean.editBook}">
            <f:param name="index" value="#{IndexBean.datatableBooks.rowIndex}"/>
        </h:commandButton>
    </h:column>
</h:dataTable>

我的豆子:

@ManagedBean(name="IndexBean")
@ViewScoped
public class IndexBean implements Serializable {
    private HtmlDataTable datatableBooks;

    public HtmlDataTable getDatatableBooks() {
        return datatableBooks;
    }

    public void setDatatableBooks(HtmlDataTable datatableBooks) {
        this.datatableBooks = datatableBooks;
    }

    public void editBook() throws IOException{
        int index = Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("index").toString());
        System.out.println(index);
    }
}

我的问题是,即使单击不同的编辑按钮,我也总是在服务器日志中获得相同的索引。想象有一个提供给数据表的集合。我没有在bean中显示出来。

如果我将范围从ViewScope更改为RequestScope,则可以正常工作。可能是什么问题@ViewScoped?提前致谢 :)

编辑:

<h:column>
    <h:commandButton value="Edit" actionListener="#{IndexBean.editBook}" />
</h:column>

public void editBook(ActionEvent ev) throws IOException{
    if (ev.getSource() != null && ev.getSource() instanceof HtmlDataTable) {
        HtmlDataTable objHtmlDataTable = (HtmlDataTable) ev.getSource();
        System.out.println(objHtmlDataTable.getRowIndex());
    }
}

问题答案:

您已经将<h:dataTable>组件绑定到了bean。您需要做的只是:

public void editBook() throws IOException{
    int index = datatableBooks.getRowIndex(); // Actually not interesting info.
    Book book = (Book) datatableBooks.getRowData(); // This is what you want.
}

<f:param>也这里不需要。有关更多提示,请参阅本文

更新
:我可以重现您的问题。这可能是的错误@ViewScoped。当Bean设置为时@RequestScoped,它将按预期工作。同样,当您删除组件绑定并自己从viewroot获取组件时,它会按预期工作。我已经对此提交了1658号