JSF 2 dataTable example

In JSF, “h:dataTable” tag is used to display data in a HTML table format. The following JSF 2.0 example show you how to use “h:dataTable” tag to loop over an array of “order” object, and display it in a HTML table format.

1. Project Folder

Project folder structure of this example.

jsf2-dataTable-folders

2. Managed bean

A managed bean named “order”, initialized the array object for later use.

OrderBean.java


package com.mkyong;

import java.io.Serializable;
import java.math.BigDecimal;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="order")
@SessionScoped
public class OrderBean implements Serializable{

	private static final long serialVersionUID = 1L;

	private static final Order[] orderList = new Order[] {
		
		new Order("A0001", "Intel CPU", 
				new BigDecimal("700.00"), 1),
		new Order("A0002", "Harddisk 10TB", 
				new BigDecimal("500.00"), 2),
		new Order("A0003", "Dell Laptop", 
				new BigDecimal("11600.00"), 8),
		new Order("A0004", "Samsung LCD", 
				new BigDecimal("5200.00"), 3),
		new Order("A0005", "A4Tech Mouse", 
				new BigDecimal("100.00"), 10)
	};
	 
	public Order[] getOrderList() {
 
		return orderList;
 
	}
	
	public static class Order{
		
		String orderNo;
		String productName;
		BigDecimal price;
		int qty;

		public Order(String orderNo, String productName, 
                                BigDecimal price, int qty) {

			this.orderNo = orderNo;
			this.productName = productName;
			this.price = price;
			this.qty = qty;
		}
		
		//getter and setter methods
	}
}

3. CSS

Create a CSS file to style the table layout.

table-style.css


.order-table{   
	border-collapse:collapse;
}

.order-table-header{
	text-align:center;
	background:none repeat scroll 0 0 #E5E5E5;
	border-bottom:1px solid #BBBBBB;
	padding:16px;
}

.order-table-odd-row{
	text-align:center;
	background:none repeat scroll 0 0 #FFFFFFF;
	border-top:1px solid #BBBBBB;
}

.order-table-even-row{
	text-align:center;
	background:none repeat scroll 0 0 #F9F9F9;
	border-top:1px solid #BBBBBB;
}

4. h:dataTable

A JSF 2.0 xhtml page to show the use of “h:dataTable” tag to loop over the array of “order” object. This example should be self-explanatory.

default.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:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      >
    <h:head>
    	<h:outputStylesheet library="css" name="table-style.css"  />
    </h:head>
    <h:body>
    	
    	<h1>JSF 2 dataTable example</h1>
    	
    		<h:dataTable value="#{order.orderList}" var="o"
    			styleClass="order-table"
    			headerClass="order-table-header"
    			rowClasses="order-table-odd-row,order-table-even-row"
    		>

    			<h:column>
    				<!-- column header -->
    				<f:facet name="header">Order No</f:facet>
    				<!-- row record -->
    				#{o.orderNo}
    			</h:column>
    			
    			<h:column>
    				<f:facet name="header">Product Name</f:facet>
    				#{o.productName}
    			</h:column>
    			
    			<h:column>
    				<f:facet name="header">Price</f:facet>
    				#{o.price}
    			</h:column>
    			
    			<h:column>
    				<f:facet name="header">Quantity</f:facet>
    				#{o.qty}
    			</h:column>
    		
    		</h:dataTable>
    		
    </h:body>
</html>

Generate this HTML output


<!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">
	<head>
	   <link type="text/css" rel="stylesheet" 
	      href="/JavaServerFaces/faces/javax.faces.resource/table-style.css?ln=css" />
	</head>
	<body> 
    	
	<h1>JSF 2 dataTable example</h1>
	
	<table class="order-table"> 
	
  	  <thead> 
		<tr> 
		<th class="order-table-header" scope="col">Order No</th> 
		<th class="order-table-header" scope="col">Product Name</th> 
		<th class="order-table-header" scope="col">Price</th> 
		<th class="order-table-header" scope="col">Quantity</th> 
		</tr> 
	  </thead> 
	  
	  <tbody> 
		<tr class="order-table-odd-row"> 
			<td>A0001</td> 
			<td>Intel CPU</td> 
			<td>700.00</td> 
			<td>1</td> 
		</tr> 
		<tr class="order-table-even-row"> 
			<td>A0002</td> 
			<td>Harddisk 10TB</td> 
			<td>500.00</td> 
			<td>2</td> 
		</tr> 
		<tr class="order-table-odd-row"> 
			<td>A0003</td> 
			<td>Dell Laptop</td> 
			<td>11600.00</td> 
			<td>8</td> 
		</tr> 
		<tr class="order-table-even-row"> 
			<td>A0004</td> 
			<td>Samsung LCD</td> 
			<td>5200.00</td> 
			<td>3</td> 
		</tr> 
		<tr class="order-table-odd-row"> 
			<td>A0005</td> 
			<td>A4Tech Mouse</td> 
			<td>100.00</td> 
			<td>10</td> 		
		</tr> 
	  </tbody> 
	 </table> 
      </body> 	
</html>

6. Demo

URL : http://localhost:8080/JavaServerFaces/default.xhtml

jsf2-dataTable-example
Download It – JSF-2-DataTable-Example.zip (11KB)

Reference

  1. JSF <h:dataTable /> JavaDoc
  2. JSF <h:column /> JavaDoc
  3. JSF <f:facet /> JavaDoc
  4. JSF 2 resource bundles example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
35 Comment threads
3 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
31 Comment authors
anithaWimLakhan Nandwaniryan MuneneYouth.? Recent comment authors
newest oldest most voted
Lakhan Nandwani
Guest
Lakhan Nandwani

