Searching...
Saturday, 20 April 2013

JSF Data table Simple example

07:03

JSF 2 DataTable

In JSF we can create data table to iterate collection or array or values and display or edit in to JSF pages. Here is one simple example to display data table using h:dataTable tag.
Steps
  • Create a Managed bean which contains the collection of records which needs to be displayed in JSF page
  • Create a JSF page and create h:dataTable component


1. Create a Customer class

package com.vinod.jsf;

public class Customer {
    private String name;
    private String address;
    private String phonenumber;
    public String getPhonenumber() {
        return phonenumber;
    }
    public void setPhonenumber(String phonenumber) {
        this.phonenumber = phonenumber;
    }
    public Customer(String name, String address, String phoneNumber) {
        super();
        this.name = name;
        this.address = address;
        this.phonenumber = phoneNumber;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}
2. Create a Managed Bean
package com.vinod.jsf;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class DataTableBean {

    public DataTableBean() {
    }
    public List getCustomers() {
        List customers = new ArrayList();
        customers.add(new Customer("vinod", "Bangalore", "7777777777"));
        customers.add(new Customer("hari", "chennai", "7777447777"));
        customers.add(new Customer("Jithesh", "Pala", "7777557777"));
        return customers;

    }
}
3. Create a jsf Page
<?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:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>My JSF Examples</title>
</head>
<h:body>
    <h:form id="vinod">
        <h:dataTable value="#{dataTableBean.customers}" var="customer">
            <h:column>
                <f:facet name="header">Name</f:facet>
                    #{customer.name}
                      </h:column>
            <h:column>
                <f:facet name="header">Address</f:facet>
                    #{customer.address}
                </h:column>
            <h:column>
                <f:facet name="header">Phone Number</f:facet>
                    #{customer.phonenumber}
                </h:column>
        </h:dataTable>
    </h:form>
</h:body>
</html>
4. Run Application

https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-jsf
Done..download application ..use mvn jetty:run to run the application

0 comments: