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

我在index.xhtml上有一个数据库

       

我的豆子:

 @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会出现什么问题? 提前致谢 :)

编辑:

    

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

您已经将组件绑定到bean。 您需要做的就是:

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

这里也不需要 。 有关更多提示,请参阅此文章 。

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

您可以做的是使用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代码现在看起来像:

  

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

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

  

我希望能帮到你