Hi MKyong,

Could you please explain how to apply width attribute in percentage(e.g.width:70%) to component in inside jsf datatable?

I have tried with many ways ( e.g. component attribute,CSS), but it couldn’t work.

ryan Munene
Guest
ryan Munene

i would like to know if the datatable can be added filter function

Youth.?
Guest
Youth.?

So it is use this tag [ Order No ] to add a header~~Thank YOU a lot!

Aman Birjpuriya
Guest
Aman Birjpuriya

Order No #{o.orderNo} Product Name #{o.productName} Price #{o.price} Quantitynjn #{o.qty}

I applied all getterand setter methord but got this as output please help

anitha
Guest
anitha

You could refresh and run starting file like index.xhtml

Doaa
Guest
Doaa

how to use <datascroller ??

sath
Guest
sath

thanks Mkyong… Cheers from Sri lanka ..!

the guest
Guest
the guest

Thx dude!

Elan
Guest
Elan

there is any examples available for data table with pagination

Alan
Guest
Alan

Nice article. Since the article was written, however, there has been a library of classes released that work with DataTables on the Java platform. Check out JED at http://jed-datatables.ca/jed/

rudelaris
Guest
rudelaris

thx! the example help me!

trackback
Fill a datatable with a list in JSF 2.2CopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android doubt, ios question, sql query, sqlite query, nodejsquery, dns query, update que
Amruta
Guest
Amruta

hello sir,

I tried Your JSF 2 DATATABLE Example its Working fine, But Css file is not applying fine

please reply,I m new to JSF.

Thanx in Advance

Vicky
Guest
Vicky

is there any way to add component dynamically on JSP page through which we can take input also. those components should be configurable via DB or some configuration file.

Thanks

Diva
Guest
Diva

you can find some more details in the below in the link,”http://javadomain.in/jsf-datatable-example/”

Viacheslav Sulekov
Guest
Viacheslav Sulekov

Many Thanks!”The Java EE 6 Tutorial vol. I ” is not a tutorial.

Nelson
Guest
Nelson

Hi! how to filter with primefaces datatable?

Jose
Guest
Jose

Thanks!!!!!!!!!!!!Your posts are very interestings an usefuls.

Archik
Guest
Archik

Thanks!!!

nam hai vo
Guest
nam hai vo

thanks great!

Mohamed Uvais
Guest
Mohamed Uvais

Hi, First of all Thanks a lot for giving such a website. What is the use of inside the tag . I know here we are using it for telling the column name. In primefaces column, it has a attribute called headerText through which we can tell the column name. Mydoubt is when i export that entire p:dataTable(which uses ) to excel using dataExpoter in primefaces, the column-name or headerText is not exported. but when i use the f:facet tag in side (in primefaces) the column-name or header-text is exported. so what is the role of this f:facet tag here?… Read more »

Mohamed Uvais
Guest
Mohamed Uvais

Hi, First of all Thanks a lot for giving such a website. What is the use of inside the . I know here we are using it for telling the column name. In primefaces column, it has a attribute called headerText through which we can tell the column name. Mydoubt is when i export that entire p:dataTable(which uses ) to excel using dataExpoter in primefaces, the column-name or headerText is not exported. but when i use the f:facet tag in side (in primefaces) the column-name or header-text is exported. so what is the role of this f:facet tag here? waht… Read more »

pawel
Guest
pawel

why the method “OrderList” is called three times, I think should be called only once. is this a bug?

joy
Guest
joy

I think the element: var=o doesn’t work. You know why ?

I am getting following error..
action=”#{order.deleteAction(o)}” Error Parsing: #{order.deleteAction(o)}

serg
Guest
serg

When I refreshed test page 1 time, getOrderList() called 3 times. Why?

sou2zimate
Guest
sou2zimate

I encountered the same “problem” that getOrderList() get called three times, I found a good explaination here:
http://stackoverflow.com/questions/2090033/why-jsf-calls-getters-multiple-times

trackback
JSF 2.0 Tutorial « java config

[…] JSF 2 dataTable example JSF 2 <h:dataTable>, <h:column> and <f:facet> tags to display data in a HTML table format. […]

Son1
Guest
Son1

Hi,

I apply your tutorial and I have an error :

The error arrives during the redirection on the default.xhtml page

An Error Occurred:
/default.xhtml: The class 'com.AppShop.controller.OrderBean$Order' does not have the property 'orderNo'.

I think the element: var=o doesn’t work. You know why ?

I work on Netbeans 7.1.1.
with JSF 2.0.
and GlassFish 3.1.2.

Son1
Guest
Son1

Sorry I’m a noob !

Just forget to implements getters and setter.

Andre Souza
Guest
Andre Souza

How to change the background color of a cell according to the value contained in it? Any hint or suggestion to do this in JSF 2.0 without using any other framework?
Tks

Lutz
Guest
Lutz

Hi everybody, I’vo got a scrolling problem and I wonder if you can help me. I took the original example, extended the table to be bigger than the screen in hight and width and added scrolling by adding the following to the css: tbody { height: 350px; width: 400px; overflow: auto; } It works fine for vertical scrolling and does not work for horizontal scrolling in the latest version of FireFox (IE I don’t know). Most of the horizontal scrolling is done by the browser and only a tiny portion is done by the css scrollbar. Of course I’d want… Read more »

trackback
JSF 2 repeat tag example

[…] a JSF 2.0 ui:repeat example to render exactly the same HTML output like this h:dataTable example. Compare both and spot the […]