Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

java - How to get selected row index in JSF datatable?

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>

My bean:

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

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.

If I change scope from ViewScope to RequestScope it works fine. What can be the problem with @ViewScoped? Thanks in advance :)

EDIT:

<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());
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.
}

The <f:param> is also not needed here. For more hints also see this article.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...