JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Integrating Spring Web Flow with JSF

November 11, 2010 by Krishna Srinivasan Leave a Comment

Spring Web Flow is a framework that provides abilities to developers to capture the workflow of a web application in the form of configurational constructs called Flows. JSF is a UI framework that provides support for developing complex user interface components along with simplified page navigation rules and event handling. In this article we will discuss about the integration techniques between Spring Web Flow and JSF with the assumption that the readers have a good understanding of these two technologies.

Test application

In this section, we will see the basic artifacts necessary for integrating Spring Web flow with JSF by developing a simple application. Because the idea is to illustrate the integration between Spring Web Flow and JSF, the application does nothing other than displaying a simple JSF invoked from Spring Web Flow. In the later sections of the article, we will see how to use services that makes use of database.

also read:

  1. Introduction to JSF
  2. JSF Interview Questions
  3. Request Processing Lifecycle phases in JSF

Web application deployment descriptor

We will start with defining the deployment descriptor of the application which is given below. Note that the following code snippet contains declarations specific to Spring Web Flow as well as JSF.

[code lang=”java”]<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/spring-fc-config.xml
</param-value>
</context-param>

<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>

<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>true</param-value>
</context-param>

<context-param>
<param-name>facelets.REFRESH_PERIOD</param-name>
<param-value>1</param-value>
</context-param>

<filter>
<filter-name>charEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>charEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>Resources Servlet</servlet-name>
<servlet-class>org.springframework.js.resource.ResourceServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Resources Servlet</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>

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

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>[/code]

The mapping for all the faces requests are handled by the Faces Servlet and the context path containing ‘spring’ is handled by Spring’s Dispatcher Servlet. A listener is configured which will load the application context which is found in the path ‘/WEB-INF/config/spring-fc.xml’.

Spring’s Configuration file

The content of Spring’s configuration file is given below. Note that this file contains a mixture of definitions related to Spring Web Flow and Spring MVC although it is possible to segregate them.

[code lang=”java”]<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:webflow="http://www.springframework.org/schema/webflow-config"
xmlns:faces="http://www.springframework.org/schema/faces"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/webflow-config
http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
http://www.springframework.org/schema/faces
http://www.springframework.org/schema/faces/spring-faces-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<webflow:flow-executor id="flowExecutor">
</webflow:flow-executor>

<webflow:flow-registry id="flowRegistry" flow-builder-services="facesFlowBuilderServices">
<webflow:flow-location path="/WEB-INF/flows/test.xml" />
</webflow:flow-registry>

<faces:flow-builder-services id="facesFlowBuilderServices" />

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/test=flowController
</value>
</property>
<property name="defaultHandler">
<bean class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
</property>
</bean>

<bean id="flowController" class="org.springframework.webflow.mvc.servlet.FlowController">
<property name="flowExecutor" ref="flowExecutor"/>
</bean>

<bean id="faceletsViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.faces.mvc.JsfView"/>
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".xhtml" />
</bean>

</beans>[/code]

We have defined the Spring Web Flow’s flow Controller that is responsible for creating the flow definitions by loading the flows from the file ‘/WEB-INF/flows/test.xml’. We have defined URL based mapping of requests by defining ‘SimpleUrlHandlerMapping’. Note that for JSf integration, the declaration of ‘faces:flow-builder-services’ is necessary.

Faces Configuration file

[code lang=”java”]<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
"http://java.sun.com/dtd/web-facesconfig_1_0.dtd">

<faces-config>
<application>
<!– Enables Facelets –>
<view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
</application>
</faces-config>[/code]

In the above faces configuration file, we have explicitly instructed to make use of Faceets as the view technology instead of JSF. Also note that the managed beans declarations and the navigation rules will simply go off and won’t be required at all as part of the integration since it will be taken care by Spring Web Flow itself.

Welcome file

The welcome file mentioned in the Web application’s deployment descriptor is ‘index.htm’ whose contents is given below.

[code lang=”java”]<html>
<head>
<meta http-equiv="Refresh" content="0; URL=spring/start">
</head>
</html>[/code]

Note that it re-directs the control to the url mapping which will be handled by Spring’s dispatcher servlet.

Flow Definition file

The code snippet for the flow definition file is given below. Remember that the below definitions will be loaded by Spring Web Flow’s Flow Controller as we have configured a context listener in the web.xml file.

[code lang=”java”]<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

<view-state id="test">
</view-state>

</flow>[/code]

There is only one state defined which is ‘test’. So, when the flow is invoked, the framework will look out for a file called ‘test.xhtml’ in the directory ‘/WEB-INF/flows’ as that is how we have configured the view resolver in the Spring’s application context file.

[code lang=”java”]<bean id="faceletsViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.faces.mvc.JsfView"/>
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".xhtml" />
</bean>[/code]

Sample Facelets file

The sample facelets file is given below. Note that it really does nothing other than displaying information message to the user. Also note that in the below file we are making use of templates and the name of the template file is ‘template.xhtml’.

[code lang=”java”]<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>

<ui:composition template="../template.xhtml">

<ui:define name="heading">
</ui:define>

<ui:define name="body">
Sample page which illustrates the integration between JSF and Spring Web Flow
</ui:define>

</ui:composition>

</body>
</html>[/code]

Starting Page

Note that this is the page that will be invoked at startup and from here the control resumes back to Spring Web flow for displaying the page ‘test.xhtml’.

[code lang=”java”]<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:sf="http://www.springframework.org/tags/faces"
template="template.xhtml">

<ui:define name="heading">
</ui:define>

<ui:define name="body">
<div align="left">
<p align="left">
<a href="test">Click here to invoke the Facelets page</a>
</p>
</div>
</ui:define>
</ui:composition>[/code]

Running the application

When the application is invoked, the welcome.html is invoked which redirects the control with the url pattern ‘spring/start’ which will ultimately invoke the file start.xhtml. From here, when the user clicks the link, the url ‘test’ will be mapped to test.xhtml file present in the directory ‘/WEB-INF/flows’. Running the above application will result in something like the following.

Sample application

That’s it. We have run the first sample application that integrates Spring Web Flow and JSF.

Making use of model

In this section, we will extend the knowledge that we gained in the last section by writing a simple search application that will perform search on a list of employees. When running the application, the interface will prompt the user to provide the name of the employee and will do the search accordingly. For brevity, we will omit the code snippets for the most commonly used files such as web.xml, faces-config.xml etc in this section.

Flow Definition file

The content of the flow definition file is given below. Note that the file also illustrates the usage of flow variables and flow transitions.

[code lang=”java”]<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

<var name="employeeSearchCriteria" class="net.javabeat.spring.webflow.jsf.search.employee.EmployeeCriteria" />

<view-state id="showSearchPage">
<transition on="searchEmployee" to="showSearchResults">
</transition>
</view-state>

<view-state id="showSearchResults">
<on-render>
<evaluate expression="employeeSearchService.findEmployees(employeeSearchCriteria)"
result="viewScope.allEmployees" result-type="dataModel" />
</on-render>
</view-state>

</flow>[/code]

We have declared a flow variable ’employeeSearchCriteria’ of type ‘EmployeeCriteria’ and have used this in one of the state definitions. Initially the state ‘showSearchPage’ will be set which will display a simple facelets page for collecting the search parameter which is the ‘name of the employee’. When the user clicks the search button, then a transition occurs, which changes the state to ‘showSearchResults’. Note that the state ‘showSearchResults’ in turn will map to a facelets page that will display the results of the search. For finding out the matching employees, we have used the ‘findEmplyees’ service defined on the object ’employeeSearchService’ and the results were stored in the variable ‘allEmployees’. We will look into the contents of both the facelets files in the next section.

Search Page

The content of the search page is given below. As you can see, it provides a simple form for collecting the name of the employee as the search criteria from the user.

[code lang=”java”]<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:sf="http://www.springframework.org/tags/faces">
<body>

<ui:composition template="../template.xhtml">

<ui:define name="heading">
<p>Employee Search Page</p>
</ui:define>

<ui:define name="body">
<h:form id="mainForm">
<h:outputLabel for="searchString">Search Employee:</h:outputLabel>
<sf:clientTextValidator promptMessage="Search employees by name">
<h:inputText id="empName" value="#{employeeSearchCriteria.empName}" />
</sf:clientTextValidator>
<br/><br/>
<sf:commandButton id="searchEmployees" value="Find Employees" processIds="*" action="searchEmployee" />
</h:form>
</ui:define>

</ui:composition>

</body>
</html>[/code]

Also note that the name of the action is ‘searchEmployee’ which happens to be the identifier for the state transition in the flow definition file. We have bound the user inputs to the model object ‘EmployeeSearchCriteria’ which we will be looking at shortly.

Search Results Page

This page will display the search results to the user. We are making use of the ‘dataTable’ element for displaying the results. Note that when the action is triggered, we use the search service for finding out the list of employees matching the criteria and the results of the search are stored in the flow variable ‘allEmployees’.

[code lang=”java”]<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:sf="http://www.springframework.org/tags/faces">
<body>

<ui:composition template="../template.xhtml">

<ui:define name="heading">
<h2>Search Results</h2>
</ui:define>

<ui:define name="body">

<h:dataTable id="allEmployees" var="employee" value="#{allEmployees}" cellspacing="0" cellpadding="0" border="1">
<h:column>
<f:facet name="header">Emp Id</f:facet>
<h:outputText value="#{employee.id}" align="left" />
</h:column>
<h:column>
<f:facet name="header">Name</f:facet>
<h:outputText value="#{employee.name}" align="left" />
</h:column>
<h:column>
<f:facet name="header">Date of Birth</f:facet>
<h:outputText value="#{employee.dob}" align="left" />
</h:column>
<h:column>
<f:facet name="header">Designation</f:facet>
<h:outputText value="#{employee.designation}" align="left" />
</h:column>
</h:dataTable>

<p align="left">
<a href="search">Search Again</a>
</p>

</ui:define>

</ui:composition>

</body>
</html>[/code]

Within the ‘dataTable’ element, we iterate over the search results for displaying the various properties of an employee such as id, name, date of birth. We still haven’t looked into the Employee model that we used in the above page which we will be discussing it shortly.

Employee Model object

The definition of the employee object is given below. The model comprises several properties such as id, name, date of birth and designation for an employee.

[code lang=”java”]package net.javabeat.spring.webflow.jsf.search.employee;

import java.io.Serializable;
import java.util.Date;

public class Employee implements Serializable{

private String id;
private String name;
private Date dob;
private String designation;

public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {
this.designation = designation;
}

public Date getDob() {
return dob;
}

public void setDob(Date dob) {
this.dob = dob;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

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

}[/code]

Employee Search Criteria

If we could remember, in the employee search page, we use binding for collecting the user parameters in a model object which happens to be ‘EmployeeCriteria’, the definition of which is given below. Note that this is the object that will be passed to the Employee Service for finding out the matching employees.

[code lang=”java”]package net.javabeat.spring.webflow.jsf.search.employee;

import java.io.Serializable;

public class EmployeeCriteria implements Serializable{

private static final long serialVersionUID = 1L;
private String empName;

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

}[/code]

Employee Search Service

The search service for employee object is given below. Note that we are not performing real-time search by hitting the database for finding out the matching employees, instead we create and load dummy employee objects and search against them.

[code lang=”java”]package net.javabeat.spring.webflow.jsf.search.employee;

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

public class EmployeeSearchService {

private static List<Employee> allEmployees;

public List<Employee> findEmployees(EmployeeCriteria criteria){

List<Employee> searchedEmployees = new ArrayList<Employee>();
if (criteria == null){
return allEmployees;
}

String searchEmpName = criteria.getEmpName();
if (searchEmpName != null && searchEmpName.trim().length() > 0){

for (Employee anEmployee : allEmployees){

if (anEmployee.getName().contains(searchEmpName)){
searchedEmployees.add(anEmployee);
}
}
return searchedEmployees;
}else{
return allEmployees;
}
}

static{

allEmployees = new ArrayList<Employee>();
allEmployees.add(employee("10000", "Steve Clark", new Date(1960, 6, 12), "Employee"));
allEmployees.add(employee("10000", "Alfred Ray", new Date(1954, 4, 17), "Manager"));
allEmployees.add(employee("10000", "Robert Woulsh", new Date(1944, 2, 16), "Director"));
}

static Employee employee(String id, String name, Date dob, String designation){

Employee employee = new Employee();
employee.setId(id);
employee.setName(name);
employee.setDob(dob);
employee.setDesignation(designation);
return employee;
}
}[/code]

The above method findEmpoyees() was used in the expression definition for finding out the matched employees against the search criteria.

Running the application

Running the above application will display the following page for collecting the user input – i.e the name of the employee to be searched.

Employee search interface

After entering the name and clicking the ‘Find Employees’ button will taken to the search results page which is given below.

Employee search results

Interacting with the database

In this section, we will see how to integrate database in an application that runs on a Spring Web Flow and JSF framework. We will develop an application that provides an interface for adding book to a book store, since the purpose of the application is to demonstrate the integration of database; we will keep the functionality of this application as simple as possible.

Spring’s Configuration file

Other than the definitions that are related to Spring Web Flow and JSF, we have included lot many bean definitions which are related to persistence. For example, we have used the declarations ‘annotation-config’ that indicate that our persistent entities will be making use of annotations and all such entities which are present in the package ‘net.javabeat.spring.webflow.jsf.book’ has to be automatically scanned.

[code lang=”java”]<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:webflow="http://www.springframework.org/schema/webflow-config"
xmlns:faces="http://www.springframework.org/schema/faces"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/webflow-config
http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
http://www.springframework.org/schema/faces
http://www.springframework.org/schema/faces/spring-faces-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<context:annotation-config />
<context:component-scan base-package="net.javabeat.spring.webflow.jsf.book" />

<webflow:flow-executor id="flowExecutor">
<webflow:flow-execution-listeners>
<webflow:listener ref="jpaFlowExecutionListener" />
</webflow:flow-execution-listeners>
</webflow:flow-executor>

<webflow:flow-registry id="flowRegistry" flow-builder-services="facesFlowBuilderServices">
<webflow:flow-location path="/WEB-INF/flows/bookMain.xml" />
</webflow:flow-registry>

<faces:flow-builder-services id="facesFlowBuilderServices" />

<bean id="jpaFlowExecutionListener" class="org.springframework.webflow.persistence.JpaFlowExecutionListener">
<constructor-arg ref="entityManagerFactory" />
<constructor-arg ref="transactionManager" />
</bean>

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/bookMain=flowController
/bookSearchPage=flowController
/bookAdd=flowController
</value>
</property>
<property name="defaultHandler">
<bean class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
</property>
</bean>

<bean id="flowController" class="org.springframework.webflow.mvc.servlet.FlowController">
<property name="flowExecutor" ref="flowExecutor"/>
</bean>

<bean id="faceletsViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.faces.mvc.JsfView"/>
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".xhtml" />
</bean>

<tx:annotation-driven />

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:mem:book" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>

</beans>[/code]

Integrating of database specific code happens through the declaration of the ‘jpaFlowExcutionListener’ that happens as part of flow execution. We have made use of HSQL in-memory database through the ‘dataSource’ definition and the same is referred in ‘entityManagerFactory’ which is again referred in Spring’s transaction manager. Note that JPA Flow Execution listener needs a reference to Entity Manager’s factory and a reference to the transaction manager.

Persistence Configuration file

The persistence configuration file has to be placed in ‘META-INF’ directory which in turn has to be in the application’s classpath.

[code lang=”java”]<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="bookDatabase">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>net.javabeat.spring.webflow.jsf.book.Book</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider"/>
</properties>
</persistence-unit>
</persistence>[/code]

Book Entity

The declaration of the Book Entity is given below. Note that for indicating that the Book class is an Entity, we have annotated using @Entity.

[code lang=”java”]package net.javabeat.spring.webflow.jsf.book;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Book implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String category;
private String author;
private double price;

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public String getCategory() {
return category;
}

public void setCategory(String category) {
this.category = category;
}

public String getName() {
return name;
}

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

public double getPrice() {
return price;
}

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

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
if (!(object instanceof Book)) {
return false;
}
Book other = (Book) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "net.javabeat.spring.webflow.jsf.book.Book[id=" + id + "]";
}

}[/code]

We have also declared properties such as name of the book, book’s author, the categotry of book as well as its price.

Book Service interface

The book service interface that is used for creating and searching books is given here. Note that the method createBook() will be used when the user is attempting to create a new book. Similarly the methods findAllBooks() and findBooks() can be used for searching books.

[code lang=”java”]package net.javabeat.spring.webflow.jsf.book;

import java.util.List;

public interface BookService {

List<Book> findAllBooks();

List<Book> findBooks(BookSearchCriteria criteria);

void createBook(String name, String category, String author, double price);

}[/code]

Book Service Implementation

The service implementation for the book service interface is given below. Remember that we make use of JPA API for persisting entity information into the HSQL database. Also note the usage of the annotations @Service and @Repository. To indicate that the DAO class is a repository for Book objects, we have used the annotation @Repository.

[code lang=”java”]package net.javabeat.spring.webflow.jsf.book;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("bookService")
@Repository
public class BookServiceImpl implements BookService {

private EntityManager em;

@PersistenceContext
public void setEntityManager(EntityManager em){
this.em = em;
}

@Transactional(readOnly=true)
public List<Book> findAllBooks() {
Query query = em.createQuery("select book from Book book");
List<Book> results = query.getResultList();

if (results == null || results.size() == 0){
createTestBooks();
return query.getResultList();
}else{
return results;
}
}

private void createTestBooks(){

createBook("Java Programming", "Technical", "James", 1110.00);
createBook("Life After Death", "Spiritual", "Unknown", 3140.00);
createBook("All About Numerology", "Numerolgy", "Richard", 6130.00);
}

@Transactional(readOnly=true)
public List<Book> findBooks(BookSearchCriteria criteria) {

if (criteria == null){
return findAllBooks();
}

String name = criteria.getName();
String author = criteria.getAuthor();

String query = "select book from Book";
if (name != null && name.trim().length() > 0){
query = query + " where upper(book.name) = :name ";
}

if (author != null && author.trim().length() > 0){
if (query.contains("where")){
query = query + " and ";
}else{
query = query + "where ";
}
query = query + " upper(book.author) = :author ";
}

Query queryObject = em.createQuery(query);
queryObject.setParameter("name", name);
queryObject.setParameter("author", author);

List<Book> results = queryObject.getResultList();
if (results == null || results.size() == 0){
createTestBooks();
}
return queryObject.getResultList();
}

@Transactional(readOnly=true)
public void createBook(String name, String category, String author, double price) {

Book book = new Book();
book.setName(name);
book.setCategory(category);
book.setAuthor(author);
book.setPrice(price);
em.persist(book);
}
}[/code]

Flow Definition file

The flow definition file is given below and the flow is quite simple. The application will display a main page ‘bookPage’ that displays a form for creating a new book. In the same page, a separate section is available that displays the list of available books by fetching them from the database.

[code lang=”java”]<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

<var name="bookSearchCriteria" class="net.javabeat.spring.webflow.jsf.book.BookSearchCriteria" />

<view-state id="bookMain">
<on-render>
<evaluate expression="bookService.findAllBooks()" result="viewScope.allBooks" result-type="dataModel" />
</on-render>
<transition on="addBooks" to="bookAdd">
</transition>
</view-state>

<view-state id="bookAdd">
<on-render>
<evaluate expression="bookService.createBook(bookSearchCriteria.name, bookSearchCriteria.category,
bookSearchCriteria.author, bookSearchCriteria.price)"/>
</on-render>
</view-state>

</flow>[/code]

When the user tries to create a book, then the state transition happens and the control gets transferred to the state definition ‘bookAdd’ and finally the service ‘createBook’ is called for creating a book. Also when the page gets loaded, we call the service findAllBooks() that fetches all book objects from the database for display. Running the application will display an interface similar to the following

Book Management Page

Conclusion

This article provided three sample applications that illustrated the techniques on making up an application that makes use of Spring Web Flow and JSF technologies. The first sample application provided a basic startup in illustrating the various pieces of artifacts required for supporting the integration. The second application illustrated the usage of flow variables, flow transitions by providing an employee search application. The final sample application explained the process of integration with the database by providing various configurations specific to JPA and Entities.

Filed Under: JSF Tagged With: JSF, Spring Web Flow

Introduction to Facelets

September 26, 2010 by Krishna Srinivasan Leave a Comment

Introduction

This article will provide an introduction to the Facelets framework with the assumption that the readers have a basic understanding on Java Server Pages. With the Introduction of JSF, the idea is to make JSP as the view technology for JSF. However the architecture of JSF and JSP are completely different and there were integration issues with the combination of JSF and JSP. With this in mind, Facelets was introduced which is another view definition framework similar to JSP. However, the architecture of the Facelets was designed with the complex JSF architecture and life-cycle in mind so that the component trees construction of Facelets can nicely mingle with JSF. Also in comparision with JSF, facelets can provide extending re-use of content code through templates.

also read:

  • Introduction to JSF
  • JSF Interview Questions
  • Request Processing Lifecycle phases in JSF

Hello World Application

In this section, we will look into a starter application that will display the text Hello in the browser. The application will make the view as Facelets instead. We will provide explanation with the various aspects while going through the snippet code in the relevant section.

JSP Page

In the example application, the web application deployment descriptor is configured to look up for the file hello.jsp. The following is the code listing for the file hello.jsp. The page does a forward to the file hello.jsf. The extension of the forward file is ‘.jsf’ and in the application’s deployment descriptor (which we will be seeing in the next section), we will see such requests forwarded to the Faces Servlet.
hello.jsp
[code lang=”html”]
<%@page contentType="text/html" pageEncoding="UTF 8"%>
<jsp:forward page="hello.jsf"/>
[/code]

Facelets Page

The code listing for the facelets page is given below. Once we can see that the following page has the extension .xhtml. Later on we will see how to map this extension to a Facelets page. Also within the page we have included the namespace uri ‘http://java.sun.com/jsf/facelets’ so that we can refer to Facelets related tags in the page.
Hello.xhtml
[code lang=”html”]
<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>

<ui:composition template="/template.xhtml">

<ui:define name="heading">
Hello world application(Heading area)
</ui:define>

<ui:define name="body">
Hello World1! (Body area)
</ui:define>

</ui:composition>

