title: How to get selected row index in JSF datatable?
body: <p>I have a databale on index.xhtml</p>
  
  <pre><code>&lt;h:dataTable style="border: solid 2px black;"
      value="#{IndexBean.bookList}" var="item"
      binding="#{IndexBean.datatableBooks}"&gt;
  
      &lt;h:column&gt;
          &lt;h:commandButton value="Edit" actionListener="#{IndexBean.editBook}"&gt;
              &lt;f:param name="index" value="#{IndexBean.datatableBooks.rowIndex}"/&gt;
          &lt;/h:commandButton&gt;
      &lt;/h:column&gt;
  &lt;/h:dataTable&gt;
  </code></pre>
  
  <p>My bean:</p>
  
  <pre><code>@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);
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>If I change scope from ViewScope to RequestScope it works fine. What can be the problem with <code>@ViewScoped</code>? Thanks in advance :)</p>
  
  <p>EDIT:</p>
  
  <pre><code>&lt;h:column&gt;
      &lt;h:commandButton value="Edit" actionListener="#{IndexBean.editBook}" /&gt;
  &lt;/h:column&gt;
  </code></pre>
  
  <hr>
  
  <pre><code>public void editBook(ActionEvent ev) throws IOException{
      if (ev.getSource() != null &amp;&amp; ev.getSource() instanceof HtmlDataTable) {
          HtmlDataTable objHtmlDataTable = (HtmlDataTable) ev.getSource();
          System.out.println(objHtmlDataTable.getRowIndex());
      }
  }
  </code></pre>