JSF 2 dataTable sorting example

Here’s the idea to sort a JSF dataTable list :

1. Column Header

Put a commandLink in the column header, if this link is clicked, sort the dataTable list.


<h:column>
    <f:facet name="header">
    	<h:commandLink action="#{order.sortByOrderNo}">
    	   Order No
    	</h:commandLink>
    </f:facet>
    #{o.orderNo}
</h:column>

2. Implementation

In the managed bean, uses Collections.sort() and custom comparator to sort the list.


@ManagedBean(name="order")
@SessionScoped
public class OrderBean implements Serializable{

	//sort by order no
	public String sortByOrderNo() {
	    
	   Collections.sort(orderArrayList, new Comparator<Order>() {

		@Override
		public int compare(Order o1, Order o2) {
					
			return o1.getOrderNo().compareTo(o2.getOrderNo());
					
		}
	   });	
	}
	//...
}

dataTable Sorting example

A JSF 2.0 example to implement the sorting feature in dataTable. Click on the “Order No” column header make the list order by “Order No” in ascending order; Click it again, make the list order by “Order No” in descending order.

1. Managed Bean

A managed bean to provide a dummy list for testing, and shows the use of Collections.sort() to sort the dataTable list.


package com.mkyong;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
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 List<Order> orderArrayList;

	private boolean sortAscending = true; 
	
	private static final Order[] orderList = {
		new Order("A0002", "Harddisk 100TB", 
				new BigDecimal("500.00"), 3),
		new Order("A0001", "Intel CPU", 
				new BigDecimal("4200.00"), 6),
		new Order("A0004", "Samsung LCD", 
				new BigDecimal("5200.00"), 10),
		new Order("A0003", "Dell Laptop", 
				new BigDecimal("11600.00"), 9),
		new Order("A0005", "A4Tech Mouse", 
				new BigDecimal("200.00"), 20)
	};
	
	public OrderBean(){

		orderArrayList = new ArrayList<Order>(Arrays.asList(orderList));

	}
	
	public List<Order> getOrderList() {
		 
		return orderArrayList;
 
	}
 
	//sort by order no
	public String sortByOrderNo() {
	    
	   if(sortAscending){
			
		//ascending order
		Collections.sort(orderArrayList, new Comparator<Order>() {

			@Override
			public int compare(Order o1, Order o2) {
					
				return o1.getOrderNo().compareTo(o2.getOrderNo());
					
			}

		});
		sortAscending = false;
			
	   }else{

		//descending order
		Collections.sort(orderArrayList, new Comparator<Order>() {

			@Override
			public int compare(Order o1, Order o2) {
					
				return o2.getOrderNo().compareTo(o1.getOrderNo());
					
			}

		});
		sortAscending = true;
	   }

	   return null;
	}

	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;
		}

		public String getOrderNo() {
			return orderNo;
		}

		public void setOrderNo(String orderNo) {
			this.orderNo = orderNo;
		}

		public String getProductName() {
			return productName;
		}

		public void setProductName(String productName) {
			this.productName = productName;
		}

		public BigDecimal getPrice() {
			return price;
		}

		public void setPrice(BigDecimal price) {
			this.price = price;
		}

		public int getQty() {
			return qty;
		}

		public void setQty(int qty) {
			this.qty = qty;
		}
	}
}

2. dataTable Tag

A JSF page, put a commandLink tag in the “Order No” column header, if click, sort the dataTable list.


<?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:c="http://java.sun.com/jsp/jstl/core"
      >
    <h:head>
    	<h:outputStylesheet library="css" name="table-style.css"  />
    </h:head>
    <h:body>
    	
    	<h1>JSF 2 dataTable sorting example</h1>
		  <h:form>
    		<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>
    			<f:facet name="header">
    			   <h:commandLink action="#{order.sortByOrderNo}">
    				Order No
    			   </h:commandLink>
    			</f:facet>
    			#{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:form>
    </h:body>
</html>

3. Demo

From top to bottom, shows a dataTable list being sorted in ascending and descending order.

jsf2-dataTable-Sorting-Example-1
jsf2-dataTable-Sorting-Example-2
jsf2-dataTable-Sorting-Example-3

Download Source Code

Download It – JSF-2-DataTable-Sorting-Example.zip (10KB)

Reference

  1. using database to sort dataTable list
  2. JSF h:dataTable JavaDoc
  3. JSF 2 link, commandLink and outputLink example
  4. Java object sorting example

About the Author

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

Comments

avatar
9 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
7 Comment authors
Johana KlotzrghvipsOmarPablo Recent comment authors
newest oldest most voted
trackback
JSF 2.0 Tutorials

[…] JSF 2 dataTable sorting example A JSF 2.0 example to show the use of custom comparator to implement the sorting feature in dataTable tag. […]

trackback
JSF 2 dataTable sorting example – DataModel

[…] – DataModel Written on October 26, 2010 at 11:45 am by mkyong In the previous JSF 2 dataTable sorting example, showed the simplest way, a custom comparator to sort a list and display in […]

Tousif Khan
Guest
Tousif Khan

Hi Yong.

How to implement Pagination using JSP2.
please provide some resource.

Jhon Newman
Guest
Jhon Newman

And how do you do with strings?

Pablo
Guest
Pablo

Thanks, this article was very useful.

Omar
Guest
Omar

Hi all, I want to obtain a result like the one in the screenshot below: http://imageshack.us/a/img821/4747/extract.png Basically, I need a data table that contains (dynamically generated) subgroups, each of them displaying rows for the respective items. My requirements are: Each subgroup must have the toggle property. The main data table must fire sort and resize events for the displayed columns: when an event is generated, each subgroup must sort its items (or resize its columns) accordingly. The “plus button” displayed at the right corner in the second subgroup should open a dialog to add a new item within the subgroup… Read more »

vips
Guest
vips

Yong, please put any example of searching the database from textbox or whatever as soon as possible… thanks

rgh
Guest
rgh

Just tried this example with Mojarra 2.2
The first click on the header does indeed sort the table by Order No but clicking a 2nd time doesn’t sort by order number in descending order.
Anyone know why?

Johana Klotz
Guest
Johana Klotz

This doesn’t work properly on my example, I don’t know why. I have a list of 170 custom objects, and when i sort it for the first time, some of the rows are out of order (I checked the arraylist on bean and is sorted correctly there). Anyone?