</body>
</html>[/code]
In the above page, we have included the ui:composition and ui:define tags. The ui:composition along with the template attribute instructs that we want to use the page referenced in the attribute as the template page. The template page that we will look in the following section defines the section for the title content and the body content through ‘h1’ (heading) and ‘p’ (body) contents. The logical names given for the heading and the body content are ‘heading’ and ‘body’. Now back to the ‘hello.xhtml’, it is always possible to define or override the logical named sections in the template page. In our case, we have overridden the sections ‘heading’ and ‘body’ with some simple customized content through ui:define tags.

Template.xhtml

One could remember the usage of template.xhtml is the previous section, the content being giving in the following section. As discussed, this template page has provided named logical sections for the heading and the body area. It does this definition with the usage of ui:insert tags. Once this template page is defined, it is possible to override the named logical sections. For example, if the logical section ‘heading’ is not defined in the template-client page, i.e. the template page used by some client, in our case this file is hello.xhtml, then the content in the template.xhtml will be displayed.
template.xhtml
[code lang=”html”]<?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:ui="http://java.sun.com/jsf/facelets">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facelets – Template Example</title>
<link href="./css/default.css" rel="stylesheet" type="text/css" />
</head>

<body>
<h1>
<ui:insert name="heading">Default Heading area to be overriden</ui:insert>
</h1>
<p>
<ui:insert name="body">Default body area to be overriden</ui:insert>

</body>

</html>[/code]

Web Application deployment Descriptor

