JSF - Add Data to DataTable


In this article, we'll showcase adding a row to a datatable

Example Application

Let us create a test JSF application to test the above functionality.

1Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - Display DataTable sub-chapter of JSF - Data Tables chapter.
2Modify home.xhtml as explained below. Keep rest of the files unchanged.
3Compile and run the application to make sure business logic is working as per the requirements.
4Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver.
5Launch your web application using appropriate URL as explained below in the last step.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="http://www.w3.org/1999/xhtml"   
      <title>JSF tutorial</title>		
      <h:outputStylesheet library="css" name="styles.css"  /> 	
   <h2>DataTable Example</h2>
      <h:dataTable value="#{userData.employees}" var="employee"
            <f:facet name="header">Name</f:facet>    				
            <f:facet name="header">Department</f:facet>
            <f:facet name="header">Age</f:facet>
            <f:facet name="header">Salary</f:facet>
      <h3>Add Employee</h3>
            <td>Name :</td>
            <td><h:inputText size="10" value="#{userData.name}" /></td>
            <td>Department :</td>
            <td><h:inputText size="20" value="#{userData.dept}" /></td>
            <td>Age :</td>
            <td><h:inputText size="5" value="#{userData.age}" /></td>
            <td>Salary :</td>
            <td><h:inputText size="5" value="#{userData.salary}" /></td>
            <td> </td>
            <td><h:commandButton value="Add Employee" 
               action="#{userData.addEmployee}" /></td>

Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:

JSF Add Data to datatable

Add values to Add Employee Form and click Add Employee button.See the result. JSF Add Data to datatable1