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

时间:2010-05-06 07:43:28

标签: java jsf facelets

我在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());
    }
}

3 个答案:

答案 0 :(得分:14)

您已将<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>。有关更多提示,请参阅this article

更新:我可以重现您的问题。这可能是@ViewScoped的错误。当bean设置为@RequestScoped时,它按预期工作。此外,当您删除组件绑定并自己从视图中获取组件时,它将按预期工作。我已就此提出issue 1658

答案 1 :(得分:1)

您可以使用Java bean上的[getRowData()][1]方法直接获取位于用户单击按钮的行上的对象。

代码示例:

public void editBook(ActionEvent evt) {
    // We get the table object
    HtmlDataTable table = getParentDatatable((UIComponent) evt.getSource());
    // We get the object on the selected line.
    Object o = table.getRowData();
    // Eventually, if you need the index of the line, simply do:
    int index = table.getRowIndex();
    // ...
}

// Method to get the HtmlDataTable.
private HtmlDataTable getParentDatatable(UIComponent compo) {
    if (compo == null) {
        return null;
    }
    if (compo instanceof HtmlDataTable) {
        return (HtmlDataTable) compo;
    }
    return getParentDataTable(compo.getParent());
}

<小时/> 修改

JSF代码现在看起来像:

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

此外,不要忘记通过设置editBook()参数来更改javax.faces.event.ActionEvent方法的签名。

答案 2 :(得分:0)

如果您使用EL 2.2,例如使用Tomcat7,您可以尝试

<h:commandLink action="#{IndexBean.editBook(item)}" immediate="true">

我希望能帮助