The web application’s deployment descriptor file is given below. As you can see in the snippet code, the requests ending with ‘*.jsf’ are mapped to Faces Servlet. But till now we haven’t specified how Facelets is coming into the picture. We will see it shortly.
web.xml
[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">
<context-param>
<param-name>com.sun.faces.verifyObjects</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.validateXml</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>facelets.SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>

<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>*.jsf</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>
30
</session-timeout>
</session-config>

<welcome-file-list>
<welcome-file>hello.jsp</welcome-file>
</welcome-file-list>
</web-app>[/code]
Also, there are various parameters defined with respect to the Faces Servlet. Significant parameters being the development mode (represented through facelets.DEVELOPMENT) which when set to true instructs the framework that the application is still in development and any errors during page requests will be displayed in the browser.

Sun-web.xml

The vendor specific application’s deployment descriptor is given below. It defines the context name of the application set to Facelets-Helo
sub-web.xml
[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd">
<sun-web-app error-url="">
<context-root>/Facelets-Hello</context-root>
</sun-web-app>[/code]

Faces Configuration file

The view handler for JSF is implemented through ViewHandler. To ensure that our application is using the View definition framework of Facelets, all we have to do is to replace the JSF version of View Handler with the Facelets view which happens to be ‘com.sun.facelets.FaceletViewHandler’ in the configuration file.
faces-config.xml
[code lang=”java”]<?xml version=’1.0′ encoding=’UTF-8′?>

<faces-config version="1.2"
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">

<application>
<view-handler>
com.sun.facelets.FaceletViewHandler
</view-handler>
</application>

</faces-config>[/code]

Facelets – Hello Application.

Templates in Facelets

In this section, we will extend the hello application to develop a simple web-site’s home page that will display the header, footer and other areas. We will see the real power of Facelets template in this section.

Footer Page

First, we will define the footer for the web-page. Note that usually the footer area will be common across all the pages within the web-site. So it would be wise to define the contents of the footer in page and reuse it wherever necessary.
footer.xhtml
[code lang=”html”]<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<div style="background-color: #82CAFA; color: #FFFFFF; width: 100%;">@<pre lang="LANGUAGE" line="1" lang="LANGUAGE" line="1" (2004-2010),India</div>
</body>
</html>[/code]

Header Page

The code listing for the header page is given below in the file header.xhtml. The header page provides welcome information to the users and it is expected that this page will be getting referenced in multiple pages.
header.xhtml
[code lang=”html”]<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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">
<body>
<div style="background-color: #82CAFA; color: #FFFFFF; width: 100%;">
Welcome to <pre lang="LANGUAGE" line="1" lang="LANGUAGE" line="1"
</div>
</body>
</html>[/code]

Template Page

In this section, we will see the template page definition for a page. This template will provide the logical view definitions for header, footer, left side navigation menu, right side navigation menu and the contents. Note that it is usually the content area which used to be different across pages.
template.xhtml
[code lang=”html”]
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">

<head>
<title>Facelets example</title>
</head>

<body >
<div style="border-bottom: grey; border-left: grey; border-right: grey; border-top: grey; height: 100%;text-align: center; width: 100%;">
<ui:insert name="header">
<ui:include src="header.xhtml" />
</ui:insert>
</div>

<table width="100%" >
<tr>
<td width="20%">

<div style="background-color: #82CAFA; color: #FFFFFF;height: 250px; width: 100%;text-align: center;">
<br/>
<ui:insert name="leftSideMenu">
<h:form>
<h:commandLink value="Home"></h:commandLink>
<br/><br/>
<h:commandLink value="News"></h:commandLink>
<br/><br/>
<h:commandLink value="Articles"></h:commandLink>
<br/><br/>
<h:commandLink value="About Us"></h:commandLink>
<br/><br/>
</h:form>
</ui:insert>
</div>
</td>

<td width="60%">
<div style="background-color: #82CAFA;text-align: center;">
<ui:insert name="content">Content displayed from Template </ui:insert>
</div>
</td>
<td width="20%">
<div style="background-color: #82CAFA; color: #FFFFFF;height: 250px; width: 100%;text-align: center;">
<br/>
<ui:insert name="righSideMenu">
<h:form>
<h:commandLink value="Java"></h:commandLink>
<br/><br/>
<h:commandLink value="J2EE"></h:commandLink>
<br/><br/>
<h:commandLink value="Spring"></h:commandLink>
<br/><br/>
<h:commandLink value="Hibernate"></h:commandLink>
<br/><br/>
</h:form>
</ui:insert>
</div>
</td>
</tr>
</table>

<div style="border-bottom: grey; border-left: grey; border-right: grey; border-top: grey; height: 100%;text-align: center; width: 100%;">
<ui:insert name="footer">
<ui:include src="footer.xhtml" />
</ui:insert>
</div>
</body>

</html>[/code]
In the above template page, we have defined logical sections through the ‘ui:insert’ tags. The named logical areas that we have defined for the header, footer, left side navigation menu, right side navigation menu, content are ‘header’, ‘footer’, ‘leftSideMenu’, ‘rightSideMenu’, and ‘content’ respectively. Note that we have made use of the ‘ui:insert’ tag for the header and the footer tags which is used a resource. The resources happen to the header.xhtml and footer.xhtml that we had discussed previously.

Home Page

Now that we have looked into the template page that defines the header, footer and others, we will look into the definition of a template-client page. One such page that uses the template page is the homepage.xhtml, the code listing for which is given below.
homepage.xhtml
[code lang=”html”]<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<ui:composition template="templates/template.xhtml">

<ui:define name="content">
Welcome to <pre lang="LANGUAGE" line="1" lang="LANGUAGE" line="1"… Here you can see references <br/> to Articles, Tips and Mock Questions for Java, J2EE,<br/> Spring, Hibernate and other platform.<br/>
</ui:define>

</ui:composition>

</html>[/code]
In the above page, we have defined the ui:composition tag whose template attribute points to the template.xhtml page that we created just before. Note that we want to keep the original definition of the header, footer, left navigation menu and the right navigation menu. However, we want to override the definition of the content area. To achieve that, we have used the ui:define tag which overrides the default content with the one relevant to the home page.

Facelets – Templates Demo Application.

UI Components and Backing Beans

In this section, we will introduce the new tag ‘ui:component’ which is used to introduce a new component in the component’s root hierarchy. Also we will introduce the usage of backing beans in facelets. In the last example that we introduced, if we recall, the template page defined the left side menu items and the right side menu items. The content of the menu items is hard-coded. Now in this section, we will see how to pass the list of items to be displayed in the template page for better reuse.

Menu Item

We will define the model object for the displayable menu item. The model object defines the name of the menu item as well as the url. For simplicity, we will ignore the value of the url propery. Here is the listing for the java model MenuItem.
MenuItem.java
[code lang=”java”]
package net.articles.facelets;

public class MenuItem {

private String url;
private String name;

public MenuItem(String url, String label) {
this.url = url;
this.name = label;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}[/code]

Backing Bean

We will look into the definition of the backing bean in the following section. In our application, backing bean is used to store the contents of the menu items to be displayed in the left side as well as in the right side.
MenuBackingBean.java
[code lang=”java”]
package net.articles.facelets;
import java.util.ArrayList;
import java.util.List;

public class MenuBackingBean {

private List<MenuItem> leftSideMenuItems;
private List<MenuItem> rightSideMenuItems;

public List<MenuItem> getLeftSideMenuItems() {

if (leftSideMenuItems == null || leftSideMenuItems.size() == 0){
leftSideMenuItems = new ArrayList<MenuItem>();
leftSideMenuItems.add(new MenuItem("home.xhtml", "Home"));
leftSideMenuItems.add(new MenuItem("news.xhtml", "News"));
leftSideMenuItems.add(new MenuItem("articles.xhtml", "Articles"));
leftSideMenuItems.add(new MenuItem("certifications.xhtml", "Certifications"));
leftSideMenuItems.add(new MenuItem("bookstore.xhtml", "Book Store"));
leftSideMenuItems.add(new MenuItem("feeds.xhtml", "Feeds"));
leftSideMenuItems.add(new MenuItem("about.xhtml", "About Us"));
}
return leftSideMenuItems;
}

public void setLeftSideMenuItems(List<MenuItem> leftSideMenuItems) {
this.leftSideMenuItems = leftSideMenuItems;
}

public List<MenuItem> getRightSideMenuItems() {
if (rightSideMenuItems == null || rightSideMenuItems.size() == 0){
rightSideMenuItems = new ArrayList<MenuItem>();
rightSideMenuItems.add(new MenuItem("java.xhtml", "Java"));
rightSideMenuItems.add(new MenuItem("j2ee.xhtml", "J2EE"));
rightSideMenuItems.add(new MenuItem("spring.xhtml", "Spring"));
rightSideMenuItems.add(new MenuItem("hibernate.xhtml", "Hibernate"));
rightSideMenuItems.add(new MenuItem("struts.xhtml", "Struts"));
rightSideMenuItems.add(new MenuItem("jsf.xhtml", "JSF"));
rightSideMenuItems.add(new MenuItem("ejb.xhtml", "EJB"));
}
return rightSideMenuItems;
}

public void setRightSideMenuItems(List<MenuItem> rightSideMenuItems) {
this.rightSideMenuItems = rightSideMenuItems;
}
}[/code]
Have a look at the definition of the methods getLeftSideMenuItems() and getRightSideMenuItems(). We have checked for the emptiness of the collection and if found to be empty, have initialized the collection with some values before returning it.

Template page

Have a look at the modified version of the template page. It no longer defines the content of the left side and the right side menu items. Instead it defines the logical area for the left side and the right side menu items and leaves it for the template client to be overridden.
template.xhtml
[code lang=”html”]
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">

<head>
<title>Facelets example</title>
</head>

<body >
<div style="border-bottom: grey; border-left: grey; border-right: grey; border-top: grey; height: 100%;text-align: center; width: 100%;">
<ui:insert name="header">
<ui:include src="header.xhtml" />
</ui:insert>
</div>

<table width="100%" >
<tr>
<td width="20%">

<div style="background-color: #82CAFA; color: #FFFFFF;height: 250px; width: 100%;text-align: center;">
<br/>
<ui:insert name="leftSideMenu">
</ui:insert>
</div>
</td>

<td width="60%">
<div style="background-color: #82CAFA;text-align: center;">
<ui:insert name="content">Content displayed from Template </ui:insert>
</div>
</td>

<td width="20%">
<div style="background-color: #82CAFA; color: #FFFFFF;height: 250px; width: 100%;text-align: center;">
<br/>
<ui:insert name="rightSideMenu">
</ui:insert>
</div>
</td>

</tr>
</table>

<div style="border-bottom: grey; border-left: grey; border-right: grey; border-top: grey; height: 100%;text-align: center; width: 100%;">
<ui:insert name="footer">
<ui:include src="footer.xhtml" />
</ui:insert></div>
</body>

</html>[/code]
Note that the logical area defined for the left side and the right side menu are ‘leftSideMenu’ and ‘rightSideMenu’ respectively.

Home Page

Here is the revised version of the home page. Not that it is upto the home page now to give the definition for the left side and the right side menu items. It does so by overriding the logical named areas ‘leftSideMenu’ and ‘rightSideMenu’ through ui:define tags.
homePage.xhtml
[code lang=”html”]
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<ui:composition template="templates/template.xhtml">

<ui:define name="leftSideMenu">
<ui:include src="menuItems.xhtml" >
<ui:param name="menus" value="#{menuBackingBean.leftSideMenuItems}"/>
</ui:include>
</ui:define>

<ui:define name="content">
Welcome to <pre lang="LANGUAGE" line="1" lang="LANGUAGE" line="1"… Here you can see references <br/>
to Articles, Tips and Mock Questions for Java, J2EE,<br/>
Spring, Hibernate and other platform.<br/>
</ui:define>

<ui:define name="rightSideMenu">
<ui:include src="menuItems.xhtml" >
<ui:param name="menus" value="#{menuBackingBean.rightSideMenuItems}"/>
</ui:include>
</ui:define>

</ui:composition>
</html>[/code]
Have a look at the implementation of the menu items. It makes an inclusion of the generic menuItems.xhtml page through the ui:include tag. Because the content of the left side and right side menu items is going to vary, the menuItems.xhml is passed with the parameter ‘menus’ through the tag ‘ui:param’. This means that the referencing page menuItems.xhtml can make use of the named parameter ‘menus’.

Menu Items

Here is the code snippet for the menuItems.xhtml. Note that this page defines a new component through ui:component tag. Note that the implementation iterates over the parameter passed, which is a collection, to get a reference to the MenuItem object. It then makes use of the properties name and url for getting displayed as a link.
MenuItem.xhtml
[code lang=”html”]
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jstl/core">

<ui:component>
<c:forEach var="menuItem" items="#{menus}">
<a href="#{menuItem.url}">#{menuItem.name}</a><br/>
</c:forEach>
</ui:component>

</html>[/code]

Facelets – Templates Demo Application.

Writing Custom Tags

In the final section of the article, we will see how to write custom tag definitions using Facelets. We will extend the display of the menu items as a custom tag. As with all tag definition frameworks, writing custom tag invokes the declaration of the tag in an xml file, providing the implementation of the tag and then finally using it in a client page.

Tag Definition

Here is the listing for the tag definition. It defines two tags ‘verticalMenu’ and ‘horizontalMenu’ in the namespace ‘http://<pre lang="LANGUAGE" line="1" lang="LANGUAGE" line="1".net/facelets'. The source for the two tags comes from 'verticalMenu.xhtml' and 'horizontalMenu.xhtml' file. These files contain the implementation of the two tags.
Tag Definition
[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems,
Inc.//DTD Facelet Taglib 1.0//EN" "facelet-taglib_1_0.dtd" >
<facelet-taglib>

<namespace>http://<pre lang="LANGUAGE" line="1" lang="LANGUAGE" line="1".net/facelets</namespace>

<tag>
<tag-name>verticalMenu</tag-name>
<source>../tags/verticalMenu.xhtml</source>
</tag>

<tag>
<tag-name>horizontalMenu</tag-name>
<source>../tags/horizontalMenu.xhtml</source>
</tag>

</facelet-taglib>[/code]

Vertical Menu

In the implementation of the tag ‘verticalMenu’, we have imitated that logic that we used in the last section which iterates over the collection for displaying the menu items horizontally.
verticalMenu.xhtml
[code lang=”html”]
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jstl/core">

<ui:component>
<c:forEach var="menuItem" items="#{menus}">
<a href="#{menuItem.url}">#{menuItem.name}</a>
<br/>
</c:forEach>
</ui:component>

</html>[/code]

Horizontal Menu

Similarly for the implementation of the tag ‘horizontalMenu’, we have ensured that the menu items are displayed horizontally leaving the line break tag.
horizontalMenu.java
[code lang=”html”]
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jstl/core">

<ui:component>
<c:forEach var="menuItem" items="#{menus}">
<a href="#{menuItem.url}">#{menuItem.name}</a>
</c:forEach>
</ui:component>

</html>[/code]

Tag Inclusion

Once these tags are defined, the application’s deployment descriptor has to be updated with the tag definition file so that the application accessing the tag has the visibility. The code snippet for the inclusion of the tag definition file is given below.

[code lang=”xml”]
<context-param>
..
<param-name>facelets.LIBRARIES</param-name>
<param-value>/WEB-INF/facelets/custom.xml</param-value>
..
</context-param>[/code]

Home Page

The final version of the home page making use of the custom tag is given below. The very first thing that it does is defining the prefix ‘jb’ pointing to the namespace ‘http://<pre lang="LANGUAGE" line="1" lang="LANGUAGE" line="1".net/facelets'.
homePage.xhtml
[code lang=”html”]
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:jb="http://<pre lang="LANGUAGE" line="1" lang="LANGUAGE" line="1".net/facelets" >

<ui:composition template="templates/template.xhtml">

<ui:define name="leftSideMenu">
<jb:verticalMenu menus="#{menuBackingBean.leftSideMenuItems}"/>
</ui:define>

<ui:define name="content">
Welcome to <pre lang="LANGUAGE" line="1" lang="LANGUAGE" line="1"… Here you can see references <br/>
to Articles, Tips and Mock Questions for Java, J2EE,<br/>
Spring, Hibernate and other platform.<br/>
</ui:define>

<ui:define name="rightSideMenu">
<jb:horizontalMenu menus="#{menuBackingBean.rightSideMenuItems}"/>
</ui:define>

</ui:composition>
</html>[/code]
The definition of the logical areas ‘leftSideMenu’ and ‘rightSideMenu’ have been updated with the usage of the custom tag. Note the usage of the tags ‘jb:horizontalMenu’ and ‘jb:verticalMenu’ and the passing of the named parameter ‘menus’.

Facelets – Tag Demo Application.

Conclusion

This article attempted an introduction to the facelets Framework by providing a brief discussion of the various components. The article initially dealt with the starter application that discussed the various aspects suitable for the setup of a Facelets application. It then went on to details of the templating aspects of Facelets through the ui:composition, ui:define and ui:insert tags. Discussion on backing beans and passing parameters from one facelet page to another facelet page is also discussed along with ui:component tag. Finally the article concluded with writing custom tag libraries.

Filed Under: JSF Tagged With: Facelets, JSF

Introduction to JSFUnit

September 19, 2010 by Krishna Srinivasan Leave a Comment

Introduction

Testing has become an important aspect for every application and an application cannot be released unless it is not thoroughly tested. JSFUnit provides an attempt to bring in testing capabilities for JSF applications. Not many frameworks exists in the market for testing JSF applications and this framework which originated from JBoss community provides wider coverage for testing JSF applications with respect to the managed beans state, navigation flows, application configuration etc. This article is an attempt to provide an introduction to the framework JSFUnit.

If you are not familiar with Java Server Faces, first read our list of articles on Java Server Faces (JSF) including Introduction to Java Server Faces by Raja. We have also listed some of the popular JSF Books.

  • JSF Interview Questions
  • JSF books
  • Building JSF application with Exadel IDE

JSFUnit Starter

In this section, we will see how to setup JSFUnit framework for testing JSF applications. We will also see how to write simple JSF test cases at the end of the section. The example is as simple as it will display a JSP page that will return static html content to the browser.

JSF Page

Given below is the code snippet of the JSF page. Note that for each component we have explicitly assigned identifiers through the id attribute. This is absolutely necessary because later on the test case access will try to get a reference to a JSF page component only through identifiers.

index.jsp

[code lang=”html”]
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<HTML>

<f:view>
<h1><h:outputText value="JSFUnit HelloJSF Demo Application" id="title"/></h1>
<h:form id="startupForm">
<h:outputText value="JSF application is running" id="test"/>
</h:form>
</f:view>

</HTML>

[/code]

The above JSF page makes use of two outputText tags for displaying static content one being embedded within the form whereas the other didn’t.

Web Application Deployment Descriptor

In the below web application’s deployment description, apart from the regular entries related to JSF mapping, we have configured plenty of configurations related to JSFUnit suitable for performing testing on JSF pages.

web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

<filter>
<filter-name>JSFUnitFilter</filter-name>
<filter-class>org.jboss.jsfunit.framework.JSFUnitFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>JSFUnitFilter</filter-name>
<servlet-name>ServletTestRunner</servlet-name>
</filter-mapping>

<filter-mapping>
<filter-name>JSFUnitFilter</filter-name>
<servlet-name>ServletRedirector</servlet-name>
</filter-mapping>

<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>

<servlet>
<servlet-name>ServletRedirector</servlet-name>
<servlet-class>org.jboss.jsfunit.framework.JSFUnitServletRedirector</servlet-class>
</servlet>

<servlet>
<servlet-name>ServletTestRunner</servlet-name>
<servlet-class>org.apache.cactus.server.runner.ServletTestRunner</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>ServletRedirector</servlet-name>
<url-pattern>/ServletRedirector</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>ServletTestRunner</servlet-name>
<url-pattern>/ServletTestRunner</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>
[/code]

JSFUnit framework provides a facility for running the unit test cases for JSF application directly from the browser. To make use of it, we have to define a JSFUnit Filter represented through org.jboss..JSFUnitFilter which is used to initiate the environment suitable for running test cases. The JSF Servlet Redirector represented through org.jboss..JSFUnitServletRedirector is used for invoking test cases for JSF as well as does the job of clean up. As the name suggests, the component org.apache.cactus..ServletTestRunner acts as a Servlet for starting a JUnit Runner within a web application.

Vendor Specific Web Deployment Descriptor

This example is targeted to be deployed in Glassfish and the below vendor specific configuration file is used to define the context root for the web application as ‘JSFUnit-Startup’.

sun-web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd">
<sun-web-app error-url="">

<context-root>/JSFUnit-Startup</context-root>

</sun-web-app>
[/code]

Faces Configuration

In this example application, there is no need to define managed beans or the navigation rules, so the faces configuration file will be empty.

faces-config.xml

[code lang=”xml”]
<?xml version=’1.0′ encoding=’UTF-8′?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>

</faces-config>
[/code]

JSF Test Case

In this example, we will see how to write simple test cases for the above JSF page that we have written. Note that the following compile-time and run-time jar files need to be present in the classpath.

  • ant-1.5.4.jar
  • aspectjrt-1.2.1.jar
  • cactus-13-1.7.1.jar
  • cactus-ant-13-1.7.1.jar
  • cargo-0.5.jar
  • commons-codec-1.3.jar
  • commons-collections-3.2.jar
  • commons-httpclient-3.1.jar
  • commons-io-1.4.jar
  • commons-lang-2.4.jar
  • commons-logging-1.1.1.jar
  • cssparser-0.9.5.jar
  • htmlunit-2.4.jar
  • htmlunit-core-js-2.4.jar
  • jboss-jsfunit-core-1.0.0.GA-SNAPSHOT.jar
  • junit-3.8.1.jar
  • nekohtml-1.9.9.jar
  • sac-1.3.jar
  • xalan-2.7.0.jar
  • xercesImpl-2.8.1.jar
  • xml-apis-1.0.b2.jar

JSFUnitStartupTest.java

[code lang=”java”]
package net.javabeat.jsfunit.articles.startup;

import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlForm;
import javax.faces.component.html.HtmlOutputText;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.cactus.ServletTestCase;
import org.jboss.jsfunit.jsfsession.JSFClientSession;
import org.jboss.jsfunit.jsfsession.JSFServerSession;
import org.jboss.jsfunit.jsfsession.JSFSession;

public class JSFUnitStartupTest extends ServletTestCase{

private JSFClientSession client;
private JSFServerSession server;

@Override
public void setUp() throws IOException{
JSFSession jsfSession = new JSFSession("/index.faces");
client = jsfSession.getJSFClientSession();
server = jsfSession.getJSFServerSession();
}

public static Test suite(){
return new TestSuite( JSFUnitStartupTest.class );
}

public void testGetCurrentViewId() throws IOException{
assertEquals("/index.jsp", server.getCurrentViewID());
}

public void testTitleComponent() throws IOException{

UIComponent titleComponent = server.findComponent("title");
assertNotNull(titleComponent);

Object componentValue = server.getComponentValue("title");
assertNotNull(componentValue);

if (componentValue instanceof String){

String strValue = (String)componentValue;
assertEquals("JSFUnit HelloJSF Demo Application", strValue);
}else{
assertTrue("Value of title component is not an instance of String", false);
}
}

public void testFormComponent() throws IOException{

UIComponent formComponent = server.findComponent("startupForm");
assertNotNull(formComponent);
assertTrue(formComponent instanceof HtmlForm);

UIComponent textComponent = server.findComponent("startupForm:test");
assertNotNull(textComponent);
assertTrue(textComponent instanceof HtmlOutputText);

Object componentValue = server.getComponentValue("startupForm:test");
assertNotNull(componentValue);

if (componentValue instanceof String){
String strValue = (String)componentValue;
assertEquals("JSF application is running", strValue);
}else{
assertTrue("Value of test component is not an instance of String", false);
}
}
}[/code]

The very first thing to note is all the test case classes should extend org.apache.cactus.ServetTestCase so that the Servlet Runner can run the test case class within a web application. In the setup() method we have tried to establish a session to a JSF page through JSFSession API. Through this JSFSession, one can have a client side session as well as a server side session by calling the methods getJSFClientSession() and getJSFServerSession(). Note that the argument we have given is the “/index.faces” and we have configured the web application’s deployment descriptor to map this to “/index.jsp”.

The test method testGetCurrentViewId() is used to test the identifier of the current view. Note that even though we have established a session to “/index.faces”, the final view displayed will be “/index.jsp” and we have asserted whether the view identifier is correct. In the example JSF page, we have displayed two label components with the help of outputText tag, one within the form and one outside the form tag. The test method testTitleComponent() is used to test whether the component is rendered and if rendered making sure the text displayed in the component is correct. One can use the method findComponent() method to identify a component displayed in the page. If the framework is able to find the component it will return a valid UIComponent reference and the value for the component can be obtained by calling getComponentValue(). Note that the test method makes appropriate assertions before checking for the existence and the value rendered in the component.

For identifying components within a form, the identifier “formId:componentId” can be used. For example if the form id is “testFormId” and the id of a component displayed in a form is “testComponentId”, then for identifying this component “testFormId:testComponentId” should be passed to the method findComponent() for proper identification and the third test case method just does that.

Running the Application

In this section, we will see how to run the JSF application and also how to invoke the test cases that test the page integrity from the browser.

Running the JSF application is simple. Assuming that the application is running locally on the port number 8080 and with the given context root ‘JSFUnit-Startup’, then the URL “http://localhost:8080/JSFUnit-Startup/index.faces” can be used to access the JSF page.

For running the test-cases and to see the test results on the browser, we have to make use of Servlet Test Case runner. The Servlet Test Case Runner class expects the test case class name in the parameter ‘suite’ and the xs file name for formatting the test results in the parameter ‘xsl’. Note that the xsl file that is used for formatting the test results is included in the source code in the name ‘cactus-report.xsl’

The combined query string now becomes “ServletTestRunner?suite=net.javabeat.jsfunit.articles.startup.JSFUnitStartupTest&xsl=cactus-report.xsl”. This query string has to be appended with the application’s context root, in our case, the application’s context root is http://localhost:8080/JSFUnit-Startup. So the URL “http://localhost:8080/JSFUnit-Startup/ServletTestRunner?suite=net.javabeat.jsfunit.articles.startup.JSFUnitStartupTest&xsl=cactus-report.xsl” can be used to run the test cases and the results will get displayed in the browser. The following screen shot captures the test results,

Test results for the jsf unit startup application.

Exploring JSFUnit API

In this example we will try to explore the client side API that JSFUnit framework supports. For illustrating this, we will develop a traditional login application which prompts for the username and a password during application startup. If the username and the password combination is correct, the application redirects to a successful page and when the password is incorrect, an error page will be returned. To make things interesting, we will redirect to a different page if the username is invaid.

Login JSF Page

Below is the login JSF page. This page displays the input components for accepting the username and password through the inputText and the inputSecret tags. Note that to validate the user information, when the login button is clicked, the control is forwarded to User managed bean’s login method which will be discussed in the forth coming section. Note that we have explicitly specified the identifier to each of the components.

login.jsp

[code lang=”html”]
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<HTML>

<f:view>

<h1><h:outputText value="Enter username and pasword" id="infoText"/></h1>

<h:form id="startupForm">

<h:outputText id = "usernameLabel" value = "Username" />
<h:inputText id = "usernameText" value ="#{user.username}"/>

<br/>
<h:outputText id = "passwordLabel" value = "Password" />
<h:inputSecret id = "passwordText" value ="#{user.password}"/>

<br/><br/>
<h:commandButton id = "loginButton" action = "#{user.login}" value = "Login"/>

</h:form>

</f:view>

</HTML>
[/code]

Welcome JSF Page

Given below is the welcome page that will be displayed to the user when the username and the password are correct.

welcome.jsp

[code lang=”html”]
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:loadBundle basename = "net.javabeat.articles.jsfunit.login.messages" var = "message"/>
<HTML>

<f:view>

<h1><h:outputText value="Welcome #{user.username}." id="infoText"/></h1>

</f:view>

</HTML>

[/code]

Invalid User JSF Page

Have a look at the following invalid user JSF page.

invalid-user.jsp

[code lang=”html”]
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<HTML>

<f:view>

<h1><h:outputText value="Invalid user #{user.username}. Please try again." id="infoText"/></h1>

</f:view>

</HTML>
[/code]

The above page will be displayed when the username is invalid. Note that for testing purpose, we have hard-coded the username as “admin”.

Error page

This page will be displayed when the password is incorrect for a valid username. For testing purposes, we have hard-coded the username and password to “admin” and “admin”.

error.jsp

[code lang=”html”]
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<HTML>

<f:view>

<h1><h:outputText value="Invalid password for the username #{user.username}. Please try again." id="infoText"/></h1>

</f:view>

</HTML>
[/code]

User Managed bean

The following class which represents the managed bean for the login application does two things. At first, it encapsulates the username and password properties. Secondly, the validation of username and password is done within the implementation of this class in the method login().

User.java

[code lang=”java”]
package net.javabeat.articles.jsfunit.login;

public class User {

private String username;
private String password;

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String login(){

if (username.equals("admin")){
if (password.equals("admin")){
return "welcome";
}else{
return "invalid-password";
}
}else{
return "error";
}
}
}[/code]

Note that as part of validation in the login() method, if the user specifies correct username and password, a return value “welcome” is returned. Later on we will see how this return value maps to the view welcome.jsp. Similarly for the incorrect username and incorrect password, the views returned are error.jsp and invalid-password.jsp

Faces Configuration

In the below faces configuration file, we have configured the class User as a managed bean and have given the scope as session. Note that the return value view mapping during login process is modeled as navigation rules and navigation cases.

faces-config.xml

[code lang=”xml”]
<?xml version=’1.0′ encoding=’UTF-8′?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>

<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>net.javabeat.articles.jsfunit.login.User</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>welcome</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
</navigation-rule>

<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>error</from-outcome>
<to-view-id>/error.jsp</to-view-id>
</navigation-case>
</navigation-rule>

<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>invalid-password</from-outcome>
<to-view-id>/invalid-password.jsp</to-view-id>
</navigation-case>
</navigation-rule>

</faces-config>
[/code]

JSF Test Cases

In the following test class, we will discuss three testing scenarios, one when the username and password given by the user is correct, the second being the scenario when the username is correct and the password is wrong, and finally for the username being incorrect. As part of the discussion we will also be seeing the usage of the class JSFClientSession.

LoginAppTest.java

[code lang=”java”]
package net.javabeat.articles.jsfunit.login;

import java.io.IOException;
import javax.faces.component.UIComponent;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.cactus.ServletTestCase;
import org.jboss.jsfunit.jsfsession.JSFClientSession;
import org.jboss.jsfunit.jsfsession.JSFServerSession;
import org.jboss.jsfunit.jsfsession.JSFSession;

public class LoginAppTest extends ServletTestCase{

private JSFClientSession client;
private JSFServerSession server;

@Override
public void setUp() throws IOException{
JSFSession jsfSession = new JSFSession("/login.faces");
client = jsfSession.getJSFClientSession();
server = jsfSession.getJSFServerSession();
}

public static Test suite(){
return new TestSuite( LoginAppTest.class );
}

public void testCorrectUsernameAndPassword() throws IOException{

UIComponent buttonComponent = server.findComponent("loginButton");
assertNotNull(buttonComponent);

String username = "admin";

client.setValue("usernameText", username);
client.setValue("passwordText", "admin");

client.click("loginButton");

String pageText = client.getPageAsText();
assertNotNull(pageText);

assertTrue(pageText.contains("Welcome " + username + "."));
}

public void testCorrectUsernameAndIncorrectPassword() throws IOException{

UIComponent buttonComponent = server.findComponent("loginButton");
assertNotNull(buttonComponent);

String username = "admin";

client.setValue("usernameText", username);
client.setValue("passwordText", "1234");

client.click("loginButton");

String pageText = client.getPageAsText();
assertNotNull(pageText);

assertTrue(pageText.contains("Invalid password for the username " + username + ". Please try again."));
}

public void testIncorrectUsername() throws IOException{

UIComponent buttonComponent = server.findComponent("loginButton");
assertNotNull(buttonComponent);

String username = "admin123";

client.setValue("usernameText", username);
client.setValue("passwordText", "admin");

client.click("loginButton");

String pageText = client.getPageAsText();
assertNotNull(pageText);

assertTrue(pageText.contains("Invalid user " + username + ". Please try again."));
}
}[/code]

As part of the regular process, the setup() method is overridden for acquiring a session to the application’s startup page – which is “/login.faces”. Now the application is displaying the login page and in the first test case, we have made of the JSFClientSession API for setting the username and password parameters by calling setValue(paramName, paramValue). Note that this will simulate as if the user is typing the values for the username and the password fields. Finally the request submission is simulated by calling the method click() defined on the JSFClientSession object. Note that argument passed to click() is the identifier for the button. As soon as the request is submitted and the response is received, the client can call the method getPageAsText() which will return a raw HTML page text. And finally the page content is validated for correctness by comparing it with the return value from getPageAsText() method. Similarly the second and the third test cases deals with incorrect username and incorrect password combination.

Running the application

The application can be invoked through the URL “http://localhost:8080/JSFUnit-Login/login.faces”.
And for invoking the test cases, the URL “http://localhost:8080/JSFUnit-Login/ServletTestRunner?suite=net.javabeat.articles.jsfunit.login.LoginAppTest&xsl=cactus-report.xsl”. Given below is the screen shot of the test results for the login application,

Test results for the jsf unit login application.

Miscellaneous

In this miscellaneous section, we will further dig into the API support on JSFUnit framework.

Adding Request Listener

A Request Listener object can be used to intercept client request and customizations can be injected before and after the invocation of client request. For example, the following code adds a simple Request Listener,

[code lang=”java”]
public void testRequestListener(){

WebClientSpec specification = new WebClientSpec("/login.faces");
WebConnection webConnection = specification.getWebClient().getWebConnection();

if (webConnection instanceof JSFUnitWebConnection){
JSFUnitWebConnection jsfConnection = (JSFUnitWebConnection)webConnection;
MyRequestListener listener = new MyRequestListener();
jsfConnection.addListener(listener);
}
}

class MyRequestListener implements RequestListener{

public void beforeRequest(WebRequestSettings settings) {
System.out.println("Before Request");
throw new UnsupportedOperationException("Not supported yet.");
}

public void afterRequest(WebResponse settings) {
System.out.println("After Request");
}

}[/code]

Testing Faces Messages

An application can emit faces messages which can be warning, information or an error. JSFUnit framework provides support for iterating over the faces messages upon response completion for validating its contents. For example,

[code lang=”java”]
public void testGetFacesMessages(){

Iterator iterator = server.getFacesMessages("someComponentId");
while (iterator.hasNext()){

FacesMessage facesMessage = iterator.next();
// Validate the facesMessage object.
}
}[/code]

Testing Managed Bean states

The state of managed beans will keep changing in an application’s workflow and the framework adds capabilities for testing the value of a managed bean’s state giving an EL expression. Consider the following code snippet the gets the state of username and password for the Managed bean User.

[code lang=”java”]
public void testManagedBeans(){

String username = (String)server.getManagedBeanValue("${user.username}");
assertEquals("admin", username);

String password = (String)server.getManagedBeanValue("${user.password}");
assertEquals("admin", password);
}[/code]

Dumping Client Ids

Sometimes, as part of debugging, it will be essential for dumping the client id information pertaining the current page.

[code lang=”java”]
public void testClientId(){

ClientIDs clienIds = server.getClientIDs();
clienIds.dumpAllIDs();
}[/code]

The method dumpAllIDs() will print all the Client IDs to the console.

Conclusion

This article provided step by step process in setting up the environment for facilitating testing for JSF applications. Detailed discussions were given with respect to configuring and running test cases within a web application. The article also focused on explaining the essential APIs like JSFSession, JSFServerSession, JSFClientSession. Finally the article provided the miscellaneous capabitiies like checking the state of managed beans, adding request listeners, testing faces messages etc.

  • JSF Interview Questions
  • JSF books
  • Building JSF application with Exadel IDE

Filed Under: JSF Tagged With: JSF, JSFUnit

Tags and Tag Attributes in Apache MyFaces Trinidad 1.2

November 21, 2009 by Krishna Srinivasan Leave a Comment

Apache MyFaces Trinidad 1.2 In this book, you will learn how Facelets and Seam are used to get the most out of JSF. You start out by learning where Trinidad comes from and what its aims are. Additionally, you will also learn the often occurring tag attributes and, in particular, Trinidad’s Ajax technology. You will implement login, authorization, navigation, internationalization, polling and browser issues with the help of these technologies. You will then use Seamgen for deployment.

also read:

  • Introduction to JSF
  • JSF Interview Questions
  • Request Processing Lifecycle phases in JSF

As you move through the book, you will develop a web application example where a series of selected Trinidad components are applied and their capabilities explored.Finally, you will master the Trinidad dialog framework, a Trinidad key technology that allows the application of dialogs.

What This Book Covers

Chapter 1, Introducing Trinidad, introduces you to the Trinidad component library. We give a general idea of this component library, the areas covered by its components, and compare it to other libraries. Finally, the integration of Trinidad and Seam is discussed.

Chapter 2, Structuring and Building Pages with Facelets, explains Facelets as a basic means to structure and build pages using Facelet page composition, Facelet composition components, and JSTL.

Chapter 3, Most Wanted Tags and Tag Attributes, discusses the Trinidad tags and theirattributes in a structured approach. You will gain an insight into the design of Trinidad allowing you to draw an efficient mental map of the library and make an effective selection and application of tags.

Chapter 4, Rendering Pages Partially, introduces you to the Trinidad’s Ajax technology called PPR (Partial Page Rendering). PPR is inspected from two points of view—the pure tag-based partial rendering and the pure Java-side partial rendering techniques.

Chapter 5, Web Application Groundwork, teaches you how to develop the basic parts of the web application that serves as our Trinidad example. We present using Seam-gen to rapidly deploy after each change of any file.

Chapter 6, Building a Panel-based Content, deals with Trinidad’s panelAccordion and showDetailItem components to show how they can be combined to build panel-based, panel-wise collapsible content.

Chapter 7, Building a Form, discusses the combinination of Trinidad’s tags to Facelet composition components to build highly flexible and well-formatted forms, including messaging support.

Chapter 8, Growing a Tree, deals with Trinidad’s tree components and models and exemplify their application. We present an effective shortcut that makes Trinidad’s tree support an easy, and yet powerful, technology.

Chapter 9, The table and treeTable Components, gives an insight to Trinidad’s table and treeTable components and exemplifies their application. We apply the components in an increasingly refined way, revealing most of their features one at a time.

Chapter 10, The Chart Component, deals with Trinidad’s chart component and shows its application. You will learn to competently set up representation parameters, effectively achieving the intended representation focus and thus graphically materializing hidden
information in an appropriate way.

Chapter 11, Building a Wizard, deals with Trinidad’s components to implement a wizard and show their application. We present a solution to avoid an existing Facelet problem.

Chapter 12, Dialogs—Pop Up Your Web Application, discusses Trinidad’s pop-up window techniques. We revisit Seam conversations to address the specific necessities for pop-up dialogs in Trinidad and Seam. We enhance the web application with a couple of pop-up windows including wizard pop-up support.

Appendix, References, provides us with useful references and links related to Apache MyFaces Trinidad.

Most Wanted Tags and Tag Attributes

This chapter discusses the Trinidad tags and their attributes in a structured approach. The reader will gain an insight into the design of Trinidad allowing them to draw an efficient mental map of the library and an effective selection and application of tags. More concretely, the following topics are covered:

  • An overview of the XHTML-focused Trinidad namespace trh
  • An overview of the central Trinidad namespace tr
  • An orientation and classification on the attributes supported by Trinidad

Component library structure

Trinidad’s approach to web technology is comprehensive: Aimed at full control of all the bits and pieces that make up a web application, little should be left that needs to be added. So based on such a closed world, Trinidad presents itself with a wealth of components and tags that even include very basic XHTML tags as replacements for the real XHTML originals. This is no radical replacement approach, rather it enables Trinidad to remain in full control of mechanisms such as partial-page rendering (PPR, also generally known as Ajax) that otherwise would need to deal with potentially incompatible libraries externally (refer to Chapter 1, Introducing Trinidad, for further discussion).

The following image provides an outline of Trinidad’s structural package design:

myFaces-trinidad-1Trinidad is divided into the following two namespaces:

  • tr: It is the usual tag library id that references Trinidad’s core library tags. It’s a large library of over 100 components ranging from layout components and navigational components, to special viewer components that all implicitly support skinning, partial-page rendering, popup dialogs, error or info messaging, and so on.
  • trh: It is the usual tag library id that references Trinidad’s XHTML supportlibrary tags, a small companion that offers alternatives for those XHTML tags that are usually applied to build XHTML structures, for example, XHTML tables.

Let us take a closer look at both namespaces. The upcoming image shows the core API’s hierarchical structure. The tags are backed by two types of Trinidad classes—UIX* classes that deal with the JSF component requirements to implement specific JSF lifecycle processing methods, and Core* classes that deal with the specific properties (getters or setters).

myFaces-trinidad-2

Trinidad’s XHTML tag library namespace (trh)

Two groups can be distinguished from the trh namespace. The first one deals with the definition of an XHTML page and provides the developer with the following tags:

  • <trh:html>: It is used to define the whole XHTML page, analogous to <html>
  • <trh:head>: It is used to define the header, analogous to <head>
  • <trh:body>: It is used to define the main contents, analogous to <body>
  • <trh:script>: It is used to define a JavaScript to be executed, analogous to <script>

The second group deals with the layout of an XHTML table:

  • <trh:tableLayout>: It is used to define an XHTML table.
  • <trh:rowLayout>: It is used to define an XHTML table line, analogous to <tr>; note that it can also be used to display an arbitrary line, particularly when elements need to be kept in one and the same line. Alternatively, it is particularly interesting to look at the tr namespace as it provides some less heavy structures free from table constructions, for instance panelGroupLayout with a layout set to vertical or a panelBorderLayout, both generating div structures instead.
  • <trh:cellFormat>: It is used to define an XHTML table cell as part of an XHTML table.

The attributes of each tag are defined in a most consistent, and thus recognizable, way that will be seen in detail later in this book. By the way, there are also tags for the construction of framesets such as
trh:frame in case anyone still wants to make use of framesets.

However, before we deal with the attributes let us conclude this structural over view by a look at the organization of the functionality of the core tag library.

Trinidad’s core tag library namespace (tr)

The following groups can be functionally distinguished which is also refl ected in the packages structure of Trinidad’s API (all beginning with org.apache.myfaces. trinidad.component; which has been left out here to avoid repetition). Note that, for completeness, we will also include information on the pure Java side as well as information on the few components that stem from the trh namespace:

  • Basic document composition tags from the core API: document, stylesheet, form, subform. poll also appears here although it is not a composition tag.
  • Form input and display tags, components from the core.input API: inputText, inputDate, inputListOfValues, and so on.
  • Command or navigation tags from core.nav that includes two tag types:
  • One that is focused on command tags that assumes a given form, presupposing the use of form and display tags from the foregoing group—commandButton, commandLink, goButton, goLink, and so on.
  • The other deals exclusively with navigation: navigationTree, navigationPane, breadCrumbs, and so on.
  • Large input and output component tags from core.data, for example, table, tree, and treeTable components.
  • Layout component tags from core.layout, for example, all the swinglike panel tags, such as panelBorderLayout, panelHorizontalLayout, panelAccordion, showDetail, showDetailItem, and so on.
  • Basic output components from core.output that are almost always used in a web application, for example, messages, outputText, outputLabel, spacer, statusIndicator, and so on.
  • Model objects from core.model devised for various tags ; they provide the corresponding view models for their tag viewer counterparts, for example, SortableModel CollectionModeland RowKeySet for tr:table,ChildPropertyTreeModel for tr:tree and ChartModel for tr:chart.
  • A couple of converter components from trinidad.convert equip JSF and Trinidad input components with powerful JSF conversion, that is, convertNumber and convertDateTime.
  • Validator components from trinidad.validator equip JSF and Trinidad input components with powerful JSF validation such as range validation (validateDateTimeRange) and validation by regular expression match (validateRegExp).
  • Events and event listeners from trinidad.event add new event types and listeners specific for Trinidad components such as those that support Trinidad’s dialog framework, for example, commandButton to launch a popup dialogue using LaunchEvent, ReturnEvent, and ReturnListener. It provides only a few tags, but these can be very utile, for example, fileDownloadActionListener, resetActionListener, returnActionListener, and setActionListener.

There is a lot more to be found on the pure Java API side that either surfaces indirectly on the tag library as attributes, or is used implicitly by the tags themselves. Furthermore, there are utility classes and context support classes—RequestContext being probably the most prominent one because it offers a lot of functionality, for example, PPR from the server side. This is described in the upcoming chapter.

The following figure illustrates the Java side of things (it shows what the structure of some of the classes behind core.input look like):

myFaces-trinidad-3The preceding figure is an outline of the core.input API hierarchy. Again, we can see the typical UIX* and Core* structure.

Finally, let us take a closer look at the tag attributes.

Standard tag attributes

We begin by taking a closer look at the attributes that practically always occur, no matter which tag is actually involved.

As mentioned before, this occurrence is because of Trinidad’s
design which is noted by its consequent application of attributes
that are shared by many different tags.

The following attributes occur almost always:

  • id: As it is already known from JSF itself, it ought to be set in most cases as it is used by Trinidad itself to identify the component. However, if it is not set by the developer, Trinidad sets up arbitrary, but not very legible, IDs.
  • rendered: Typical for JSF; it is a Boolean attribute that allows setting if the component is to become part of the page sent to the client—in other words if it is considered by the Trinidad renderer.
  • binding, attributeChangeListener: These are attributes that are practically never used because binding is an architecturally questionable JSF attribute as it incurs a traffic-intense, tight coupling between view and server-side model and is therefore not supported by Seam. On the other hand, attributeChangeListener is rather an internal Trinidad attribute to tell a Trinidad to re-render itself if renderer attributes of some other component have changed.
  • onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, ondblclick, onclick: These are the usual
    JavaScript mouse event listeners, onclick is typically used to implement simple JavaScript confirm dialogues “Are you sure (Y or N)?”.
  • onkeydown, onkeypress, onkeyup: These are the usual JavaScript keyboard, single key event listeners and may
    be of interest although the attributes accessKey and textAccessKey are usually more practical.
  • shortDesc: This attribute serves to set a short tool tip that is displayed when the user hovers with the mouse on the
    respective component.
  • inlineStyle and styleClass: The former attribute is very practical because it allows explicitly setting the style and
    overriding default style settings. However, it is cleaner to use styleClass, which is analogous to the XHTML style
    attribute, and define this explicit setup as a style sheet class in the style sheet (note that there are a couple of less
    frequent style attributes geared towards Trinidad-specific contents of component parts: contentStyle, labelStyle,
    listStyle, dateStyle, timeStyle, warnStyle, infoStyle, fatalStyle, errorStyle, defaultStyle,stateStyle, userStyle).
  • partialTriggers: This attribute serves to state the IDs of the components (separated by single spaces) that trigger
    a partial page refresh (PPR) which is discussed in the upcoming chapter.

Standard tag attributes in tag groups

Let’s take a look at the attributes that almost always occur in certain tag groups(mentioned in the beginning of this chapter):

Attributes that occur in form and display tags

This relates to the second tag group we learned in the earlier section named Trinidad’s core tag library namespace (tr). The following Trinidad-specific attributes occur there:

  • label: This attribute serves to set the label of an input field; note that Trinidad support label indication, along with the respective input field, is also used for error or info messaging, for example, in the messages component.
  • accessKey, labelAndAccessKey: Both attributes allow keyboard shortcuts for an input field, but labelAndAccessKey allows you to indicate the shortcut as part of the label. For example, label=”&9: date” activates the 9 key as keyboard shortcut for the respective input field (e.g. pressing Alt + Shift + 9 in Firefox). Note that, its analogon, textAndAccessKey in the command area.
  • contentStyle: This attribute is used to set the style of the tag’s content area,for example, the style used within input text’s box.
  • disabled, readOnly: These are Boolean attributes that both deactivate input fields, but disabled differs in its look by keeping the frame around the box.
  • autoSubmit: If “true”, it sends the enclosing form when this Boolean attribute’s field is somehow manipulated, for example, by changing its entry and pressing tab or return. Note that this attribute must be “true” if partial page rendering is started from this attribute’s field (refer to the upcoming chapter for detailed information).
  • required, requiredMessageDetail, showRequired: The attribute required is a Boolean attribute to indicate if an input field entry must be provided by the user, and when it is not provided, it is allowed to indicate a custom message (requiredMessageDetail) and display a missing symbol (showRequired=”true”).
  • simple: This is a Boolean attribute to control if Trinidad’s label and messaging support is used. It also appears in the table tag.

A series of attributes in this group are those that stem from the core JSF tag libraries:

  • immediate: This is a JSF attribute and serves to have the respective input field converted, and validated before the process validator phase of the JSF lifecycle so that its possible server request may directly follow (apply request phase). For example, this occurs when using action listeners, which is a common practice.
  • onblur, onfocus, onchange: These attributes expect the usual JavaScript handlers to be assigned.
  • validator, converter: Both attributes serve to reference JSF’s usual conversion and validation mechanisms, but validator differs in expecting a method call instead of a class. This is somewhat confusing, but JSF’s core library supports the tag <f:validator validatorId=”aValidatorClass”/> which can be very practically used inside of any Trinidad input field tag.
  • value: This is JSF’s standard attribute to assign the model behind the respective tag, for example, a view model or a real domain object.

Finally, in this group are listener attributes which come both from pure JSF and Trinidad:

  • actionListener: This attribute is based on the ActionEvent
  • valueChangeListener: This attribute is based on the ValueChangeEvent
  • returnListener: A Trinidad-specific listener called returnListener,is supported, and is used to indicate a listener method for a Trinidad Return Event when control returns from a Trinidad dialog (see respective dialogs chapter)

Attributes that occur in command and navigation components

These are attributes that occur in the third tag group. We have learned about the command and navigation tags, to which these attributes are related, in the earlier section. Here we can see their attributes:

  • launchListener: This attribute serves to indicate a listener method that is called just before a Trinidad dialogue is displayed.
  • partialSubmit: This is a Boolean attribute, which when set to “true” has the effect that its tag acts as a partial page rendering source (refer to the upcoming chapter for details).
  • blocking: This is a Boolean attribute that, when true lets Trinidad block any other user input while the respective request is ongoing.
  • textAndAccessKey: T his is, as mentioned earlier, an attribute that allows assigning a keyboard shortcut. Note that its the power of Trinidad’s consistent support of the keyboard that makes it a framework for all applications that heavily support keyboard users with minimal mouse activity.
  • useWindow, windowHeight, windowWidth: These attributes are used to setup a Trinidad dialogue popup (useWindow=”true”) and its window size.

Attributes that occur in large input and output components

These attributes come from the fourth tag group, the rather heavyweight input and output components as described in the beginning section. They can be further grouped into the following attribute categories:

  • component attributes specific for table, treeTable, and tree
  • attributes specific for table and treeTable components only
  • attributes specific for tree and treeTable components only
  • attributes specific for the treeTable component only
  • attributes specific for the table component only

In the following section, we will give an overview of each of the above attribute categories.

The tag attributes for table, treeTable, and tree

First, we come across a couple of listeners that deal with selection and disclosure:

  • A Trinidad-specific selectionListener serves to handle a SelectionEvent that is raised when the user selects a row
  • A Trinidad-specific rowDisclosureListener to handle a RowDisclosureEvent that is raised when the users clicks on a detail item or any other node that is closed

Next, follow the row-specific attributes:

  • selectedRowKeys: This is the set of all rows (or row indices) that are selected
  • disclosedRowKeys: This is the set of all open nodes and rows
  • var, varStatus: As known from JSF; note that varStatus serves to set if a model-based reference is used, for example, when returning a selected row or if an index is preferred

The tag attributes for table and treeTable

A series of facets are supported that deal with the inclusion of developer own parts in certain areas of the views:

  • actions: This attribute is used to indicate any other action areas that are to be shown on the same line as Trinidad’s built-in table or treeTable actions
  • footer: This serves to setup anything in the footer area
  • header: This is to setup anything in the header area

A couple of specific listeners are provided to deal with sorting and range change:

  • A Trinidad-specific sortListener is provided to allow handling any SortEvent that occurs when the user clicks on the label of a column that has sorting activated
  • A rangeChangeListener is supported to handle any RangeChangeEvent that occurs when the user thumbs through the data when it is displayed page-wise

In connection with the sortListener table and treeTable, we need to provide the following attribute for setting up a selection mode:

  • rowSelection: This attribute serves to indicate if any selection at all is to be supported (“none”), and if so which type (“multiple” or “single”)
  • autoSubmit: This is to enable partial page rendering which also sends the enclosing form
  • emptyText: This is used to indicate any text that is displayed when there is no data to be obtained from the model

The following series of attributes deal with the general view setup:

  • rows: This is the number of lines to be displayed at once
  • summary: This is used to indicate the purpose and structure of this component (only useful for non-visual output)
  • rowBandingInterval, columnBandingInterval: These attributes serve to setup band style for easier reading and in particular, to indicate when which (horizontal, vertical, or both) band is changed (for example, every two lines)
  • horizontalGridVisible, verticalGridVisible: These Boolean attributes are used to display a horizontal grid, vertical grid, or both
  • width: This attribute serves to define the overall width of this component

The tag attributes for tree and treeTable

There are just three attributes that are specific for both tree and treeTable:

  • nodeStamp: This facet allows to build the tree nodes by specifying a single looped node that allows us to build a tree in a highly dynamic way using an implicit loop (see the tree chapter for details)
  • focusListener, focusRowKey: These attributes allow handling the focus when it is on a node, which raises a FocusEvent that may be handled by the indicated focusListener and that is accessible in the object indicated as focusRowKey
  • initiallyExpanded: This is used to set if the component shows all the nodes when shown for the first time

The tag attributes for treeTable

The treeTable tag is exclusively supported by the following attributes:

  • rowsByDepth: This allows us to set the maximum size of displayed nodes depending on the actual level(depth) by passing an array of integers for the depths that the developer wants to specify (for more details refer to Chapter 8, Growing a Tree)
  • rootNoteRendered: This is used to set if the root is rendered at all

The tag attributes for tree

Actually, there is only one attribute here that exclusively supports this tag:

  • allDetailsEnabled: This serves to set if the detail feature of a table is to be used, thereby allowing to display additional detail information per line

Summary

We have seen what Trinidad is all about with regards to its component set. More concretely, we have first looked at the XHTML-focused Trinidad namespace trh that basically contains a component set for XHTML layout.

Furthermore, we looked at Trinidad’s core namespace which is its tr JSF tag library. It contains a large component set with various types of components for basic document composition, form input and display, command and navigation, large and basic input and output, layout, models, converters, validators, events, and event listeners.

Finally, we looked at the attributes of all those tags and found out that a straight-forward orientation along tag groups is possible. This is thanks to Trinidad’s framework character.

Filed Under: JSF Tagged With: JSF, MyFaces Trinidad 1.2

JSF Interview Questions

February 13, 2009 by Krishna Srinivasan Leave a Comment

1) What is JSF?

JSF stands for Java Server Faces. JSF has set of pre-assembled User Interface (UI). By this it means complex components are pre-coded and can be used with ease. It is event-driven programming model. By that it means that JSF has all necessary code for event handling and component organization. Application programmers can concentrate on application logic rather sending effort on these issues. It has component model that enables third-party components to be added like AJAX. If you are interested in reading specific articles about Java Server Faces (JSF),

also read:

  • Introduction to Java Server Faces
  • Request Processing Lifecycle phases in JSF
  • Accessing Web Services from JSF applications
  • Navigation model in JSF
  • BalusC on JSF

2) What is required for JSF to get started?

Following things required for JSF:

  • JDK (Java SE Development Kit)
  • JSF 1.2
  • Application Server (Tomcat or any standard application server)
  • Integrated Development Environment (IDE) Ex. Netbeans 5.5, Eclipse 3.2.x, etc.

Once JDK and Application Server is downloaded and configured, one can copy the JSF jar files to JSF project and could just start coding. 🙂

If IDE is used, it will make things very smooth and will save your time.

3) What is JSF architecture?

JSF was developed using MVC (a.k.a Model View Controller) design pattern so that applications can be scaled better with greater maintainability. It is driven by Java Community Process (JCP) and has become a standard. The advantage of JSF is that it’s both a Java Web user – interface and a framework that fits well with the MVC. It provides clean separation between presentation and behavior. UI (a.k.a User Interface) can be created by page author using reusable UI components and business logic part can be implemented using managed beans.

4) How JSF different from conventional JSP / Servlet Model?

