HomeJSF

JSF 1.2 Data Table (h:dataTable) example

Like Tweet Pin it Share Share Email

Tutorial – JSF 1.2 Data Table Example

Describing Example : in JSF tutorial :

1. In this tutorial example we will explain how to use h:dataTable component in JSF.

2.  h:dataTable (data table in JSF) is one of very useful component in JSF. It is used often. For example, Suppose we have a list of Gulf countries, European countries and Asian countries. Suppose user select  Asian countries then we want to show the list of countries comes under the category of Asian Country. Then we can display this list of Asian Countries using h:dataTable component. We will see it by doing this example.
3. We have these files while doing this example.

  1. countryOptionPage.jsp
  2.  showStateList.jsp
  3. DataTableJSFManagedBean.java
  4. DataTableView.java
  5. faces-config.xml
  6. web.xml

4. Eclipse image for this project.

Image showing Eclipse Screen for Example Of JSF Component (h:dataTable)
Eclipse Image – JSF : h:DataTable Example Project Hierarchy

Procedures to do this Example :

1. Creating a dynamic web application
We are considering that you have basic knowledge of creating a web application in JSF. In this step we have to create a dynamic web application with name “dataTableExampleInJSF”. Configure this dynamic web application with JSF capabilities.
Please read – First Sample Hello World Example in JSF. This tutorial will explain you how to create first JSF web project in Eclipse using Apache Tomcat Server.
After creating JSF  dynamic Web Application, Let us see Data Table component (h:dataTable) in JSF.

2. Create JSP Pages :
Now we have to create two JSP pages.
1. countryOptionPage.jsp – This is  page is to provide countries type list  like European, Gulf and Asian Countries as options. In this page we can select any country type from given options. If user is Empty fields will be validated at client side. If we will leave any field empty, an alert message will be shown showing that country type field is empty. Please select value for country type.
2. showStateList.jsp – This page will show the list of countries belongs to the country type selected in countryOptionPage.jsp. We have to concentrate more on this JSP because this JSP is using component of JSF to display the list of countries.

1. countryOptionPage.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>h:dataTable Example In JSF-Tutorial</title>
<script type="text/javascript">
 function validateCountryType() {
  var countryTypeId = document.getElementById("dataTableExampleInJSFFormId:countryTypeId");
  if (countryTypeId != null && countryTypeId.value == '00') {
   alert("Please Select Country Type");
   return false;
  }
  return true;
 }
</script>
</head>
<body>
 <f:view>
  <h:form id="dataTableExampleInJSFFormId"
   onsubmit="return validateCountryType()">
   <h:panelGrid>
    <h:outputText value="Please Select Countries Type:"></h:outputText>
    <h:selectOneMenu id="countryTypeId" value="#{dataTableJSFMBean.viewModel.countriesType}">
     <f:selectItems value="#{dataTableJSFMBean.countriesTypeList}" />
    </h:selectOneMenu>
   </h:panelGrid>
   <h:panelGroup>
    <h:commandButton action="#{dataTableJSFMBean.showCountriesList}"></h:commandButton>
   </h:panelGroup>
  </h:form>
 </f:view>
</body>
</html>

2. displaySelectOneMenuExample.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>h:dataTable Example In JSF-Tutorial</title>
</head>
<body>
    <f:view>
        <h:dataTable id="stateDataTableId" border="1"
            value="#{dataTableJSFMBean.viewModel.dataTableList}" var="stateVar">
            <h:column id="stateNameColID">
                <f:facet name="header">
                    <h:outputText value="Country Name" />
                </f:facet>
                <h:outputText value="#{stateVar}" />
            </h:column>
        </h:dataTable>
    </f:view>
</body>
</html>

3. Create Managed Bean For this Example :
Throughout this JSF example you can see these value binded attributes “#{dataTableJSFMBean.viewModel.dataTableList}”
Here
dataTableJSFMBean – Manged Bean
viewModel – View Model (Used to get & set values of the form field attribute)
dataTableList –  List of States falling in certain category (This attribute is displayed inside viewModel )

dataTableJSFMBean will be defined in faces-config.xml file. Please see faces-config.xml file for this example.
Below code is for Managed Bean DataTableJSFManagedBean.javaCode for DataTableJSFManagedBean.java


package com.sitenol.dataTableExampleInJSF;
import java.util.List;
import java.util.Map;
import javax.faces.model.SelectItem;
public class DataTableJSFManagedBean {
    private DataTableView viewModel;
    public DataTableJSFManagedBean(){
        viewModel = new DataTableView();
    }
    public DataTableView getViewModel() {
        return viewModel;
    }
    public void setViewModel(DataTableView viewModel) {
        this.viewModel = viewModel;
    }
    public List<SelectItem> getCountriesTypeList() {
        return this.getViewModel().getCountriesTypeList();
    }
    public String showCountriesList(){
        if(this.getViewModel() != null    && 
                this.getViewModel().getCountryMap() != null 
                && this.getViewModel().getCountryMap().size() >= 0 
                && this.getViewModel().getCountriesType() != null){
            Map<String, List<String>> countryList = this.getViewModel().getCountryMap();
            List<String> dataTableList = countryList.get(this.getViewModel().getCountriesType());
            if(dataTableList != null && dataTableList.size() > 0){
                System.out.println("Country Type Selected - "+this.getViewModel().getCountriesType() +" && List size Of Countries Values "+dataTableList.size());
                this.getViewModel().setDataTableList(dataTableList);
                return "showCountriesList";
            }
        }
        return null;
    }
}

4. Create View Model For this Example :
Inside Managed Bean DataTableJSFManagedBean.java you can see
private DataTableView viewModel;
DataTableView.java is view model. Code for DataTableView.java


