如何在JSF数据表中获取选定的行索引? [英] How to get selected row index in JSF datatable?
问题描述
我在index.xhtml上有一个数据库
I have a databale on 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中显示过。
My problem is that I always get the same index in server log even though I click the different edit buttons. Imagine that there is one collection which is supplied to the datatable. I have not shown that in bean.
如果我将范围从ViewScope更改为RequestScope,它可以正常工作。 @ViewScoped
会出现什么问题?在此先感谢:)
If I change scope from ViewScope to RequestScope it works fine. What can be the problem with @ViewScoped
? Thanks in advance :)
编辑:
<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。您需要做的就是:
You've already bound the <h:dataTable>
component to the bean. All you need to do is:
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> $这里也不需要c $ c>。有关更多提示,请参阅本文。
The <f:param>
is also not needed here. For more hints also see this article.
更新:我可以重现您的问题。这可能是 @ViewScoped
的错误。当bean设置为 @RequestScoped
时,它按预期工作。此外,当您删除组件绑定并自己从视图中获取组件时,它将按预期工作。我已经提交了问题1658 。
Update: I can reproduce your problem. This is likely a bug with @ViewScoped
. When the bean is set to @RequestScoped
, it works as expected. Also when you remove the component binding and obtain the component from the viewroot yourself, it works as expected. I've filed issue 1658 about this.
这篇关于如何在JSF数据表中获取选定的行索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!