JSF much more plumbing that JSP developers have to implement by hand, such as page navigation and validation. One can think of JSP and servlets as the “assembly language� under the hood of the high-level JSF framework.

5) How the components of JSF are rendered? An Example

In an application add the JSF libraries. Further in the .jsp page one has to add the tag library like:

[code lang=”html”]<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>[/code]

Or one can try XML style as well:

[code lang=”xml”]<?xml version="1.0"?>
<jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">[/code]

Once this is done, one can access the JSF components using the prefix attached. If working with an IDE (a.k.a Integrated Development Environment) one can easily add JSF but when working without them one also has to update/make the faces-config.xml and have to populate the file with classes i.e. Managed Beans between

[code lang=”xml”]<faces-config> </faces-config> tags [/code]

6) How to declare the Navigation Rules for JSF?

Navigation rules tells JSF implementation which page to send back to the browser after a form has been submitted. For ex. for a login page, after the login gets successful, it should go to Main page, else to return on the same login page, for that we have to code as:

[code lang=”xml”]<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/main.jsp<to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>fail</from-outcome>
<to-view-id>/login.jsp<to-view-id>
</navigation-case>
</navigation-rule>[/code]

from-outcome to be match with action attribute of the command button of the login.jsp as:

[code lang=”xml”]<h:commandbutton value="Login" action="login"/> [/code]

Secondly, it should also match with the navigation rule in face-config.xml as

[code lang=”xml”]<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>core.jsf.LoginBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>[/code]

In the UI component, to be declared / used as:

[code lang=”xml”]<h:inputText value="#{user.name}"/> [/code]

value attribute refers to name property of the user bean.

7) How do I configure the configuration file?

The configuration file used is our old web.xml, if we use some IDE it will be pretty simple to generate but the contents will be something like below:

[code lang=”xml”]<?xml version="e;1.0"e; encoding="e;UTF-8"e;?>

<web-app version="e;2.4"e;
xmlns="e;http://java.sun.com/xml/ns/j2ee"e;
xmlns:xsi="e;http://www.w3.org/2001/XMLSchema-instance"e;
xsi:schemaLocation="e;http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"e;>
<context-param>
<param-name>com.sun.faces.verifyObjects</param-name>
<param-value>false</param-value>
</context-param>

<context-param>
<param-name>com.sun.faces.validateXml</param-name>
<param-value>true</param-value>
</context-param>

<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>

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

<session-config>
<session-timeout>
30
</session-timeout>
</session-config>

<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
</web-app>[/code]

The unique thing about this file is ?servlet mapping?. JSF pages are processed by a servlet known to be part of JSF implementation code. In the example above, it has extension of .faces. It would be wrong to point your browser to http://localhost:8080/MyJSF/login.jsp, but it has to be http://localhost:8080/MyJSF/login.faces. If you want that your pages to be with .jsf, it can be done with small modification :-),

[code]<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>

<servlet-mapping>[/code]

8)What is JSF framework?

JSF framework can be explained with the following diagram:

As can be seen in Figure 1, JSF interacts with Client Devices which ties together with presentation, navigation and event handling and business logic of web tier model. Hence JSF is limited to presentation logic / tier. For Database tier i.e. Database and Web services one has to rely on other services.

9) How does JSF depict the MVC (a.k.a Model View Controller) model?

The data that is manipulated in form or the other is done by model. The data presented to user in one form or the other is done by view. JSF is connects the view and the model. View can be depicted as shown by:

[code]<h:inputText value="#{user.name}"/> [/code]

JSF acts as controller by way of action processing done by the user or triggering of an event. For ex.

[code]<h:commandbutton value="Login" action="login"/> [/code]

, this button event will triggered by the user on Button press, which will invoke the login Bean as stated in the faces-config.xml file.
Hence, it could be summarized as below: User Button Click -> form submission to server -> invocation of Bean class -> result thrown by Bean class caught be navigation rule -> navigation rule based on action directs to specific page.

10) What does it mean by rendering of page in JSF?

Every JSF page as described has various components made with the help of JSF library. JSF may contain h:form, h:inputText, h:commandButton, etc. Each of these are rendered (translated) to HTML output. This process is called encoding. The encoding procedure also assigns each component with a unique ID assigned by framework. The ID generated is random.

11) What is JavaServer Faces?

JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client. JSF provides ease-of-use in the following ways:

  • Makes it easy to construct a UI from a set of reusable UI components
  • Simplifies migration of application data to and from the UI
  • Helps manage UI state across server requests
  • Provides a simple model for wiring client-generated events to server-side application code
  • Allows custom UI components to be easily built and re-used

Most importantly, JSF establishes standards which are designed to be leveraged by tools to provide a developer experience which is accessible to a wide variety of developer types, ranging from corporate developers to systems programmers. A “corporate developer” is characterized as an individual who is proficient in writing procedural code and business logic, but is not necessarily skilled in object-oriented programming. A “systems programmer” understands object-oriented fundamentals, including abstraction and designing for re-use. A corporate developer typically relies on tools for development, while a system programmer may define his or her tool as a text editor for writing code. Therefore, JSF is designed to be tooled, but also exposes the framework and programming model as APIs so that it can be used outside of tools, as is sometimes required by systems programmers.

12) How to pass a parameter to the JSF application using the URL string?

if you have the following URL: http://your_server/your_app/product.jsf?id=777, you access the passing parameter id with the following lines of java code:

[code lang=”java”]FacesContext fc = FacesContext.getCurrentInstance();
String id = (String) fc.getExternalContext()
.getRequestParameterMap().get("id");[/code]

From the page, you can access the same parameter using the predefined variable with name param. For example,

[code]<h:outputText value="#{param[‘id’]}" /> [/code]

Note: You have to call the jsf page directly and using the servlet mapping.

13) How to add context path to URL for outputLink?

Current JSF implementation does not add the context path for outputLink if the defined path starts with ‘/’. To correct this problem use #{facesContext.externalContext.requestContextPath} prefix at the beginning of the outputLink value attribute. For example:

[code]<h:outputLink
value="#{facesContext.externalContext.requestContextPath}/myPage.faces">
[/code]

14) How to get current page URL from backing bean?

You can get a reference to the HTTP request object via FacesContext like this:

[code lang=”java”]FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)
fc.getExternalContext().getRequest();[/code]

and then use the normal request methods to obtain path information. Alternatively,

[code lang=”java”]context.getViewRoot().getViewId(); [/code]

will return you the name of the current JSP (JSF view IDs are basically just JSP path names).

15) How to access web.xml init parameters from java code?

You can get it using externalContext getInitParameter method. For example, if you have:

[code lang=”xml”]<context-param>
<param-name>connectionString</param-name>
<param-value>
jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB
</param-value>
</context-param>[/code]

You can access this connection string with:

[code lang=”java”]FacesContext fc = FacesContext.getCurrentInstance();
String connection = fc.getExternalContext()
.getInitParameter("connectionString");[/code]

16) How to access web.xml init parameters from jsp page?

You can get it using initParam pre-defined JSF EL valiable.

For example, if you have:

[code lang=”xml”]<context-param>
<param-name>productId</param-name>
<param-value>2004Q4</param-value>
</context-param>[/code]

You can access this parameter with #{initParam[‘productId’]} . For example:

[code lang=”java”]Product Id: <h:outputText value="#{initParam[‘productId’]}"/> [/code]

17) How to terminate the session?

In order to terminate the session you can use session invalidate method.

This is an example how to terminate the session from the action method of a backing bean:

[code lang=”java”]public String logout() {
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc
.getExternalContext().getSession(false);
session.invalidate();
return "login_page";
}
[/code]

The following code snippet allows to terminate the session from the jsp page:

[code]
<% session.invalidate(); %> <c:redirect url="loginPage.jsf" />
[/code]

18) How to implement “Please, Wait…” page?

The client-side solution might be very simple. You can wrap the jsp page (or part of it you want to hide) into the DIV, then you can add one more DIV that appears when user clicks the submit button. This DIV can contain the animated gif you speak about or any other content.

Scenario: when user clicks the button, the JavaScript function is called. This function hides the page and shows the “Wait” DIV. You can customize the look-n-fill with CSS if you like.

This is a working example:

[code lang=”html”]<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="demo.bundle.Messages" var="Message"/>

<html>
<head>
<title>Input Name Page</title>
<script>
function gowait() {
document.getElementById("main").style.visibility="hidden";
document.getElementById("wait").style.visibility="visible";
}
</script>
</head>

