我在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); } }
我的问题是,即使我点击不同的编辑按钮,我总是在服务器日志中获得相同的索引.假设有一个集合被提供给datatable.我没有在豆中显示.
如果我将范围从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>这里也不需要.更多提示也见this article.
更新:我可以重现你的问题.这可能是@ViewScoped的错误.当bean设置为@RequestScoped时,它的工作原理如预期.此外,当您删除组件绑定并从viewroot自己获取组件时,它的工作原理.我已经提交了issue 1658这个.