August 12 2015

Jsf datatable row index

Jsf datatable row index

Jsf datatable row index is used to display the row numbers for each row. This can be done by using binding attribute of datatable. Bind the table to the view itself instead of a bean.

<h:dataTable binding=”#{student}”  .. >

Add a column with the following code

<h:column>

#{student.rowIndex + 1}

</h:column>

Example

StudentList.xhtml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
 xmlns:f="http://java.sun.com/jsf/core"
 xmlns:h="http://java.sun.com/jsf/html">

 <h:head>
 <title>Jsf datatable row index</title>
</h:head>

<h:body>

<h2> Jsf datatable row index </h2>

<h:form>

<h:dataTable value="#{studentManagedBean.studentList}" var="stud"
 border="1" binding="#{student}">

<h:column>
 <f:facet name="header">Index</f:facet>
 <h:outputText value="#{student.rowIndex + 1}" />
 </h:column>

 <h:column>
 <f:facet name="header">Student ID</f:facet>
 <h:outputText value="#{stud.studId}" />
 </h:column>

<h:column>
 <f:facet name="header">Name</f:facet>
 <h:outputText value="#{stud.name}" />
 </h:column>

<h:column>
 <f:facet name="header">Age</f:facet>
 <h:outputText value="#{stud.age}" />
 </h:column>

</h:dataTable>

</h:form>
</h:body>

</html>

StudentManagedBean.java

package com.answersz;

import java.util.ArrayList;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "studentManagedBean")
@SessionScoped
public class StudentManagedBean {

private ArrayList<Student> studentList = new ArrayList<Student>();

@PostConstruct
 public void init() {
 studentList.add(new Student("2015-01", "ERIC", 20));
 studentList.add(new Student("2015-02", "ANDREW", 18));
 studentList.add(new Student("2015-03", "HARRY", 17));
 }

public ArrayList<Student> getStudentList() {
 return studentList;
 }

public void setStudentList(ArrayList<Student> studentList) {
 this.studentList = studentList;
 }

}

Student.java

package com.answersz;

public class Student {

 private String studId;
 private String name;
 private Integer age;

 public Student(String studId, String name, Integer age) {
 super();
 this.studId = studId;
 this.name = name;
 this.age = age;
 }

 // getters and setters
}

jsfrowindex


Copyright © 2014. All rights reserved.

Posted August 12, 2015 by answersz in category Jsf

Leave a Comment

Your email address will not be published. Required fields are marked *

*