<body bgcolor="white">
<f:view>
<div id="main">
<h1><h:outputText
value="#{Message.inputname_header}"/></h1>
<h:messages style="color: red"/>
<h:form id="helloForm">
<h:outputText value="#{Message.prompt}"/>
<h:inputText id="userName"
value="#{GetNameBean.userName}" required="true">
<f:validateLength minimum="2" maximum="20"/>
</h:inputText>
<h:commandButton onclick="gowait()"
id="submit" action="#{GetNameBean.action}"
value="Say Hello" />
</h:form>
</div>
<div id="wait" style="visibility:hidden;
position: absolute; top: 0; left: 0">
<table width="100%" height ="300px">
<tr>
<td align="center" valign="middle">
<h2>Please, wait…</h2>
</td>
</tr>
</table>
</div>
</f:view>
</body>
</html> [/code]

If you want to have an animated gif of the “Wait” Page, the gif should be reloaded after the form is just submitted. So, assign the id for your image and then add reload code that will be called after some short delay. For the example above, it might be:

[code lang=”java”]<script>
function gowait() {
document.getElementById("main").style.visibility="hidden";
document.getElementById("wait").style.visibility="visible";
window.setTimeout(‘showProgress()’, 500);
}
function showProgress(){
var wg = document.getElementById("waitgif");
wg.src=wg.src;
}
</script>
….
….
….

<img id="waitgif" src="animated.gif">[/code]

19) How to reload the page after ValueChangeListener is invoked?

At the end of the ValueChangeListener, call FacesContext.getCurrentInstance().renderResponse()

20) How to download PDF file with JSF?

This is an code example how it can be done with action listener of the backing bean.

Add the following method to the backing bean:

[code lang=”java”]public void viewPdf(ActionEvent event) {
String filename = "filename.pdf";

// use your own method that reads file to the byte array
byte[] pdf = getTheContentOfTheFile(filename);

FacesContext faces = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)
faces.getExternalContext().getResponse();
response.setContentType("application/pdf");
response.setContentLength(pdf.length);
response.setHeader( "Content-disposition",
"inline; filename=\""+fileName+"\"");
try {
ServletOutputStream out;
out = response.getOutputStream();
out.write(pdf);
} catch (IOException e) {
e.printStackTrace();
}
faces.responseComplete();
}[/code]

This is a jsp file snippet:

[code]<h:commandButton immediate="true"
actionListener="#{backingBean.viewPdf}"
value="Read PDF" /> [/code]

21) How to show Confirmation Dialog when user Click the Command Link?

h:commandLink assign the onclick attribute for internal use. So, you cannot use it to write your own code. This problem will fixed in the JSF 1.2. For the current JSF version you can use onmousedown event that occurs before onclick. function ConfirmDelete(link) { var delete = confirm(‘Do you want to Delete?’); if (delete == true) { link.onclick(); } } . . . .

22) What is the different between getRequestParameterMap() and getRequestParameterValuesMap()

getRequestParameterValuesMap() similar to getRequestParameterMap(), but contains multiple values for for the parameters with the same name. It is important if you one of the components such as .

23) Is it possible to have more than one Faces Configuration file?

Yes. You can define the list of the configuration files in the web.xml.

This is an example:

[code lang=”xml”]<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config-navigation.xml,
/WEB-INF/faces-beans.xml</param-value>
</context-param>[/code]

Note: Do not register /WEB-INF/faces-config.xml file in the web.xml . Otherwise, the JSF implementation will process it twice.

Hi there, I guess the Note: column should have been meant or intended for “faces-config.xml” file as thats the default configuration file for JSF (which is similar to struts-config.xml for Struts!!). faces-context.xml file sounds like the user defined config file similar to the aforementioned two xml files.

24) How to mask actual URL to the JSF page?

You’ll need to implement your own version of javax.faces.ViewHandler which does what you need. Then, you register your own view handler in faces-config.xml.

Here’s a simple abstract ViewHandler you can extend and then implement the 3 abstract methods for. The abstract methods you override here are where you’ll do your conversions to/from URI to physical paths on the file system. This information is just passed right along to the default ViewHandler for JSF to deal with in the usual way. For example, you could override these methods to add and remove the file extension of an incoming view id (like in your example), for extension-less view URIs.

[code lang=”java”]import java.io.IOException;
import java.util.Locale;

import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* A facade view handler which maps URIs into actual physical views that the
* underlying implementation can deal with regularly.
* Therefore, all internal references to view ids, for example in faces-config,
* will use the path to the physical files. Everything publicized, however, will
* see a "converted" / facade url.
*/
public abstract class SimpleConverterViewHandler
extends ViewHandler {
private static final Log LOG =
LogFactory.getLog(SimpleConverterViewHandler.class);

private final ViewHandler base;

public SimpleConverterViewHandler(ViewHandler base) {
this.base = base;
}

/**
* Distinguishes a URI from a physical file view.
* Tests if a view id is in the expected format — the format corresponding
* to the physical file views, as opposed to the URIs.
* This test is necessary because JSF takes the view ID from the
* faces-config navigation, and calls renderView() on it, etc.
*/
public abstract boolean isViewFormat(FacesContext context, String viewId);

/**
* Convert a private file path (view id) into a public URI.
*/
public abstract String convertViewToURI(FacesContext context, String viewId);

/**
* Convert a public URI into a private file path (view id)
* note: uri always starts with "/";
*/
public abstract String convertURIToView(FacesContext context, String uri);

public String getActionURL(FacesContext context, String viewId) {
// NOTE: this is used for FORM actions.

String newViewId = convertViewToURI(context, viewId);
LOG.debug("getViewIdPath: " + viewId + "->" + newViewId);
return base.getActionURL(context, newViewId);
}

private String doConvertURIToView(FacesContext context, String requestURI) {
if (isViewFormat(context, requestURI)) {
return requestURI;
} else {
return convertURIToView(context, requestURI);
}
}

public void renderView(FacesContext context, UIViewRoot viewToRender)
throws IOException, FacesException {
if (null == context || null == viewToRender)
throw new NullPointerException("null context or view");

String requestURI = viewToRender.getViewId();
String newViewId = doConvertURIToView(context, requestURI);
LOG.debug("renderView: " + requestURI + "->" + newViewId);
viewToRender.setViewId(newViewId);

base.renderView(context, viewToRender);
}

public UIViewRoot restoreView(FacesContext context, String viewId) {
String newViewId = doConvertURIToView(context, viewId);
LOG.debug("restoreView: " + viewId + "->" + newViewId);
return base.restoreView(context, newViewId);
}

public Locale calculateLocale(FacesContext arg0) {
return base.calculateLocale(arg0);
}

public String calculateRenderKitId(FacesContext arg0) {
return base.calculateRenderKitId(arg0);
}

public UIViewRoot createView(FacesContext arg0, String arg1) {
return base.createView(arg0, arg1);
}

public String getResourceURL(FacesContext arg0, String arg1) {
return base.getResourceURL(arg0, arg1);
}

public void writeState(FacesContext arg0) throws IOException {
base.writeState(arg0);
}

}[/code]

25) How to print out html markup with h:outputText?

The h:outputText has attribute escape that allows to escape the html markup. By default, it equals to “true”. It means all the special symbols will be replaced with ‘&’ codes. If you set it to “false”, the text will be printed out without ecsaping.
For example, <h:outputText value="This is a text“/> will be printed out like: This is a text
In case of <h:outputText escape="false" value="This is a text“/> you will get: This is a text

26) h:inputSecret field becomes empty when page is reloaded. How to fix this?

Set redisplay=true, it is false by default.

Filed Under: Interview Questions Tagged With: JSF

Integrating Spring and JSF

October 11, 2007 by Krishna Srinivasan Leave a Comment

1) Introduction

This article provides an introduction on how Spring and Java Server Faces Technologies can be integrated. It covers the necessary details of both Spring and JSF Technology in the initial section in the context of Integration. Later on it moves towards the concept of Variable Resolvers which help in easing the integration between the two technologies. Then a full-fledged sample application is followed to get a greater feel and understanding of the integration.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

2) Spring-JSF Integration

2.1) Introduction

Before getting into the details of how Sping JSF Integration, it is important to know a bit about basic details. The following section will talk about how the base architecture is structured for both Spring and JSF in the context of integration.

2.2) Spring

Spring is a framework that supports of Inversion of Control. For more information about Spring’s Introduction, readers are advised to read the article introduction spring framework in javabeat. Inversion of Control (IOC) enables you to decouple several components that fit in an Application. In Spring terminology, Beans (or Spring Beans) are nothing but regular java classes. It is possible to externalize the state of Bean objects by specifying them in the Xml file. A spring Bean has a dedicated life-cycle and it passes through various phases. Spring’s IOC is responsible for reading the Xml file and constructing Spring Beans from the various meta-data information. So, the main responsibility of IOC is to make the Spring Beans available to the client Application. And the other core of IOC is to provide wiring between Spring Beans. So, instead of Application code manually managing the relationship between Beans, now the burden of maintaining this is delegated to the Spring’s IOC. An example bean called Person is as follows,

[code lang=”xml”]<bean id = "personBean"
class = "net.javabeat.articles.spring.Person">
<property name = "name">
<value>Anonymous</value>
</property>
</bean>[/code]

The above example defines a Spring Bean of type Person with an identifier personBean. It also defines a simple property called name with value Anonymous. It is also possible to relate compound values (like references to other object) and collection-like (set, map, list) values as the following code snippet will illustrate that,

[code lang=”xml”]<bean id = "employee1"
class = "net.javabeat.articles.spring.Employee">
<property name = "name">
<value>Emp1</value>
</property>
</bean>

<bean id = "employee2"
class = "net.javabeat.articles.spring.Employee">
<property name = "name">
<value>Emp2</value>
</property>
</bean>

<bean id = "manager1"
class = "net.javabeat.articles.spring.Manager">
<property name = "name">
<value>Manager1</value>
</property>

<property name = "employees">
<ref bean = "employee1"/>
<ref bean = "employee2"/>
</property>
</bean>[/code]
Note that in the above example, we have declared two employee objects with identifiers employee1 and employee2. We want these two employee objects to be associated with the manager object. This is an example of a composite relationship, since we are relating Manager to Employees. This is achieved through the reference tag within the property declaration.

2.3) Java Server Faces

Having seen about how Spring’s IOC manages and maintains Spring Beans, let us see an overview about Java Server Faces managing its components. JSF is responsible for providing a component oriented development for UI layer in a Web Application. A client request is directly mapped to an Action in the Web tier, which means that the event-handling mechanism resembles the one what we see in Swings or AWT. If Swings event-handling mechanism is for Desktop Applications, then JSF event-oriented architecture is for Web Applications. Similar to Spring Beans, in JSF we have something called Managed Beans or Backing Beans. These managed beans are responsible for handling all types of actions in a Web Application. How a UI component is associated with a particular action is easily configurable in Xml file. The following code shows the declaration of a managed bean in JSF.

[code lang=”xml”]<managed-bean>
<managed-bean-name>timerBean</managed-bean-name>
<managed-bean-class>
net.javabeat.articles.springjsf.TimerBean
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>[/code]
A managed bean is also a regular Java class in JSF and it is configured in faces-config.xml file and it made available to the Application by the JSF Framework.

2.4) Spring Beans in JSF Environment

Now that we have seen about Spring and JSF, let us see about Integration and what component gets integrated. Spring uses Spring Beans and JSF uses Managed Beans. The Spring Framework provides support in such a way that a Spring Bean is made visible to the JSF Environment. Precisely, the Spring Bean what we have configured in the Xml file can be directly referred in the faces-config.xml as if it was a JSF managed Bean. Let us further clarify this,

[code lang=”xml”]<bean id = "personBean"
class = "net.javabeat.articles.spring.Person">
<property name = "name">
<value>Anonymous</value>
</property>
</bean>
[/code]
The above is a Spring Bean. Now, consider the following,

[code lang=”xml”]<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>
net.javabeat.articles.spring.Person
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>[/code]
We have used the Person Bean which was previously given configuration in Spring in JSF Environment. This is the core of what the Spring-JSF Integration is all about.

3) Supporting API’s for Integration

3.1) Introduction

Let us turn our focus to the various API in the Spring Distribution that are related to JSF for supporting integration. The Spring API is vast and the supporting classes for JSF Integration are available in org.springframework.web.jsf and org.springframework.web.jsf.el packages. But for the integration to work, we need to know only about Spring Resolvers. The following section tries to provide an overview about Spring Resolvers.

3.2) Spring Resolvers

In JSF Context, Resolving is a process of identifying an object from a given symbol. More specifically given an identifier the JSF framework tries to construct and associate the object with the identifier. Going back to the declaration of managed beans,

[code lang=”xml”]<managed-bean>
<managed-bean-name>timerBean</managed-bean-name>
<managed-bean-class>
net.javabeat.articles.springjsf.TimerBean
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>[/code]

In the above declaration, we have an identifier (or variable) called timerBean. The aim of a JSF Resolver implementation should be to associate an object of type net.javabeat.articles.springjsf.TimerBean to timerBean. Let us see what happens when we try to identify a variable that is not managed by JSF Application Context, but rather it is in Spring’s Application Context. The JSF implementation will simply throw an error telling that the variable cannot be resolved. Because the JSF implementation doesn’t care or doesn’t know anything about the Beans that are maintained in the Spring’s Application Context.
So, in order to resolve the variables in the Spring’s Application Context, we have to replace the implementation of JSF resolver to Spring’s revolver implementation. Spring’s resolver implementation will try to resolve the variables from Spring’s Application Context also. Instead of defining a custom Variable Resolver, Spring’s distribution comes with a pre-defined Variable Resolver called “org.springframework.web.jsf.DelegatingVariableResolver”.

4) Spring and JSF – Sample Application

Let us see what exactly the sample is all about. Since the purpose of the sample is to show how the integration works, the sample does not deal in depth about the real business logic. The application is all about getting the stock value for a particular stock symbol. Initially it displays a stock input page, providing a text-box where a user can enter a stock symbol, after that pressing the submit button to get the value of the stock. If the stock symbol is not valid, an error page will be returned.

4.1) Stock Input Page

stockInput.jsp

[code lang=”html”]<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

<f:view>
<html>
<head>
<title>
Stock Input Page
</title>
</head>
<body>
<h:form id="stockForm">

<h1>
Please Enter the Stock Symbol and click the button
</h1>

<p>
<h:inputText id="stockSymbolInput" value="#{stockBean.symbolName}"
required="true">
</h:inputText>

<h:commandButton id="stockSubmit" type="submit" value="Submit Symbol"
action="#{stockBean.findStockValue}">
</h:commandButton>

</h:form>

</body>
</html>
</f:view>[/code]
The above stock input page renders a text-box for entering the stock symbol for which the value has to be determined. Here, we note the use of the expressions stockBean.symbolBean and stockBean.findStockValue. Later on we will see that these expressions are mapped to a property and a behaviour respectively.

4.2) Stock Output Success Page

stockOutputSuccess.jsp

[code lang=”html”]<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

<!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=UTF-8">
<title>JSP Page</title>
</head>
<body>

<f:view>
<h1>
The Stock Value of the symbol
<h:outputText value="#{stockBean.symbolName}"> </h:outputText>
is
<h:outputText value="#{stockBean.symbolValue}"> </h:outputText>
</h1>
</f:view>

</body>
</html>[/code]
This page will be rendered if the user-entered stock symbol is valid and if it is available in the stock database.

4.3) Stock Output Failure Page

stockOutputFailure.jsp

[code lang=”html”]<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

<!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=UTF-8">
<title>JSP Page</title>
</head>
<body>

<f:view>
<h1>
The Stock symbol
<h:outputText value="#{stockBean.symbolName}"> </h:outputText>
is not found. Please check again.
</h1>
</f:view>

</body>
</html>[/code]
This error page will be displayed if the user-entered stock symbol is not available in the database.

4.4) Java Source

StockValueFetcher.java

[code lang=”java”]package net.javabeat.articles.springjsf.introduction;

import java.util.*;

public class StockValueFetcher {

private Map<String, String> stockSymbolsAndValues;

private String symbolName;
private String symbolValue;

public StockValueFetcher() {
stockSymbolsAndValues = new HashMap<String, String>();
stockSymbolsAndValues.put("ABC", "10");
stockSymbolsAndValues.put("DEF", "20");
stockSymbolsAndValues.put("GHI", "30");
stockSymbolsAndValues.put("JKL", "40");
}

public String getSymbolName() {
return symbolName;
}

public void setSymbolName(String symbolName) {
this.symbolName = symbolName;
}

public String getSymbolValue() {
return symbolValue;
}

public void setSymbolValue(String symbolValue) {
this.symbolValue = symbolValue;
}

public String findStockValue(){
boolean symbolFound = stockSymbolsAndValues.containsKey(symbolName);
if (symbolFound){
symbolValue = stockSymbolsAndValues.get(symbolName);
return "stockOutputSuccess";
}else{
return "stockOutputFailure";
}
}
}[/code]
This class maintains a map of stock symbols keyed with stock values. Note that the stock information is directly maintained in the Application since this is just a sample Application. Also, it has getters and setters for holding the stock symbol and the value for the stock symbol. Note that the method findStockValue() will be fired when the user clicks the submit button after entering the stock value. If the stock symbol is valid, the output will be redirected to the success page, else the failure page would be displayed with the appropriate message.

4.5) Faces Configuration

faces-config.xml

[code lang=”xml”]<?xml version=’1.0′ encoding=’UTF-8′?>

<faces-config version="1.2"
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">

<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>

<managed-bean>
<managed-bean-name>stockBean</managed-bean-name>
<managed-bean-class>
net.javabeat.articles.springjsf.introduction.StockValueFetcher
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>

<navigation-rule>
<description>Navigation from the hello page.</description>
<from-view-id>/stockInput.jsp</from-view-id>
<navigation-case>
<from-outcome>stockOutputSuccess</from-outcome>
<to-view-id>/stockOutputSuccess.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>stockOutputFailure</from-outcome>
<to-view-id>/stockOutputFailure.jsp</to-view-id>
</navigation-case>
</navigation-rule>

</faces-config>[/code]
The above configuration file has 3 sections. The first one specifies to use the Spring Resolver for identifying any Spring Beans and making them available into the JSF Application Context. The second one declares a managed bean instance. We will see that this Managed Bean will be resolved from Spring Application context. The third section deals with the navigation rule. For the valid user input, the control goes to the stockOutputSuccess page, else to the stockOutputFailure page.

4.6) Application Context

applicationContext.xml

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="stockBean"
class="net.javabeat.articles.springjsf.introduction.StockValueFetcher">
</bean>

</beans>[/code]
The above code snippet shows the Spring Bean declaration for the StockValueFetcher class. This Bean will be read by the Spring IOC and the Spring Resolver will make the Bean available to JSF Environment.

4.7) Web Configuration

web.xml

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

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

<session-config>
<session-timeout>30</session-timeout>
</session-config>

<welcome-file-list>
<welcome-file>faces/stockInput.jsp</welcome-file>
</welcome-file-list>
</web-app>[/code]
In the above code snippet, we find the declaration of ContextLoaderListener. This is needed for loading the Spring’s Web Application Context. The contextConfigLocation tells where to look for the declaration of Spring Beans.

5) Conclusion

Spring provides a greater degree of flexibility for integration with other Web frameworks. This article provided an introduction to Spring-JSF Integration. More specifically it guided how to make Spring Beans visible to JSF Application Context.
By having this kind of integration, we can get all the benefits of Spring Beans into the JSF Environment. Above all, the Integration is not very complex. It is all about replacing the default JSF Resolver in the Application’s Configuration file.
If you have any doubts on the spring framework integration with JSF, please post it in the comments section. Also search in our website to find lot of other interesting articles related to the spring framework. There are some interesting articles about spring framework, interview questions, spring and hibernate integration, spring web services, etc.

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

If you would like to receive the future java articles from our website, please subscribe here.

Filed Under: Spring Framework Tagged With: JSF, Spring Integration

JSF implementations – Ajax4Jsf, RichFaces and IceFaces

July 16, 2007 by Krishna Srinivasan Leave a Comment

Introduction

With the advent of internet, there has been constant paradigm change from time and again. There are many scripting web languages which came and showed their impact now and then. But the feature I am going to talk about will give a close look to internet as a close friend.In this article, I am trying to showcase the use of AJAX i.e. Asynchronous JavaScript and XML using JSF i.e. JavaServer Faces based components.The pre–requisite for this is some knowledge on JSF and AJAX.There are many JSF implementations for AJAX which help us to provide AJAX features using JSF. Why at all we use JSF and not Struts?. That’s a very typical question people now days ask. Unlike Struts, JSF allows you to create custom components extending standard components. Struts doesn’t provide user to explore the User Interface (UI), but JSF does. There are many typical differences between JSF and Struts.

also read:

  • JSF Interview Questions
  • Request Processing Lifecycle phases in JSF
  • Accessing Web Services from JSF applications
  • Navigation model in JSF

But let’s just focus on JSF and AJAX. As we all know AJAX provide us quick response. How? Using asynchronous response / request mechanism. Your request goes to server, which internally does some calculations and provides the response back while you can do other things on the same page. For example, GMAIL. We normally fascinate those things that are friendly to user and as developers try to implement the same in our business applications. So here we go…

Different AJAX implementations for JSF

There are various AJAX–based JSF implementations available today. But you may ask why we use those. Well, it provides ease of development and reusability. Of course, we can make our own components and implement them using AJAX functionality but the development time will be steep.Various AJAX–based JSF implementations are Ajax4JSF, TomaHawk, RichFaces, Trinidad, IceFaces,and many others. All of them provide one or more components to make developers time less.For example, there are some nice Calendar features, Drag ‘n’ Drop, Auto Complete, Dynamic Loading, and what not.

  • JSF books

But each may be different from the other. One may find that one implementation limits in number of components,
other is limited in documentation, support, examples, and learning curve.The best choice which I could make is with the use of JSF Matrix. If one looks, it will give clear picture what components are provided, how much documentation, active forum support, license issues and the like.Evaluating each one of them, I short listed few like Ajax4JSF, RichFaces and IceFaces. My discussion will focus on these three. The reason I have short–listed them, is because of the number of components, active forum, documentation, open license support and active forum to least. I worked with Netbeans 5.5, but they could easily work with other Integrated Development Environments (IDEs) as well.

