how to create table with jsf, java and html

Explanation
We all know 'dataTable' component. Its about show some table with some data. Most programmers found the 'h:dataTable' component hard to customize.
There are a lot of 'custom' or 'extended' implementations, that lock you to specific vendor or library. We need more flexibility!
For programmer that used to read and write HTML tags, table-tr-td is common knowledge with tons of examples and tips.

New to Java, JSF, Icefaces? Here is some links to start with:
Why and when use ICEFACES?
First steps with jsf and java

We use simplest HTML tags, together with "ui:repeat" tag, which loops on 'tr' element. Pros: every programmer, even not-jsf, can understand it. CSS is transparent: what you see is what you get. Customization is simple too.
Use you favorite HTML editor, or JSF editor together with CSS tools to customize every aspect of this table, its easy!
This is simplest example, just one table with two columns.
fragment from TableWithLoop.jspx
	<table> 
		<caption>Here is simple table</caption> 
		<tr> 
			<td>Name</td> 
			<td>Phone</td> 
		</tr> 
		<ui:repeat value="#{tableWithLoopBean.rows}" var="row"> 
			<tr> 
				<td><ice:outputText value="#{row.name}" /></td> 
				<td><ice:outputText value="#{row.phone}" /></td> 
			</tr> 
		</ui:repeat> 
	</table> 

This is main entry point. Copy it to you java editor!
com.gpost.jsfexamples.tableWithLoop.TableWithLoopBean
package com.gpost.jsfexamples.tableWithLoop;

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

/*
* Java class for example 'Table with simple html tags'
* referenced as 'tableWithLoopBean' from faces-config.xml, 
* used in 'TableWithLoop.jspx'
*/
public class TableWithLoopBean{

	List<ManWithPhone> rows = null;

	public List<ManWithPhone> getRows() {
		if (rows == null) {
			rows = new ArrayList<ManWithPhone>();
			rows.add(new ManWithPhone("Gary", "1234-6767"));
			rows.add(new ManWithPhone("Bob", "5678-4553"));
		}
		return rows;
	}
} // end of class

This class defines data in row.
com.gpost.jsfexamples.tableWithLoop.ManWithPhone
package com.gpost.jsfexamples.tableWithLoop;

public class ManWithPhone {
	public ManWithPhone(String name, String phone) {
		super();
		this.name = name;
		this.phone = phone;
	}

	String name;
	
	String phone;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}
}


part of faces-config.xml
<managed-bean>
 <managed-bean-name>tableWithLoopBean</managed-bean-name>
 <managed-bean-class>com.gpost.jsfexamples.tableWithLoop.TableWithLoopBean</managed-bean-class>
 <managed-bean-scope>session</managed-bean-scope>

</managed-bean>

conclusion
As we saw in this example, you can create a table with simple html/css, then add some binding to your java bean and you get very flexible data table without 'h:dataTable'.

No comments:

Post a Comment