package com.sitenol.dataTableExampleInJSF;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.model.SelectItem;
public class DataTableView {
	private String countriesType;
	private Map<String, List<String>> countryMap;
	private List<String> dataTableList;
	private List<SelectItem> countriesTypeList;
	public DataTableView() {
		countryMap = new HashMap<String, List<String>>();
		dataTableList = new ArrayList<String>();
	}
	public String getCountriesType() {
		return countriesType;
	}
	public void setCountriesType(String countriesType) {
		this.countriesType = countriesType;
	}
	public Map<String, List<String>> getCountryMap() {
		if (countryMap == null)
			countryMap = new HashMap<String, List<String>>();
		List<String> sixAsianCountriesList = new ArrayList<String>();
		sixAsianCountriesList.add("BAHRAIN");
		sixAsianCountriesList.add("BANGLADESH");
		sixAsianCountriesList.add("CHINA");
		sixAsianCountriesList.add("SINGAPORE");
		sixAsianCountriesList.add("INDIA");
		sixAsianCountriesList.add("JAPAN");
		countryMap.put("asianCountries", sixAsianCountriesList);
		List<String> sixEuropeanList = new ArrayList<String>();
		sixEuropeanList.add("Sweden");
		sixEuropeanList.add("Germany");
		sixEuropeanList.add("Finland");
		sixEuropeanList.add("Italy");
		sixEuropeanList.add("Poland");
		sixEuropeanList.add("United Kingdom");
		countryMap.put("europeanCountries", sixEuropeanList);
		List<String> sixGulfCountriesList = new ArrayList<String>();
		sixGulfCountriesList.add("Bahrain - or Kingdom of Bahrain");
		sixGulfCountriesList.add("Kuwait");
		sixGulfCountriesList.add("Oman - or Sultanate of Oman");
		sixGulfCountriesList.add("Qatar");
		sixGulfCountriesList
				.add("Saudi Arabia - or Kingdom of Saudi Arabia (KSA)");
		sixGulfCountriesList.add("UAE - United Arab Emirates");
		countryMap.put("gulfCountries", sixGulfCountriesList);
		return countryMap;
	}
	public void setCountryMap(Map<String, List<String>> countryMap) {
		this.countryMap = countryMap;
	}
	public List<String> getDataTableList() {
		return dataTableList;
	}
	public void setDataTableList(List<String> dataTableList) {
		this.dataTableList = dataTableList;
	}
	public List<SelectItem> getCountriesTypeList() {
		if (countriesTypeList == null) {
			countriesTypeList = new ArrayList<SelectItem>();
			countriesTypeList.add(0, new SelectItem("00", "<--Select-->"));
			countriesTypeList.add(new SelectItem("asianCountries",
					"Asian Countries"));
			countriesTypeList.add(new SelectItem("europeanCountries",
					"European Countries"));
			countriesTypeList.add(new SelectItem("gulfCountries",
					"Gulf Countries"));
		}
		return countriesTypeList;
	}
	public void setCountriesTypeList(List<SelectItem> countriesTypeList) {
		this.countriesTypeList = countriesTypeList;
	}
}

5. Create faces-config.xml file :
Please find the faces-config.xml file code here. This faces-config.xml file is for example using h:dataTable in JSF. Faces-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
    version="1.2">
    <managed-bean>
        <managed-bean-name>dataTableJSFMBean</managed-bean-name>
        <managed-bean-class>com.sitenol.dataTableExampleInJSF.DataTableJSFManagedBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <display-name>Country List Page</display-name>
        <from-view-id>/countryOptionPage.jsp</from-view-id>
        <navigation-case>
            <from-outcome>showCountriesList</from-outcome>
            <to-view-id>/showStateList.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
</faces-config>

6. Create web.xml file :
Please find the web.xml file code here. This web.xml file is for example using in JSF. Code for web.xml :


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>dataTableExampleInJSF</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>server</param-value>
  </context-param>
  <context-param>
    <description>
    This parameter tells MyFaces if javascript code should be allowed in
    the rendered HTML output.
    If javascript is allowed, command_link anchors will have javascript code
    that submits the corresponding form.
    If javascript is not allowed, the state saving info and nested parameters
    will be added as url parameters.
    Default is 'true'</description>
    <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <description>
    If true, rendered HTML code will be formatted, so that it is 'human-readable'
    i.e. additional line separators and whitespace will be written, that do not
    influence the HTML code.
    Default is 'true'</description>
    <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
    <param-value>false</param-value>
  </context-param>
  <context-param>
    <description>
    If true, a javascript function will be rendered that is able to restore the
    former vertical scroll on every request. Convenient feature if you have pages
    with long lists and you do not want the browser page to always jump to the top
    if you trigger a link or button action that stays on the same page.
    Default is 'false'
</description>
    <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
    <param-value>true</param-value>
  </context-param>
  <listener>
    <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
  </listener>
</web-app>

7. Deploy Application and Run Server :
In this step you we have to deploy dataTableExampleInJSF.war  file to our web application server. After that please start the web server.
8. Run The Application:
After successfully war deployment. Please start the server. After that open Internet Explorer and hit this “http://localhost:8080/dataTableExampleInJSF/countryOptionPage.faces”. So now we can see output of our  example in JSF. Out put screen will be like this  First Screen

tabular format in JSF
Select A country

In this screen you have to select country type from list
1. Please Select Countries Type:
We will validate this field at client side using JavaScript. If you will fail to enter any country type field you will receive one alert message. When you will enter all the fields completely you will receive   Second Screen.
Second Screen

h:dataTable in JSF
Showing States

Comments (0)

Leave a Reply

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