Ajax – enabled JSF using Ajax4JSF

Introduction to Ajax4JSF

Ajax4JSF is an Open Source framework which adds AJAX capabilities to JSF using component library without having to write JavaScript code in your web page. Its now under Red Hat and Exadel strategic partnership hence its open source and can be used in your application(s) without sharing your own code.

To make JSF application(s) AJAX enabled

Ajax4JSF provide various features including lifecycle of JSF such as validation,
conversion facilities and management of static and dynamic resources. The look and feel using Ajax4JSF is highly customizable and easily added to JSF applications.Ajax4JSF follows page–oriented approach rather traditional component–oriented approach. By this it means that you can define events on a page which invokes a Managed Bean, and that will render data on the same page, without page refresh. For a particular component one can invoke action or action listener. By this it means that when action is called a particular event occurs that initiate some logic, but action listener may invoke some set of components to be rendered on a page.

Ajax4JSF Example

It’s comparatively easy to use Ajax4JSF in one’s application. Let’s take Netbeans 5.5 as our IDE.
Download the latest Ajax4JSF binary/source to embed in your application from Ajax4JSF Downloads. Once that is done, make a Netbeans Web Application project which is JSF enabled. Then update the Netbeans with Ajax4JSF files. In that one has to copy the ajax4jsf.jar and oscache–2.3 .jar files into the WEB–INF/lib folder of existing JSF application.Then in any web page include Ajax4JSF using tag library:
With this done, our project will be Ajax4JSF enabled. One more thing, one is free to use Ajax4JSF in certain required pages. So one can even customize application to use various other JSF implementations as well.A small snippet for Ajax4JSF:

[code lang=”html”]

&lt;a4j:form&gt;

&lt;table width="600" border="0"&gt;
&lt;tr&gt;
&lt;td width="120" valign="top" rowspan="3" &gt;

&lt;h:selectOneListbox id="list" value="#{backingBean.selectedId}"&gt;
&lt;a4j:support event="onclick" action="#{backingBean.changeCurrent}" reRender="info"/&gt;
&lt;f:selectItems value="#{backingBean.selectList}"/&gt;
&lt;/h:selectOneListbox&gt;
&lt;/td&gt;
&lt;td valign="middle" &gt;
&lt;h:panelGrid id="info" styleClass="panel" rowClasses="celltop, cellmiddle, cellbottom" columns="1"&gt;

&lt;h:panelGroup&gt;
&lt;h:outputText value="#{userList.currentUser.prefix}" /&gt;
&lt;h:outputText value=" " /&gt;
&lt;h:outputText value="#{userList.currentUser.firstName}" /&gt;
&lt;h:outputText value=" " /&gt;
&lt;h:outputText value="#{userList.currentUser.lastName}" /&gt;&lt;br /&gt;
&lt;h:outputText value="#{userList.currentUser.address}" /&gt;
&lt;/h:panelGroup&gt;

&lt;h:panelGroup&gt;
&lt;h:outputText value="#{userList.currentUser.jobTitle}" /&gt;&lt;br /&gt;
&lt;/h:panelGroup&gt;

&lt;h:panelGroup&gt;
&lt;h:outputText value="#{userList.currentUser.phone}" /&gt;&lt;br /&gt;
&lt;h:outputText value="#{userList.currentUser.mobile}" /&gt;
&lt;/h:panelGroup&gt;

&lt;/h:panelGrid&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/a4j:form&gt;

[/code]

In the above code, I am populating static data in Managed Bean in to the list box like Name of the person. Based on the selection, a person’s details will pop–up on the same page in the panel defined above.Though Ajax4JSF provides few built–in components but they are few as compared to other core competitors in the market.
Another thing which I find about Ajax4JSF is good that it’s easy to use other AJAX based implementations like Trinidad and JSF implementation like MyFaces. So its kinda blend of different implementations under one hood.

RichFaces

Introduction to RichFaces

RichFaces is a component library for JSF built on top of Ajax4JSF. Well RichFaces typically is lot more different from Ajax4JSF. RichFaces is actually a product of Exadel but now its with JBoss so it’s open source.

To make JSF application(s) AJAX enabled

As it is based on top of Ajax4JSF it provides all the components of Ajax4JSF along with many AJAX and UI Components. One doesn’t have to write a single JavaScript code and can extend the built–in components at the same time. It also provide the skin functionality which provide a web development an altogether new look.RichFaces works on similar lines as do Ajax4JSF with more built–in rendering toolset without modifying component’s functionality and way they are used. Components like datatable allow the developer to specify the width of the table, the number of rows it wants and pagination facility too.I remember for pagination one has to write a complex code, which with the use of RichFaces is practically solved.
One can look at the example implementation at Rich Faces Demo and can use the same in one’s code to enhance the AJAX capability.

RichFaces Example

To use RichFaces is simple. One has to just download the RichFaces package and extract the richfaces-<version>.jar files into the project in which you want to use. Then by including the RichFaces taglib.

[code lang=”html”]

&lt;%@ taglib uri="http://richfaces.ajax4jsf.org/rich" prefix="rich"%&gt;

[/code]

one can use RichFaces components into the required project. For example, if one want to use the table pagination feature using AJAX request, use the tag. The following code describes the same.

[code lang=”html”]

&lt;h:form&gt;
&lt;rich:datascroller for="name" maxPages="3"/&gt;
&lt;rich:spacer height="30"/&gt;
&lt;rich:dataTable width="483" id="name" rows="4" columnClasses="col" value="" var="nameCat"&gt;
&lt;f:facet name="header"&gt;
&lt;rich:columnGroup&gt;
&lt;h:column&gt;
&lt;h:outputText styleClass="headerText" value="Name"/&gt;
&lt;/h:column&gt;
&lt;h:column&gt;
&lt;h:outputText styleClass="headerText" value="Age"/&gt;
&lt;/h:column&gt;

&lt;/rich:columnGroup&gt;
&lt;/f:facet&gt;

&lt;h:column&gt;
&lt;h:outputText value="#{dndDaemon.stName}"/&gt;
&lt;/h:column&gt;
&lt;h:column&gt;
&lt;h:outputText value="#{dndDaemon.age}"/&gt;
&lt;/h:column&gt;
&lt;/rich:dataTable&gt;
&lt;/h:form&gt;

[/code]

ICEFaces

Introduction to IceFaces?

IceFaces is another technology which uses AJAX features in JSF to provide more useful customize features. IceFaces comparatively provides niche technology of AJAX to be used in complex web application particularly J2EE applications, per se. It is a product from ICEsoft. But its open source and one can use it without sharing any of your application code.

To make JSF application(s) AJAX enabled

IceFaces provides loads of in–built features which you just add in terms of its tag library components and make application development simpler. As IceFaces provides AJAX Push feature, which means it updates the page without having to manually page refresh. Now, you will ask, this was happening earlier also with above technologies, so difference lies in the way IceFaces provide collaborative and dynamic enterprise application development.IceFaces provides the AJAX features using rendering the components. This happens using the IceFaces tags which render the said the component as coded in the application. I would like to emphasize on the ease of development and the support one gets from the community. Though its a commercial product yet its open source with satisfactory documentation and user – developer community.

IceFaces Example

To use IceFaces, one has to download the its library. The library can be downloaded from IceFaces Downloads After downloading either one can integrate the libraries into the application or make the IDE IceFaces compatible. One all is set just include the tag library into the application as:

[code lang=”html”]
&lt;%@ taglib uri="http://www.icesoft.com/icefaces/component" prefix="ice" %&gt;
[/code]

Then one can explore the IceFaces various components into one’s application. For example, if any one want to use the built–in pagination support without writing complex pagination code, then do something like this:

[code lang=”html”]
&lt;ice:dataTable
id="inventoryList"
rows="4"
columnClasses="stockColumn, modelColumn, desriptionColumn, odometerColumn, priceColumn"
rowClasses="oddRow, evenRow"

styleClass="tableStyle"
sortColumn="#{inventoryList.sortColumnName}"
sortAscending="#{inventoryList.ascending}"
value="#{inventoryList.carInventory}"
var="item"&gt;

&lt;!– Stock number –&gt;
&lt;ice:column&gt;
&lt;f:facet name="header"&gt;
&lt;ice:commandSortHeader
columnName="#{inventoryList.stockColumnName}"
arrow="true" &gt;

&lt;ice:outputText value="#{inventoryList.stockColumnName}"/&gt;
&lt;/ice:commandSortHeader&gt;
&lt;/f:facet&gt;
&lt;ice:outputText value="#{item.stock}"/&gt;
&lt;/ice:column&gt;

&lt;!– Model number –&gt;
&lt;ice:column&gt;
&lt;f:facet name="header"&gt;
&lt;ice:commandSortHeader
columnName="#{inventoryList.modelColumnName}"
arrow="true" &gt;
&lt;ice:outputText value="#{inventoryList.modelColumnName}"/&gt;
&lt;/ice:commandSortHeader&gt;
&lt;/f:facet&gt;
&lt;ice:outputText value="#{item.model}"/&gt;
&lt;/ice:column&gt;

&lt;!– Description –&gt;
&lt;ice:column&gt;
&lt;f:facet name="header"&gt;
&lt;ice:commandSortHeader
columnName="#{inventoryList.descriptionColumnName}"
arrow="true" &gt;
&lt;ice:outputText value="#{inventoryList.descriptionColumnName}"/&gt;
&lt;/ice:commandSortHeader&gt;
&lt;/f:facet&gt;
&lt;ice:outputText value="#{item.description}"/&gt;
&lt;/ice:column&gt;

&lt;!– Odometer reading –&gt;
&lt;ice:column&gt;
&lt;f:facet name="header"&gt;
&lt;ice:commandSortHeader
columnName="#{inventoryList.odometerColumnName}"
arrow="true" &gt;
&lt;ice:outputText value="#{inventoryList.odometerColumnName}"/&gt;
&lt;/ice:commandSortHeader&gt;
&lt;/f:facet&gt;
&lt;ice:outputText value="#{item.odometer}"/&gt;
&lt;/ice:column&gt;

&lt;!– Price number –&gt;
&lt;ice:column&gt;
&lt;f:facet name="header"&gt;
&lt;ice:commandSortHeader
columnName="#{inventoryList.priceColumnName}"
arrow="true" &gt;
&lt;ice:outputText value="#{inventoryList.priceColumnName}"/&gt;
&lt;/ice:commandSortHeader&gt;
&lt;/f:facet&gt;
&lt;ice:outputText value="#{item.price}"/&gt;
&lt;/ice:column&gt;

&lt;/ice:dataTable&gt;

&lt;ice:panelGrid columns="2"&gt;

&lt;!– Paginator with page controls –&gt;
&lt;ice:dataPaginator id="dataScroll_3"
for="inventoryList"
paginator="true"
fastStep="3"
paginatorMaxPages="4"&gt;
&lt;f:facet name="first"&gt;
&lt;ice:graphicImage
url="./xmlhttp/css/xp/css-images/arrow-first.gif"
style="border:none;"
title="First Page"/&gt;
&lt;/f:facet&gt;
&lt;f:facet name="last"&gt;
&lt;ice:graphicImage
url="./xmlhttp/css/xp/css-images/arrow-last.gif"
style="border:none;"
title="Last Page"/&gt;
&lt;/f:facet&gt;
&lt;f:facet name="previous"&gt;
&lt;ice:graphicImage
url="./xmlhttp/css/xp/css-images/arrow-previous.gif"
style="border:none;"
title="Previous Page"/&gt;
&lt;/f:facet&gt;
&lt;f:facet name="next"&gt;
&lt;ice:graphicImage
url="./xmlhttp/css/xp/css-images/arrow-next.gif"
style="border:none;"
title="Next Page"/&gt;
&lt;/f:facet&gt;
&lt;f:facet name="fastforward"&gt;
&lt;ice:graphicImage url="./xmlhttp/css/xp/css-images/arrow-ff.gif"
style="border:none;"
title="Fast Forward"/&gt;
&lt;/f:facet&gt;
&lt;f:facet name="fastrewind"&gt;
&lt;ice:graphicImage url="./xmlhttp/css/xp/css-images/arrow-fr.gif"
style="border:none;"
title="Fast Backwards"/&gt;
&lt;/f:facet&gt;
&lt;/ice:dataPaginator&gt;
&lt;!– Display counts about the table and the currently displayed page –&gt;
&lt;ice:dataPaginator id="dataScroll_2" for="inventoryList"
rowsCountVar="rowsCount"
displayedRowsCountVar="displayedRowsCount"
firstRowIndexVar="firstRowIndex"
lastRowIndexVar="lastRowIndex"
pageCountVar="pageCount"
pageIndexVar="pageIndex"&gt;
&lt;ice:outputFormat
value="{0} cars found, displaying {1} car(s), from {2} to {3}. Page {4} / {5}."
styleClass="standard"&gt;
&lt;f:param value="#{rowsCount}"/&gt;
&lt;f:param value="#{displayedRowsCount}"/&gt;
&lt;f:param value="#{firstRowIndex}"/&gt;
&lt;f:param value="#{lastRowIndex}"/&gt;
&lt;f:param value="#{pageIndex}"/&gt;
&lt;f:param value="#{pageCount}"/&gt;
&lt;/ice:outputFormat&gt;
&lt;/ice:dataPaginator&gt;
&lt;/ice:panelGrid&gt;
&lt;/center&gt;
[/code]

Well with the sample code provided and examples done its self-evident that IceFaces provides a crisp look to the business application.

Summary

  • JSF books

By going through the AJAX–implementations for JSF, we can see that its lot easier to implement AJAX functionality in upcoming JSF business products. Depending on the requirements and closely working with them, one can select the AJAX–implementations.

Filed Under: JSF Tagged With: Ajax4jsf, JSF

Introduction to Ajax4Jsf

June 27, 2007 by Krishna Srinivasan Leave a Comment

Java Server Faces provided a Component Based Architecture for building User Interface Components for the Web Application. Ajax aims in providing Faster Response to the Client Applications by reloading only the needed Data. Wouldn’t be nice to take the advantages of both Jsf and Ajax for developing Robust Web Applications. Ajax4Jsf provides solution for this. It is the integration of Java Server Faces with Ajax (which stands for Asynchronous JavaScript and Xml), thereby providing Ajax Support to the Jsf UI Components. This article attempts to provide an overview of the Ajax4Jsf Framework which is now an open Source Project in the JBoss Community.

also read:

  • Introduction to Java Server Faces
  • Request Processing Lifecycle phases in JSF
  • Accessing Web Services from JSF applications
  • Navigation model in JSF

2) What is Ajax4Jsf?

Before trying into Ajax4Jsf, it is wise to know about the various pieces of technologies upon which Ajax4Jsf is built. From the name of the Framework itself, one should identity that Ajax (Asynchronous JavaScript and Xml) and Jsf (Java Server Faces), the most two popular technologies, are embedded within it. Let us look into these two technologies first, before delving deep into Ajax4Jsf.
Java Server Faces provides a Component Based Framework for managing and developing User Interface Components in a Web Application. It also provides rich set of Functionalities that includes Event Handling, Configuring the Page Navigation Mechanism, Validation of Client Data, Data Conversion etc. It also provides a Pluggable Architecture wherein Developers can develop their own Custom User Interface Components and plug with ease into the Framework. One of the major features of the Jsf Framework is that it is not targeted to one type of Clients. It means that apart from Html Browser Clients for the Desktop, it is even possible to have Wml Browser Clients for the mobile phones.
Ajax which stands for Asynchronous JavaScript and Xml is not new. A smarter way of using the existing standards/technologies like JavaScript, Xml and Html gave birth to Ajax. Using Ajax, it is possible for the JavaScript Code to directly communicate with the Server End. The request and the response data between Client and Server is exchanged in Xml Format. One of the major advantages of using Ajax is that it is speed up the performance of the Web Application by loading only the portion of the Web Page in consideration, thereby establishing better results.
Now it’s time to have a look on Ajax4Jsf. As one would have guessed, Ajax4Jsf is a Framework, which, when included in a Web Application will add Ajax support for the Jsf Components. Since Jsf is a Component Based Framework, it is easy to Construct Additional Components which provided Ajax Support to the Jsf Pages. So, all the Components in the Ajax4Jsf Library are nothing but extension to Jsf Components. The transparent use of Java Script Code along with Xml Http Request Objects will be taken care by the Framework itself which means that Developer don’t have to mix Java Script Code into their Application. Let us look into the Internals of the Ajax4Jsf Framework in detail in the next section.

3) Ajax4Jsf Internals

Before looking into the Ajax4Jsf internals, let us look briefly into the Architecture of Jsf. It is worth to look into the Architecture of Jsf first before getting into the details.
In Java Server Faces, whenever a Client makes a Request comes for a Resource, it is intercepted by the Faces Servlet (as represented by the javax.faces.webapp.FacesServlet). This Servlet will make the Client Request that will go through the six different Life cycle Phases like View Restoration Phase, Applying the Request Values, Validation of User Inputs, Updating the Model Objects, Execution of Application and finally Response Rendering. Ajax4Jsf is a framework that adds support to existing Jsf Application. In fact, Ajax4Jsf Framework is implemented as a Filter thereby adding JavaScript function and XmlHttpObject dependencies to the existing Jsf Components. But when the Request is a Ajax4Jsf Request, the whole things changes. Specially, whenever a Request is made by the User, a Java Script Event is fired which is processed by the Ajax Engine that usually sits in the Client Side. Now it’s the Job of the Ajax Engine to submit to original Request to the Ajax4Jsf, which means that the Request will be intercepted by the Ajax4Jsf Filter. Then the Conversion of the Data to the Xml Format will take place here through the various Xml Filters after which the Request is forwarded to the original Faces Servlet thereby making the Request to go through Several Phases.
In the Ajax4Jsf Framework, there are so-called Ajax Containers which represents a Tree of Components along with Request Values that is encoded and decoded during Ajax Request and Response. It is because of the availability of Ajax Engine in the Client updates to portion of Areas in the Web Page is possible.

4) Exploring the Ajax4Jsf Library

This section is dedicated in looking over the Ajax4Jsf Tags for the various Functionalities. Most of the Tags in this Library provide an alternate means for representing the same functionality as achieved by Jsf Tags. Either of the two Tags can be used in such a situation. It is hard to classify the set of tags based on the functionalities and the following sections attempt to provide a brief description about the most commonly used Tags along with some sample snippets.

4.1) Region Tag

Not all the Client Data in a Page is needed by the Server for processing. In most of the cases, only Data from a Portion of a Page is sufficient to process that particular request. This is where the Ajax Region Tag comes into picture. It is a kind of Container Tag meaning that it can hold other Type of Component tags. When components are defined in this Tag, only the values for these components are processed in the Server Side when an Ajax Request is made.
By default, if there is no definition for a Region Tag in a JSP page, then the whole of the JSP Page will be taken as the Ajax Region. Multiple Region Tags within the same Page is also possible.
Following code snippet shows the usage of this Tag,

[code lang=”html”]<a4j:region id = "employeeRegion" actionListener = "#{manager.processEmpData}">
<!– Other Set of Components –>
</a4:region>

<a4j:region id = "stockRegion" actionListener = "#{manager.processStockData}">
<!– Other Set of Components –>
</a4:region>[/code]

In the above code, we have defined two regions, one is the 'employeeRegion' and the other one is the 'stockRegion'. Whenever an Ajax Request is made for the 'employeeRegion' (or 'stockRegion'), then the portion of Data available only with the 'employeeRegion' will be sent to the server (Manager. processEmpData() method) for processing.

4.2) Command Button Tag

This represents a Button Component and can be used to fire Action Events on the Server. This is very similar to the Jsf Command Button Tag, but instead of generating Jsf Request, an Ajax Request will be generated upon Button Click which will be intercepted by the Ajax Engine. There is a useful attribute called 'oncomplete' which can contain JavaScript Code or a JavaScript Function that will get executed once the response comes from the Server.
All the Events like Change Events, Key Events, and Mouse Events etc are applicable to this Tag through the usage of various attributes. The property called 'reRender' will take a comma separated list of Component Identifier that will get re-rendered as soon as control comes from the Server back to the Client.
Following is the code snippet demonstrating the usage of Command Button Tag,

[code lang=”html”]<a4j:commandButton id = "clickButton" value = "Click Me"
action = "#{Listener.processClickRequest}" oncomplete = "jsFunction()">
reRender = "CompId1, CompId2, CompId3"
</a4j:commandButton>[/code]

In the above code, whenever the Button with value 'Click Me' is activated, the method processClickRequest() within the Listener class gets invoked. After that the Components as represented by the Component Ids (CompId1, CompId2 and CompId3) will get the updated value from the Server. Then finally, the Java Script function jsFunction() as mentioned in the 'oncomplete' attribute will be invoked.

4.3) Command Link Tag

There is no great difference between the Command Button and the Command Link apart from their representation, as both manifests a form of Action Components. All the properties that are applicable to Command Button are applicable to Command Link also.
The following code snippet shows the usage of this Component,

[code lang=”html”]<a4:commandLink id = "myLink" value = "This is my Link"
action = "Listener.processMyLink">
</a4:commandLink>[/code]

4.4) Media Output Tag

While the output Text Tag is used to pour normal Character contents, this Tag is used to render Rich Contents back to the Client in the form of Image, Audio or Video. To achieve this, the attribute 'createContent' must provide a method which takes two arguments of type java.io.OuputStream and java.lang.Object. Following is the usage for the same,

[code lang=”html”]<a4j:mediaOutput id = "telephone" element = "img" mimeTye = "image/png"
createContent = "#{ImagePainter.drawImage}">
</a4j:mediaOutput>[/code]

In the above code snippet, the attribute 'element' can take these possible set of values (‘anchor’, ‘image’, ‘object’, ‘applet’) which represents the name of the Html Element that should be used to render this image. Note that 'mimeType' being pointed to image/png file, since we are going to create an array of bytes from an image file that is of type png. Considering the 'createContent' attribute, it takes a Jsf EL Expression whose method takes OutputStream and Object as arguments. Following is the code for the same,
ImagePainter.java

[code lang=”java”]package net.javabeat.articles.ajax4jsf.introduction;

import java.io.*;

public class ImagePainter {

private String fileName = "telephone.png";

public void drawImage (OutputStream output, Object object) throws IOException{

File file = new File(fileName);
byte byteArray[] = new byte[1000];

FileInputStream inputStream = new FileInputStream(file);
while(true){
try{
int bytesRead = inputStream.read(byteArray);
output.write(byteArray, 0, bytesRead);
}finally{
if (inputStream != null){
inputStream.close();
}
}
}
}
}
[/code]

Note that the OutputStream object which is passed as an argument to the drawImage() method should be populated with the byte array pointing to the Image Resource.

4.5) Keep Alive Tag

Assume that a Managed Bean Component has been declared with 'Request' scope in the Configuration File with the help of <managed-bean-scope> tag. Then the Life-time of this Bean Object is valid only for the Current Request. Any attempt to make a reference to the Bean Object after the Request ends will throw in Illegal Argument Exception by the Server because the Bean Object is now invalid.
To avoid these kinds of Exceptions being happening, we can depend on the Keep Alive Tag which is used to maintain the state of the Whole Bean object among subsequent Request. Following is the code snippet for the same,

[code lang=”html”]<a4j:keepAlive beanName = "#{manager.empBean}">
</a4j:keepAlive>[/code]

Note that the attribute must point to a legal Jsf EL Expression which resolves to a Managed Bean instance. For example for the above code the Class definition may look like this,
Manager.java

[code lang=”java”]class Manager{

private EmployeeBean empBean;
// Getters and Setters for empBean.

}[/code]

4.6) Repeat Tag

The Tag implements the Basic Iteration Operation and it is generally preferred to Display a Set of Objects found in a Collection. It is very similar to the functionality available in <h:dataTable> Component. Following is usage scenario for this Tag.

[code lang=”html”]<a4j:repeat id = "repeater" value = "#{manager.empList}" var = "employee">
<h:outputText id = "name" value = "#{employee.name}"/>
<h:outputText id = "age" value = "#{employee.age}"/>
</a4:repeat>[/code]

Assume that we have a Class called Manager which represents a Collection of Employee objects holding two properties namely name and age. Following is the structure of the Manager Class.
Manager.java

[code lang=”java”]public class Manager{

private List<Employee> employees;
// Getters and setters for employees;

}[/code]

Employee.java

[code lang=”java”]public class Employee{

private String name;
private int age;

// Getters and Setters for name and age

}[/code]

If suppose, we want to display the list of Employees in a Page then we can use the Repeat Tag. The 'value' attribute in the Tag usually represents a Collection and the 'var' attribute can be assumed to hold an element from the Collection object. This tag is identically equivalent to a 'for' loop.

[code lang=”java”]for (Employee employee : manager.getEmployees() ){
display(employee.getName());
display(employee.getAge());
}[/code]

4.7) Poll Tag

The Poll Tag is used to Auto Refresh the Current Page by sending Periodic Request to the Server at Regular Intervals by submitting the Form. This can be used in Pages where the View should provide Up-to-Date Information like the Stock Value, Cricket Scores etc. Following is the code snippet demonstrating this Tag.

[code lang=”html”]<a4j:poll id = "refreshId" reRender = "CompId1, CompId2" timeout = "50000"
interval = "1000">
</a4j:poll>[/code]

In the above one, the Page will be refreshed automatically after every 1 second (as mentioned in the 'interval' attribute). Note the 'timeout' attribute set to 50 seconds, which means that after 50 seconds the page would stop to Auto Refresh. The List of Components that are to be re-rendered is specified in the 'reRender' attribute.

4.8) Status Tag

The Status Tag can be used as a kind of Indication to the Client about the current Status of the Request, like whether the Request is still being processed by the Server or the Request has been served. Following is the sample code illustrating the same,

[code lang=”html”]<a4j:status startText = "Request sent to the Server" stopText = "Request is completed">
</a4j:status>
[/code]

In the above case, whenever the Client initiates a Request then the message ‘Request sent to the Server’ (as represented by 'startText' attribute) is displayed until the Request is completely processed in which case the message ‘Request is Completed’ (as represented by 'stopText' attribute) is displayed.

4.9) Support Tag

The mostly commonly used Tag in the Ajax4Jsf Library is the Support which provides Ajax Support to the Jsf Components. It always appears as a Child Tag for the various Jsf Components. Following listing provides the usage of this Tag,

[code lang=”html”]<a4j:inputText id = "userInput">
<a4j:support event = ‘onblur’ action = "#{bean.process}"
binding = "bean.userInput" reRender = "CompId1, CompId2"/>
</a4j:inputText>[/code]

In the above sample, whenever the focus is lost for the user input text Field Component, and then the corresponding process method in the Bean class will be invoked. The 'reRender' attribute defines a list of components whose values are to be updates once the request is over. Note the usage of the 'binding' attribute. This attribute resolves to an EL Expressing which maps to the UIInput Control of the Component represented by userInput. Following is the structure in which the Bean class may look like,
Bean.java

[code lang=”java”]public class Bean{

private UIInput userInput;
//Getters and Setters

}[/code]

5) Sample Application

5.1) Introduction

In this section, let us walk through a Sample Application that makes use of the Ajax4Jsf Libraries. Let the keep the functionalities of this Sample Application to a simpler extent. This is a kind of Auto Complete Application in which whenever the User gives the Bank Account Number, the corresponding details like the name of the Bank, its Branch Name, Customer Name, Balance Details, Contact Details etc will be fetched from the Server. The more important thing to note that is the Request that is sent to the Server is not a normal Jsf Request but instead it is a Ajax Request.

5.2) Web Application Descriptor File

As seen previously, the Ajax4Jsf provides a Filter Servlet for adding Ajax capability for the Jsf Components. So, the web.xml should include a 'filter' tag about the various information about the Filter Servlet.
web.xml

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">

<filter>
<display-name>Ajax4jsf Filter</display-name>
<filter-name>ajax4jsf</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>

<filter-mapping>
<filter-name>ajax4jsf</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>

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

<session-config>
<session-timeout>30</session-timeout>
</session-config>

<!– Welcome files –>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>[/code]

As we can see from the above Xml File, apart from the normal Faces Servlet information, a Filter Servlet has been embedded to add Ajax capabilities for the Client Requests.

5.3) Faces Configuration File

The Faces Configuration file (faces-config.xml) contains only one entry that represents a Managed Bean object. As we will see in the later sections, this Managed Bean will contain the logic for creating some Dummy Account Information as well as contains the logic for fetching the appropriate Account Information. Following is the code for faces-config.xml file.
faces-config.xml

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>

<faces-config version="1.2" 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">

<managed-bean>
<managed-bean-name>accountSearcher</managed-bean-name>
<managed-bean-class>
net.javabeat.articles.ajax4jsf.introduction.AccountSearcher
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>[/code]

5.4) Jsp File containing Jsf and Ajax4Jsf Tags

The following Jsp page presents an Interface to the user, when the User is given a Text-Field prompting to enter the Account Information. If the Account Number entered in valid, which is done by comparing the list of Account Objects, then the corresponding related Information of the Account will be populated in the View.
index.jsp

[code lang=”html”]<html>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="https://ajax4jsf.dev.java.net/ajax" prefix="a4j" %>

<f:view locale="en">
<head>
<title>Account Details</title>
</head>

<body>

<h:form id="form">

<h2>Enter the Account number and tab out for getting further information</h2>

<h:panelGrid columns="2">

<h:outputLabel for = "AccountNo" value = "Account Number:"/>
<h:inputText id = "AccountNo"
binding = "#{accountSearcher.accountTextField}"
size = "6" required="true">
<f:validateLength minimum="6" maximum="6"/>
<f:convertNumber type = "number" />
<a4j:support event = "onblur" immediate="true"
actionListener = "#{accountSearcher.search}"
reRender = "BankName, CustName, BranchName, OpenDate,
ClosingBalance, Address, EmailId, PhoneNumber"/>
</h:inputText>

</h:panelGrid>

<hr>
<p>Bank Details:

<h:panelGrid columns="2">

<h:outputLabel for = "BankName" value = "Bank Name:"/>
<h:inputText id = "BankName" size="25"
binding = "#{accountSearcher.bankNameTextField}"
value = "#{accountSearcher.account.bankName}"/>

<h:outputLabel for = "CustName" value = "Customer Name"/>
<h:inputText id = "CustName" size="15"
binding = "#{accountSearcher.customerNameTextField}"
value = "#{accountSearcher.account.customerName}"/>

<h:outputLabel for = "BranchName" value = "Branch Name"/>
<h:inputText id = "BranchName" size="15"
binding = "#{accountSearcher.branchNameTextField}"
value = "#{accountSearcher.account.branchName}"/>

<h:outputLabel for = "OpenDate" value = "Open Date"/>
<h:inputText id = "OpenDate" size="15"
binding = "#{accountSearcher.openDateTextField}"
value = "#{accountSearcher.account.openDate}"/>

<h:outputLabel for = "ClosingBalance" value = "Closing Balance"/>
<h:inputText id = "ClosingBalance" size="15"
binding = "#{accountSearcher.closingBalanceTextField}"
value = "#{accountSearcher.account.closingBalance}"/>

</h:panelGrid>

<hr>
<p>Contact Details:

<h:panelGrid columns="2">

<h:outputLabel for = "Address" value = "Address"/>
<h:inputTextarea id = "Address"
binding = "#{accountSearcher.addressTextArea}"
value = "#{accountSearcher.account.address}"/>

<h:outputLabel for = "EmailId" value = "EMail Id"/>
<h:inputText id = "EmailId" size="15"
binding = "#{accountSearcher.emailIdTextField}"
value = "#{accountSearcher.account.emailId}"/>

<h:outputLabel for = "PhoneNumber" value = "Phone Number"/>
<h:inputText id = "PhoneNumber" size="15"
binding = "#{accountSearcher.phoneNumberTextField}"
value = "#{accountSearcher.account.phoneNumber}"/>

</h:panelGrid>

</h:form>
</body>

</f:view>

</html>[/code]

The main thing to observe in the Jsp Page is for the <a4j:support> tag which is embedded within the <h:inputText> tag representing the Account Number. Since we want support for the Account Number Text-Field we have done like this. That’s all, just by adding this support Tag within the Jsf UI Components, automatically Ajax Support will be applicable to the JSF UI Components. The attribute 'event' is set to 'onblur' which means that the corresponding listener method as represented by the 'actionListener' attribute (search() defined inside the AccountSearcher class) will be called when the focus is lost from the Text Field control (which means after tabbing out from the Control). The most significant attribute is the support tag is the 'reRender' attribute which takes a comma separated list of Component Identifiers that want to be re-rendered once the control returns back from the Server.
The 'binding' attribute evaluates to a Jsf EL Expression, if specified will map to the corresponding UI Component in the Backing Bean Class. For example, consider the following code snippet,

[code lang=”html”]<h:inputText id = "AccountNo" binding = "#{accountSearcher.accountTextField}">
</h:inputText>[/code]

The binding expression is given as "#{accountSearcher.accountTextField}, which means that the Input Control directly maps to a property by name accountTextField in the AccountSearcher class which is of type javax.faces.component.UIInput. Following is the Java Code for the same,
AccountSearcher.java

[code lang=”java”]public class AccountSearcher {

private UIInput accountTextField;
// Getters and Setters for the same.

}
[/code]

5.5) Account.java

Following is the class that encapsulates pieces of information like Account Number, Bank Name, Customer Name, Branch Name, Account Opening Date, Contact Information inside the Account class. Following is the complete Listing for the Account.java class.
Account.java

[code lang=”java”]package net.javabeat.articles.ajax4jsf.introduction;

import java.util.Date;

public class Account {

private long accountNo;
private String bankName;
private String customerName;
private String branchName;
private String openDate;
private double closingBalance;
private String address;
private String emailId;
private String phoneNumber;

public Account() {
}

public long getAccountNo() {
return accountNo;
}

public void setAccountNo(long accountNo) {
this.accountNo = accountNo;
}

public String getBankName() {
return bankName;
}

public void setBankName(String bankName) {
this.bankName = bankName;
}

public String getCustomerName() {
return customerName;
}

public void setCustomerName(String customerName) {
this.customerName = customerName;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getEmailId() {
return emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

public String getBranchName() {
return branchName;
}

public void setBranchName(String branchName) {
this.branchName = branchName;
}

public String getOpenDate() {
return openDate;
}

public void setOpenDate(String openDate) {
this.openDate = openDate;
}

public double getClosingBalance() {
return closingBalance;
}

public void setClosingBalance(double closingBalance) {
this.closingBalance = closingBalance;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}[/code]

5.6) AccountCreator.java

This Utility Class is used to create Dummy Account Information Objects and acts as Storage for those Account Objects. When looked-up for an Account object by giving the Account Number as a Key, the appropriate Object is returned. The Managed Bean references this Class heavily for creating and retrieving Account Objects. Following listing is the complete code for AccountCreator.java
AccountCreator.java

[code lang=”java”]package net.javabeat.articles.ajax4jsf.introduction;

import java.util.HashMap;
import java.util.Map;

public class AccountCreator {

private static Map<Long, Account> accounts;

public static void createTestAccounts(){
if (accounts == null || accounts.isEmpty()){
accounts = new HashMap<Long, Account>();
}

Account account = null;
account = createAccountInfo(123456, "Hdfc Bank",
"Jenny", "Shastri Nagar, Chennai",
"10/05/2003", 100033.53, "Address1",
"jenny@gmail.com", "99123456789");
accounts.put(account.getAccountNo(), account);

account = createAccountInfo(234567, "Icici Bank",
"Joseph", "Besant Nagar, Chennai",
"121/09/2001", 3200033.53, "Address2",
"joseph@gmail.com", "99987654321");
accounts.put(account.getAccountNo(), account);
}

private static Account createAccountInfo(long accountNo, String bankName,
String customerName, String branchName, String openDate,
double closingBalance, String address, String emailId, String phoneNumber){

Account account = new Account();
account.setAccountNo(accountNo);
account.setBankName(bankName);
account.setCustomerName(customerName);
account.setBranchName(branchName);
account.setOpenDate(openDate);
account.setClosingBalance(closingBalance);
account.setAddress(address);
account.setEmailId(emailId);
account.setPhoneNumber(phoneNumber);
return account;
}

public static Account getAccountInfo(Long accountNo){
return accounts.get(accountNo);
}
}[/code]

5.7) Account Searcher.java

This Managed Bean takes care of creating Dummy Account Objects and it returns the appropriate Account Information back to the Client upon Request. Most of the code in this class represents the getters and the setters for the various UI Components in the Jsp Page. The search logic is implemented in the search() method which takes ActionEvent as its only parameter. Following is the code for the same.
AccountSearcher.java

[code lang=”java”]package net.javabeat.articles.ajax4jsf.introduction;

import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

public class AccountSearcher {

private Account account;

private UIInput accountTextField;
private UIInput bankNameTextField;
private UIInput customerNameTextField;
private UIInput branchNameTextField;
private UIInput openDateTextField;
private UIInput closingBalanceTextField;
private UIInput addressTextArea;
private UIInput emailIdTextField;
private UIInput phoneNumberTextField;

public AccountSearcher() {
AccountCreator.createTestAccounts();
}

public void search(ActionEvent actionEvent){

String strAccountNo = (String)getAccountTextField().getSubmittedValue();
long accountNo = 0L;
try{
accountNo = Long.parseLong(strAccountNo);
account = AccountCreator.getAccountInfo(accountNo);
if (account != null){
setComponentsValueToNull();
}else{
// Error Message.
}
}catch(Exception exception){
exception.printStackTrace();
}
}

private void setComponentsValueToNull(){
bankNameTextField.setSubmittedValue(null);
customerNameTextField.setSubmittedValue(null);
branchNameTextField.setSubmittedValue(null);
openDateTextField.setSubmittedValue(null);
closingBalanceTextField.setSubmittedValue(null);
addressTextArea.setSubmittedValue(null);
emailIdTextField.setSubmittedValue(null);
phoneNumberTextField.setSubmittedValue(null);
}

public Account getAccount() {
return account;
}

public void setAccount(Account account) {
this.account = account;
}

public UIInput getAccountTextField() {
return accountTextField;
}

public void setAccountTextField(UIInput accountTextField) {
this.accountTextField = accountTextField;
}

public UIInput getBankNameTextField() {
return bankNameTextField;
}

public void setBankNameTextField(UIInput bankNameTextField) {
this.bankNameTextField = bankNameTextField;
}

public UIInput getCustomerNameTextField() {
return customerNameTextField;
}

public void setCustomerNameTextField(UIInput customerNameTextField) {
this.customerNameTextField = customerNameTextField;
}

public UIInput getBranchNameTextField() {
return branchNameTextField;
}

public void setBranchNameTextField(UIInput branchNameTextField) {
this.branchNameTextField = branchNameTextField;
}

public UIInput getOpenDateTextField() {
return openDateTextField;
}

public void setOpenDateTextField(UIInput openDateTextField) {
this.openDateTextField = openDateTextField;
}

public UIInput getClosingBalanceTextField() {
return closingBalanceTextField;
}

public void setClosingBalanceTextField(UIInput closingBalanceTextField) {
this.closingBalanceTextField = closingBalanceTextField;
}

public UIInput getAddressTextArea() {
return addressTextArea;
}

public void setAddressTextArea(UIInput addressTextArea) {
this.addressTextArea = addressTextArea;
}

public UIInput getEmailIdTextField() {
return emailIdTextField;
}

public void setEmailIdTextField(UIInput emailIdTextField) {
this.emailIdTextField = emailIdTextField;
}

public UIInput getPhoneNumberTextField() {
return phoneNumberTextField;
}

public void setPhoneNumberTextField(UIInput phoneNumberTextField) {
this.phoneNumberTextField = phoneNumberTextField;
}
}
[/code]

Take a careful look at the implementation of the Search Logic. After getting the submitted value of the Account Text Field by calling UIInput. getSubmittedValue(), the code tries to perform a lookup operation in the Account Storage. If an Account object is obtained, then the code explicitly sets all the submitted information of the UI Components to Null. This is necessary because by setting all the Submitted Value of the Input Components to null, we are ensuring that the Component’s Value will be taken from the appropriate Model Objects.

6) Conclusion

Many of the Vendors have started using Ajax4Jsf Framework in their Web Applications due to its simplicity. No need to depend on JavaScript code to make use of Ajax Functionality. This article initially focused on explaining the need to have another Framework for the Web Tier. Then it provided a Brief Information about the Workflow that happens in an Ajax4Jsf enabled Web Application. Then the most commonly used Ajax4Jsf Tags are explained in detail. Finally the article concluded by giving a Sample AutoComplete Application for populating the User Account Information when given the Account Number.

Filed Under: JSF Tagged With: Ajax4jsf, JBoss, JSF, Richfaces

Introduction to Java Server Faces(JSF) HTML Tags

June 20, 2007 by Krishna Srinivasan Leave a Comment

1) Introduction

Development of compelling JSF applications requires a good grasp of the JSF tag libraries-core and HTML-that represent a combined total of 43 tags. Because of their prominence in the JSF framework, here you have been provided in-depth coverage of some of those HTML tags, and how you can best use them. Even simple JSF pages use tags from both libraries. Many JSF pages have a structure similar to this:

also read:

  • Introduction to JSF
  • JSF Interview Questions
  • Request Processing Lifecycle phases in JSF

[code lang=”html”]&lt;%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %&gt;
&lt;%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %&gt;

&lt;f:view&gt;
&lt;h:form&gt;
…
&lt;/h:form&gt;
&lt;/f:view&gt;[/code]

To use the JSF tag libraries, you must import them with Taglib directives, as in the preceding code fragment. You can choose any name you want for the prefixes. The convention is f and h, for the core and HTML libraries, respectively.
Standard Syntax:

[code lang=”html”]&lt;%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %&gt;[/code]

XML Syntax:

[code lang=”html”]&lt;anyxmlelement xmlns:h="http://java.sun.com/jsf/html" /&gt;[/code]

2)An Overview of the JSF HTML Tags

We can group the HTML tags in the following categories:

  • Inputs
  • Outputs
  • Commands
  • Selections
  • Layouts
  • Data Table
  • Errors and messages

3) List of HTML Tags

column, commandButton, commandLink, dataTable, form, graphicImage, inputHidden, inputSecret, inputText, inputTextarea, message, messages, outputFormat, outputLabel, outputLink, outputText, panelGrid, panelGroup, selectBooleanCheckbox, selectManyCheckbox, selectManyListbox, selectManyMenu, selectOneListbox, selectOneMenu, selectOneRadio.
Here I am presenting some of the HTML Tags.

4) data Tag

The dataTable tag renders an HTML 4.01 compliant table element that can be associated with a backing bean to obtain its data as well as for event handling purposes.

The table can be customized extensively using cascading stylesheet (CSS) classes and definitions to enhance the appearance of the table’s headers, footers, columns and rows. Common formatting techniques, such as alternating row colors, can be accomplished quite easily with this tag.
The dataTable tag typically contains one or more column tags that define the columns of the table. A column component is rendered as a single td element.

A dataTable tag can also contain header and footer facets. These are rendered as a single th element in a row at the top of the table and as a single td element in a row at the bottom of the table, respectively.
Example:

[code lang=”html”]&lt;h:dataTable id="table1"value="#{shoppingCartBean.items}" var="item"&gt;
&lt;f:facet name="header"&gt;
&lt;h:outputText value="Your Shopping Cart" /&gt;
&lt;/f:facet&gt;
&lt;h:column&gt;
&lt;f:facet name="header"&gt;
&lt;h:outputText value="Item Description" /&gt;
&lt;/f:facet&gt;
&lt;h:outputText value="#{item.description}" /&gt;
&lt;/h:column&gt;
&lt;h:column&gt;
&lt;f:facet name="header"&gt;
&lt;h:outputText value="Price" /&gt;
&lt;/f:facet&gt;
&lt;h:outputText value="#{item.price}"/&gt;
&lt;/h:column&gt;
&lt;f:facet name="footer"&gt;
&lt;h:outputText value="Total: #{shoppingCartBean.total}" /&gt;
&lt;/f:facet&gt;
&lt;/h:dataTable&gt;[/code]

HTML Output:

[code lang=”html”]
&lt;table id="table1"&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th scope="colgroup"colspan="2"&gt;Your Shopping Cart&lt;/th&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;th&gt;Item Description&lt;/th&gt;&lt;th&gt;Price&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Delicious Apple&lt;/td&gt;&lt;td&gt;$5.00&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Juicy Orange&lt;/td&gt;&lt;td&gt;$5.00&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Tasty Melon&lt;/td&gt;&lt;td&gt;$5.00&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;tfoot&gt;
&lt;tr&gt;&lt;td colspan="2"&gt;Total: $15.00&lt;/td&gt;&lt;/tr&gt;
&lt;/tfoot&gt;
&lt;/table&gt; [/code]

5) form Tag

The form tag renders an HTML form element. JSF forms use the post-back technique to submit form data back to the page that contains the form. The use of the POST method is also required and it is not possible to use the GET method for forms generated by this tag.

If your application requires the use of the GET method for form submission, your options include using plain HTML forms, binding request parameters to backing bean properties, and using the outputLink tag to generate dynamic hyperlinks.
Example:

[code lang=”html”]&lt;h:form id="form1"&gt;
&lt;/h:form&gt;[/code]

HTML Output:

[code lang=”html”]&lt;form id="form1" name="form1" method="post" action="/demo/form.jsp"
enctype="application/x-www-form-urlencoded"&gt;
&lt;/form&gt;[/code]

6) message Tag

The message tag renders a message for a specific component. You can customize the message generated by this component by applying different CSS styles to the message depending on its severity (eg. red for error, green for information) as well as the detail level of the message itself. You can also customize the standard error messages by overriding specific JSF properties in your message bundle.
Example:

[code lang=”html”]&lt;h:inputText id="username" required="#{true}"
value="#{userBean.user.username}"
errorStyle="color:red"/&gt;
&lt;h:message for="username" /&gt;[/code]

HTML Output:

[code lang=”html”]&lt;input type="text" id="form:username"name="form:username" value=""/&gt;
&lt;span style="color:red"&gt;"username": Value is required.&lt;/span&gt;[/code]

  1. <h:panelGrid>
  2. <h:selectBooleanCheckbox>
  3. <h:outputFormat>
  4. <h:inputText&gt
  5. <h:commandButton>

7) panelGrid Tag

The panelGrid tag renders an HTML 4.01 compliant table element. The panelGrid component can be used as a layout manager for a grid-based user interface. It simplifies the task of constructing a layout table to hold form fields, labels, and buttons.
The panelGrid component, like the dataTable component, can be customized extensively using Cascading Style Sheets (CSS). For more information on customizing the appearance of JSF tables using CSS styles, please see the dataTable tag documentation. The panelGrid does not use an underlying data model to provide rows of data for rendering purposes. Rather, this component is a layout container that renders other JSF components in a grid of rows and columns.

By default, a panelGrid component has only one column. You can specify how many columns are used to display the components, and the panelGrid component determines how many rows are needed at rendering time. For example, if you set the number of columns for your panelGrid to 2 and you include 4 component s inside it, the rendered table will have two rows with two columns (“td” cells) in each row.

The layout algorithm for the child components of a panelGrid is as follows. The components are laid out one at a time, from left to right and from top to bottom, starting with the first component and ending with the last component in the order in which the appear inside the panelGrid tag.

The panelGrid renders one component per column and keeps track of how many columns it has rendered. When the number of columns rendered for a particular row is the same as the value of the columns attribute, it starts a new row and continues in this manner until there are no more components to render.

If you want to combine several components into a single column, you can use a panelGroup component. The panelGroup component renders its children but still counts as one component. This is useful for cases where a component only allows one child component, such as the facet tag and the column layout algorithm described above.

You can also define header and a footer facets for the panelGrid. These are rendered as a single th element in a row at the top of the table and as a single td element in a row at the bottom of the table, respectively.
Example:

[code lang=”html”]&lt;h:panelGrid id="panel" columns="2" border="1"&gt;
&lt;f:facet name="header"&gt;
&lt;h:outputText value="#{bundle.signInMessage}"/&gt;
&lt;/f:facet&gt;
&lt;h:outputLabel for="username" value="#{bundle.usernameLabel}" /&gt;
&lt;h:inputText id="username" value="#{userBean.user.username}" /&gt;
&lt;h:outputLabel for="password"value="#{bundle.passwordLabel}" /&gt;
&lt;h:inputText id="password"value="#{userBean.user.password}" /&gt;
&lt;f:facet name="footer"&gt;
&lt;h:panelGroup style="display:block; text-align:center"&gt;
&lt;h:commandButton id="submit" value="#{bundle.submitLabel}" /&gt;
&lt;/h:panelGroup&gt;
&lt;/f:facet&gt;
&lt;/h:panelGrid&gt;[/code]

HTML Output:

[code lang=”html”]&lt;table id="form:panel" border="1"&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th scope="colgroup" colspan="2"&gt;Please sign in&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;label for="form:username"&gt;Username&lt;/label&gt;&lt;/td&gt;
&lt;td&gt;&lt;input id="form:username" name="form:username"
type="text" value=""/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;label for="form:password"&gt;Password&lt;/label&gt;&lt;/td&gt;
&lt;td&gt;&lt;input id="form:password" name="form:password"
type="text" value=""/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;tfoot&gt;
&lt;tr&gt;
&lt;td colspan="2"&gt;
&lt;span style="display:block; text-align:center"&gt;
&lt;input id="form:submit" name="form:submit" type="submit"
value="Submit" onclick="clear_form();"/&gt;
&lt;/span&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tfoot&gt;
&lt;/table&gt;[/code]

8) selectBooleanCheckbox Tag

The selectBooleanCheckbox tag renders an HTML input element of the type checkbox. This component is designed for situations where you want to display an option to the user that can be enabled or disabled, such as a remember me checkbox on a login form
Example:

[code lang=”html”]&lt;h:selectBooleanCheckbox id="remember"
value="#{userBean.user.remember}" /&gt;[/code]

HTML Output:

[code lang=”html”]&lt;input type="checkbox" id="form:remember" name="form:remember"
value="true" /&gt;[/code]

9)outputFormat Tag

The outputFormat tag renders parameterized text and allows you to customize the appearance of this text using CSS styles. Parameterized text is compound text containing placeholder values to be replaced by actual values at rendering time.
Example:

[code lang=”html”]&lt;h:outputFormat value="Welcome, {0}. You have {1} new messages."&gt;
&lt;f:param value="#{userBean.user.firstName}" /&gt;
&lt;f:param value="#{userBean.user.messageCount}" /&gt;
&lt;/h:outputFormat&gt;[/code]

HTML Output:

[code]Welcome, John. You have 12 new messages.[/code]

10) inputText Tag

The inputText tag renders an HTML input element of the type text.
Example:

[code lang=”html”]&lt;h:inputText id="username" value="#{userBean.user.username}" /&gt;[/code]

HTML Output:

[code lang=”html”]&lt;input id="form:username" name="form:username" type="text" /&gt;[/code]

11) commandButton Tag

The commandButton tag renders an HTML submit button that can be associated with a backing bean or ActionListener class for event handling purposes. The display value of the button can also be obtained from a message bundle to support internationalization
Example:

[code lang=”html”]&lt;h:commandButton id="button1" value="#{bundle.checkoutLabel}"
action="#{shoppingCartBean.checkout}" /&gt;[/code]

HTML Output:

[code lang=”html”]&lt;input id="form:button1" name="form:button1" type="submit"
value="Check Out" onclick="someEvent();" /&gt;[/code]

12) Summary

Tags plays an important role in working with JSF Framework. Here i presented only some of the Tags with description and an Example for each. If you want more info about these tags and the remaining tags Please go through the link shown below.

Filed Under: JSF Tagged With: JSF

Introduction to JSF Core Tags Library

June 14, 2007 by Krishna Srinivasan Leave a Comment

1) Introduction

This article introduces about the various Core Tags that are available in JSF. Tags represent some set of Actions that will be executed in the Server. This article assumes the reader to have a fair bit of knowlege in Java Server Faces. If not, then they can visit the Introductory Article in JSF in javabeat. For more information and resources about Java Server Faces. This article will start off with the Major Classification of Core JSF Tags and then will explain in depth about the various different types of Tags that are available in each category. Wherever and whenever possible, Code Snippets are given to make the understanding of the Tags much clearer.

2) Core Tag Library

The Core Tags that are available in Java Server Faces are categorized as follows. Here the categorization is given based on the Functionality of the Tags. They are,

  • Validator Tags
  • Convertor Tags
  • Listener Tags
  • View Tags
  • Select Tags
  • Facet Tag
  • Miscellaneous Tags

Following sections explains the various above mentioned Tags in greater detail.

3) View Tags

3.1) Introduction

View Tags are Container Tags and they used to hold or Group Multiple UI Components. Following are the identified Tags in the JSF Core Library that comes under this category.

  • View Tag
  • Sub View Tag

Subsequent sections will discuss both the View Tags in greater detail.

3.2) View Tag

The View Tag is used to hold all the UI Components in the Display. View Tag can contain a Mix of Html Tags, JSF Core and Custom Tags. The View Tag as identified by <f:view> Tag and it usually contains a set of Form Tags (<h:form>) along with other Action Tags. Localization for the Messages associated with the Component can also be specified in the View Tag. The syntax definition of this View Tag is given below,

[code lang=”html”]
<f:view locale = "localeCodeValue" beforeMethod = "method" afterPhase = "method">
<!– Html and JSF Tags goes here –>
</fview>
[/code]


Following is an example for the View Tag, that holds a Form Component, which is turn is having two Text Components along with a Submit Button.

[code lang=”html”]
<f:view locale = "ja" beforeMethod = "#{MyPhaseListener.beforePhase}"
afterMethod = "#{MyPhaseListener.afterPhase}" >

<h:form>
<p>User name:
<h:inputText value = "#{UserBean.userName}" id = "userNameTextField"
required = "true">
</h:inputText>

<p>Password:
<h:inputSecret value = "#{UserBean.password}" id = "passwordTextField"
required = "true">
</h:inputText>

<h:commandButton value = "Submit" action = "submit"/>

</h:form>

</f:view>
[/code]

In the above code snippet, the locale is set to Japanse (‘ja’ is the Locale Code name for Japanese) and also the the Phase Listener methods is made to call before and after through the help of ‘beforeMethod’ and ‘afterMethod’ attributes.

3.3) Sub View Tag

Sub View represents a portion of the Display in the Entire Page. Sub View may be useful in situations where there is a need for a Main Page which is getting information fetched independently from Different Views. If we wish to represent a portion of a JSP Page as a Sub View, then it has to be embedded into the Sub View Tag with the help of Import/Include Tags (<c:import>, <jsp:include>), and then the Sub View Tag can be embedded within the View Tag. This Tag is identified by <f:subview> and following is the syntax definition for this Tag,

[code lang=”html”]

<f:subview id = "SubViewId">
</f:subview>
[/code]

Assume that there is a Web Page contains several sections like Footer, Header and Advertisements along with other contents. Then subview will be one possible solution for such a kind of View Representation. Consider the following sample which illustrates this,

[code lang=”html”]

<f:view>
<f:subview id = "header">
<jsp:include page = "header.jsp"/>
<– Other Elements Here –>
</f:subview>

<f:subview id = "footer">
<jsp:include page = "footer.jsp"/>
<– Other Elements Here –>
</f:subview>

<f:subview id = "advertisements">
<jsp:include page = "advertisements.jsp"/>
<– Other Elements Here –>
</f:subview>
</f:view>

[/code]

4) Select Tags

4.1) Introduction

These are tags used to select Single or Multiple Entries from Select Components Like List-Box, Check-Box or a Radio-Button. They usually appear as Child Tags under the Select Component Tags and they are used to represent and select Values. The identified Select tags are given as follows.

  • Select Item Tag
  • Select Items Tag

4.2) Select Item Tag

This Tag adds a Single Item to a Single or a Multi Components like (Check-Box, Radio-Button or List). This Tag always appear as Child Tag for the Single/Multi Select Components. The value can be either given in Static or Dynamic form. Below is the syntax definition of the Tag,

[code lang=”html”]

<h:selectItem id = "Id" description = "Some Description" itemValue = "itemValue"
itemLabel = "itemLabel" value = "selectValue">
</h:selectItem>
[/code]

Let us see the static way of giving values with the help of Select Item Tag. Assume that we want to represent a Season List Box Item populated with static values like ‘Summer’, ‘Winter’, ‘Spring’ and ‘Autumn’. They we could use the following to achieve that,

[code lang=”html”]

<h:selectManyMenu id = "seasonListBox">
<f:selectItem itemValue = "Summer_Season" itemLabel = "Summer Season">
<f:selectItem itemValue = "Winter_Season" itemLabel = "Winter Season">
<f:selectItem itemValue = "Spring_Season" itemLabel = "Spring Season">
<f:selectItem itemValue = "Autumn_Season" itemLabel = "Autumn Season">
</h:selectManyMenu>

[/code]

The above code populates a List-Box Component with Values like ‘Summer Season’, ‘Winter Season’, ‘Spring Season’ and ‘Autumn Season’. Note that the value corresponding to ‘itemLabel’ attribute is the one that will be shown to the Clients. The actual value that is sent to the Server is the corresponding value of the attribute ‘itemValue’. Now let us see how to display the value dynamically. For that, the ‘value’ attribute must be specified with the appropriate JSF EL Expression pointing to a Managed Bean Property. Examine the following code,

[code lang=”html”]

<h:selectSingleMenu id = "managerListBox">
<f:selectItem value = "#{User.manager}" >
</h:selectSingleMenu>

[/code]

4.3) Select Items Tag

If Select Item Tag is used to represent a single Value for a Component, then Select Items Tag is used to represent a Collection of Values. As like Select Item Tag, this Tag should appear as a Child Element for the Select Controls (List-Box, Check-Box or Radio-Buttons). This Tag is identified by <f:selectItems> and the following is the syntax representation for the same.

[code lang=”html”]

<f:selectItems id = "Id" value = "valueSet">
</f:selectItems>
[/code]

The ‘value’ attribute must be a JSF EL Expression and it must return a Collection type (List or Set) or a Array type. If the return Type is a Map, then the Map Keys will correpond to the ‘itemLabel’ attribute with the Map Values corresponding to the ‘itemValue’ attributes. Suppose that we have a List of Employees maintained in Backing Bean called Employee and we wish to display the Set of Employee Names in a List Box, then the following Code will help.

Following is the listing of Employee.java which holds a collection of employee names in a List.

Employee.java

[code lang=”java”]
package model;

public class Employee{

private List allEmployeeNames;

public List getEmployeeNames(){
return allEmployeeNames;
}

public void setEmployeeNames(List allEmployeeNames){
this.allEmployeeNames = allEmployeeNames;
}
}

[/code]

And the corresponding JSF Code will look something like the below,

[code lang=”html”]

<h:selectManyMenu id = "managerListBox">
<f:selectItems value = "#{Employee.allEmployeeNames}" >
</h:selectManyMenu>

[/code]

5) Facet Tag

One of the interesting Tag available in JSF Core Tag library is the Facet Tag. One can normally see the usage of a facet Tag in the case of a Complex UI Components (PanelGrid and DataTable) that has Parent-Child Relationship. Before illustrating the uage of Facet, let us look into the sample of Data Table. The DataTable Component identified by (<h:dataTable>)
contains a series of Column Elements (identified by <h:column>) thereby forming a Tabular Structure. Here is the Syntax Definition of the <h:dataTable> Tag.

[code lang=”html”]

<h:dataTable value = "Values" var = "BeanName">

<h:column>
<!– Display of the 1st Column –>
</h:column>

<h:column>
<!– Display of the 2nd Column –>
</h:column>

…

<h:column>
<!– Display of the 3rd Column –>
</h:column>

</h:dataTable>

[/code]

The attribute ‘value’ represents a Collection (or an Array) which is to be iterated over. And the attribute ‘var’ refers to the named identifer for each and every element being iterated. For example, if we have want to display the name, age and the city of an User in an Application in a Tabular Format with the help of <h:dataTable> tag, then we would have written the following code snippet.

[code lang=”html”]

<h:dataTable value = "#{UserManager.allUsers}" var = "anUser">

<h:column>
<h:outputText value = "Name"/>
<h:outputText value = "#{anUser.name}"/>
</h:column>

<h:column>
<h:outputText value = "Age"/>
<h:outputText value = "#{anUser.age}"/>
</h:column>

<h:column>
<h:outputText value = "Country"/>
<h:outputText value = "#{anUser.country}"/>
</h:column>

</h:dataTable>

[/code]

And correspondingly, we would have got the following set of Java Classes for the same. One is the Backing Bean by name UserManager having a property called allUsers, which is of a Collection type. The other Class is the User class which is having name, age and city as properties. Following is the snippet code for UserManager.java class.

UserManager.java

[code lang=”java”]
public class UserManager{

private List allUsers;

public List getAllUsers(){
return allUsers;
}

public void setAllUsers(List allUsers){
this.allUsers = allUsers;
}
}

[/code]

Following is the listing for the Java Class User.

User.java

[code lang=”java”]
public class User{

private String name;
private int age;
private String city;

public String User(){
}

public String getName(){
return name;
}

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

// Getters and Setters for age and country goes here.

}

[/code]

Following would be a sample output (with some sample values) in the Browser if the form containing the above dataTable Tag is rendered.

Sample Output

[code]
Name Age Country
David 33 Sweden
Johnson 32 Australia
Adams 43 Japan
[/code]

Let us come back to the purpose of using Facets here. This dataTable UI Component is a Complex Component which has Child Tags representing the Column Values taken from the User Bean. The Labels ‘Name’, ‘Age’ and ‘Country’, though are part of the DataTable Tag don’t form the Child Elements for this Tag. Such Tags (or UI Components) which are logically Child Components for some Parent Component, but strictly speaking don’t have a defined relation-ship are candidates for Facets. During Rendering of the Parent Component, all the Facet Tags will also be rendered. In our case, the Labels ‘Name’, ‘Age’ and ‘Country’ can be surrounded with Facet Tags like the following,

[code lang=”html”]

<h:dataTable value = "#{UserManager.allUsers}" var = "anUser">

<h:column>
<facet name = "NameLabel">
<h:outputText value = "Name">
</facet>
<h:outputText value = "#{anUser.name}">
</h:column>

<h:column>
<facet name = "AgeLabel">
<h:outputText value = "Age">
</facet>
<h:outputText value = "#{anUser.age}">
</h:column>

<h:column>
<facet name = "CountryLabel">
<h:outputText value = "Country">
</facet>
<h:outputText value = "#{anUser.country}">
</h:column>

</h:dataTable>

[/code]

6) Miscellaneous Tags

6.1) Introduction

Let us see the miscellaneous set of Tags in detail. The following list down the Left-over Tags.

  • Attribute Tag
  • Param Tag
  • Load Bundle Tag
  • Verbatim Tag

6.2) Attribute Tag

The Attribute Tag is used to represent an attribute for the enclosing UI Component. An attribute for a Component is encapsulated in the form of Name and Value. This tag is identified by <f:attribute>. Following is the syntax definition of the Attribute Tag.

[code lang=”html”]
<f:attribute name = "attrName" value = "attrValue">
</f:attribute>
[/code]

For example, the following code snippet associated two attributes (disabled and read-only) to a Text-Field UI Component.

[code lang=”html”]
<h:inputText id = "userNameTextField">
<f:attribute name = "disabled" value = "true"/>
<f:attribute name = "readonly" value = "false"/>
</h:inputText>
[/code]

6.3) Param Tag

The Param Tag which is identified by <f:param> is used to pass parameters to the enclosing UI Components. This Tag always appears as a Child Tag for the Input/Action UI Components. Let us look into the Syntax Declaration.

[code lang=”html”]
<param name = "paramName" value = "paramValue">
<param>
[/code]

Look into the following code snippet about the usage of Param Tags. In the First case, the value of the Param Tags are passed to the Placeholders for the String to be displayed. Whereas, in the second case, when used along with a Command Button/Link, the Component receiving the Request would found the Name/Value Parameters appended to it.

[code lang=”html”]
<h:outputFormat value = "Welcome to {0} company">
<f:param value = "ABC"/>
<h:output>
<h:commandLink action = "#{SomeAction}">
<f:param name = "Param1" value = "Value1"/>
<f:param name = "Param2" value = "Value2"/>
<h:commandLink>
[/code]

6.4) Load Bundle Tag

The Load Bundle Tag is used to load the Bundle (containing the various Components Display Name along with Messages) for an Application. Following is the syntax of <f:loadBundle> Tag.

[code lang=”html”]
<loadBundle basename = "PathToPropFile" var = "refName">
<loadBundle>
[/code]

For example, to load the Bundle File name called ‘MyBundle’ and then to use the various resources in some UI Components, the following can be used for,

[code lang=”html”]
<loadBundle basename = "resources/en/MyBundle" var = "myBundle">
<h:outputText id = "userNameTextField" value = "#{myBundle.userNameMessage}">
</h:output>
<loadBundle>
[/code]

6.5) Verbatim Tag

This Tag is often used when we want to display a Mix of Html and Other Core Tags. This Tag is identified as <h:verbatim> and by default the characters (like <, >, etc.) are not escaped. Is is very equivalent to the Html <Pre> Tag. Consider the following sample,

[code lang=”html”]
<f:verbatim>
<P>This is a Html Paragraph
</f:verbatim>

[/code]

7) Conclusion

This Article is all about Core JSF Tags. Starting with the Broder Level of Classification of the JSF Core Tags, it then brought into picture the various different set of tags that are available. The Various Different Set of Tags like Validator Tags, Converter Tags, Listener Tags, View Tags, Select Tags and Miscellaneous Tags are given healthier discussions along with some sample programs.
Javabeat has published many of the good articles related to Java Server Faces (JSF). This list will help you to learn the basic concepts on JSF and how to start using in your projects, please have a look on these articles when time permits. Don’t forget to leave your feedback on the comments section. This helps us to provide better content for you.

  • JSF Interview Questions
  • Request Processing Lifecycle phases in JSF
  • Accessing Web Services from JSF applications
  • Navigation model in JSF

The above article would provide the higher level of understanding on each concept.  If you would like to know all the features in detail, please buy any of the JSF books listed in the book recommendations for Java Server Faces (JSF). Hope this helps you!!

If you would like to receive future mails on Java articles, please subscribe here.

Filed Under: JSF Tagged With: JSF

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved