AJAX in JSF 2.0

Description

In this post, we will see ho to develop your  first JSF 2 AJAX example.  You will see some recipes that demonstrate the JSF support for AJAX. We start
with some core JSF tags that provide AJAX support and we will continue with frameworks that offer many other AJAX components.

Your first JSF 2.0

In this recipe, you will see how simple it is to use AJAX in JSF 2.0. For this we have built a “HelloWorld” example based on a simple button that when pressed renders a random number on the screen using the AJAX mechanism.

The following screenshot is a capture of this:

Random

How to do it

We start with a simple bean, meant to generate a random number using the  java.util.Random class and we will reuse the project  generated in the precedent post, Getting Started with RichFaces 4using the specialized Maven archetypes.

This bean looks like the following code snippet:

import java.util.Random;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "random")
@SessionScoped
public class RandomNumber {
private Integer random = 0;
Random generator = new Random( 19580427 );
public Integer getRandom() {

random = generator.nextInt();
return random;
}
}

We go further and develop the JSF page that will call the previous bean modifying the index.xhtml page:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Simple JSF2.0-AJAX example</title>
</h:head>
<h:body>
<h:form id="formID" prependId="false">
<strong><h:outputScript</strong> name="jsf.js"
library="javax.faces" target="head"/>
<h:outputText id="randomID" value="#{random.random}"/>
<h:commandButton id="buttonID" value="Random"
onclick="jsf.ajax.request(this, event, {execute:
this.id, render: 'randomID'}); return false;"/>
</h:form>
</h:body>
</html>

That’s it !

You can deploy on your Netbeans IDE the project to see the final result:

SimpleRichFacesLab2

How it works ?

For understanding how it works, we should take a closer look at some code lines.

  1. First, we have the h:outputScript line, which includes the JSF AJAX library into our page (this is necessary for the call to ajaxRequest)
  2. After that, we have an outputText component, which displays the random number from the bean
  3. Third, we have a commandButton, which calls ajaxRequest and returns false when it is clicked.

An ajaxRequest has three arguments, as follows:

  • The calling object, which is this
  • The calling event, which is event
  • The third argument is a little tricky. It contains the execute and render properties.
    The first property takes a list of the IDs of all the JSF components that we would like  to execute, while the second property contains the IDs of all the JSF components that we want to re-render (refresh).

 

Getting Started with RichFaces 4

Description

In this article we will show, the step to install and configure the RichFace framework.

We will set up our working environment so that you can try all the examples. As JSF 2 now has Ajax functionality built-in, we will cover that first and then move on to RichFaces and start showing you how RichFaces extends that functionality.

Setting Up

RichFaces can be used in any container that is JSF 2 compatible. This means all servers compliant with the Java EE 6 specification (JBoss AS6/7, Glassfish 3) and all major servlet containers (Tomcat, Jetty essentially).

Not to tie you to any specific IDE (integrated development environment), but we will use Apache Maven to set up a project. Since RichFaces is built on top of JSF 2, its installation is as easy as adding a few JARs to your project.

In this article, we will use a simple Maven archetype which generate a simple Richfaces project.

Launch the followong command to generate the project structure of a RichFace 4 Web  application:


mvn archetype:generate \
 -DarchetypeGroupId=org.richfaces.archetypes \
 -DarchetypeArtifactId=richfaces-archetype-simpleapp \
 -DarchetypeVersion=4.0.0.Final \
 -DgroupId=com.jasmineconseil.samples.richfaces4  \
 -DartifactId=richfaces4-start

The resulting maven structure is showed here:

richfaces4-start
/src
/target
pom.xml
readme.txt

The project comes with a simple one-page application.

Let’s deploy and run the project to make sure everything works. If you open the readme.txt file, you will see the commands to build the application for either a Tomcat or a JBoss 6 server, here we choose Tomcat 7 target:

SelectDeploymentServer

As you can see, creating a new RichFaces 4 project is very simple and you can easily open it in any IDE that supports importing a Maven-based project.

There are two ways to import the Maven project into Eclipse. One method is to execute the following command inside the project root folder:

mvn eclipse:eclipse -Dwtpversion=2.0

This command makes it possible to import the project into Eclipse by adding Eclipse project configuration files such as .project and .classpath.

Once you run this command in NetBeans, select File/Open Project into Workspace and point to the project root directory.

Click on the Run button and you will see into your favourite browser at the URL http://localhost:8084/richfaces4-start/ the deployed application in action:

RichFaces

Configuring RichFaces

There is nothing you actually need to do to configure RichFaces ! If you look inside the web.xml file in the generated project, you will see no mention of a RichFaces filter. Starting with RichFaces 4, you don’t need to register a filter in the web.xml file. If RichFaces JARs are present in the project, RichFaces will be used !

here the extract of the pom dependency of the generated project:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>org.richfaces.book</groupId>
<artifactId>richfaces4-start</artifactId>
<name>RichFaces 4 Application - Starting</name>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<url>http://jboss.org/richfaces</url>

<repositories>
<repository>
<id>jboss-public-repository-group</id>
<name>Jboss Repository for Maven</name>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>java-net</id>
<name>Java.net Maven Repository</name>
<url>http://download.java.net/maven/2</url>
</repository>
</repositories>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Setting this property using archetype-metadata.xml requiredPorperty
so that generated project uses correct version of richfaces.
-->
<org.richfaces.bom.version>4.0.0.Final</org.richfaces.bom.version>
<netbeans.hint.deploy.server>Tomcat</netbeans.hint.deploy.server>
</properties>

<build>
<finalName>richfaces4-start-${project.version}</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webResources>
<resource>
<directory>${basedir}/src/main/java</directory>
<targetPath>/WEB-INF/src</targetPath>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>

<profiles>
<profile>
<id>jee6</id>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webappDirectory>${project.build.directory}/${project.build.finalName}-jee6</webappDirectory>
</configuration>
</plugin>
</plugins>
</build>

<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<executions>
<execution>
<id>jee6</id>
<phase>package</phase>
<goals>
<goal>war</goal>
</goals>
<configuration>
<webappDirectory>${project.build.directory}/${project.build.finalName}-jee6</webappDirectory>
<classifier>jee6</classifier>
<packagingExcludes>WEB-INF/lib/jsf-api*,WEB-INF/lib/jsf-impl*</packagingExcludes>
<warSourceExcludes>WEB-INF/lib/jsf-api*,WEB-INF/lib/jsf-impl*</warSourceExcludes>
</configuration>
</execution>
</executions>
<configuration>
<webResources>
<resource>
<directory>${basedir}/src/main/java</directory>
<targetPath>/WEB-INF/src</targetPath>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.richfaces</groupId>
<artifactId>richfaces-bom</artifactId>
<version>${org.richfaces.bom.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.richfaces.ui</groupId>
<artifactId>richfaces-components-ui</artifactId>
</dependency>
<dependency>
<groupId>org.richfaces.core</groupId>
<artifactId>richfaces-core-impl</artifactId>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>

<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

<!-- Tests -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>5.10</version>
<classifier>jdk15</classifier>
<scope>test</scope>
</dependency>
</dependencies>
</project>

web.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">
<display-name>Sample RichFaces 4 Application</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.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>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<mime-mapping>
<extension>ecss</extension>
<mime-type>text/css</mime-type>
</mime-mapping>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>

Configuring a Skin

The only feature you might want to configure is a RichFaces skin.

</pre>
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>japanCherry</param-value>
</context-param>
<pre>

Now that we have seen the fundamental of a Richfaces application, let’s delve into the detail of the development of Ajax features in the next article, AJAX in JSF 2.0

JSF 2 : A brief recall

JSF2

JSF 2 : what is it ?

JSF stands for JavaServer Faces and is an API (basically, it’s some Java interfaces). To use JSF, you need an implementation (which means you need Java classes that implement those interfaces). There are many implementations: the reference implementation from Sun and popular others like Icefaces, PrimeFaces (last one) and RichFaces.

In this section,  we will user the Richfaces implementation from JBoss. JSF is a Java framework for building browser-based user interfaces (UIs) out of reusable components. The emphasis here is on UI components. You won’t be dealing with the markup (HTML)  directly as you are probably used to doing, because JSF components will provide all the necessary user interface widgets to build the application. Within the components themselves, renderers (Java classes for generating HTML) are responsible for producing the appropriate markup. Because you are building web applications and the client is basically the browser, the markup needed is HTML (although it can be anything like WML, SGL, or even XML), so the components’ renderers will generate the HTML markup that will be sent to the client (browser).

Finally, it’s important to point out that JSF is a standard technology for building web applications. It is part of the Java EE 5 stack.

JSF Architecture

JSF implements what is known as the Model 2 pattern, which is based on the MVC architecture.

If you look at how the Model 2 pattern is applied in a JSF application, you can see it consists of three elements—the view, the navigation model, and the application
logic, as shown in the MVC architecture :

MVC architecture with JSF (Model 2)

Model

With JSF, the concept of a managed bean has been introduced. The managed bean is the glue to the application logic—backing code or backing bean. Managed beans are defined in the faces-config.xml and give the application developer full access to all the mapped backing bean’s methods. This concept of IoC is successfully used in frameworks such as Spring framework, for example.

View

The JSF view layer describes the intended layout, behavior, and rendering of the application. One of the cornerstones of a JSF application is the UIComponent. UIComponents are the foundation of the JSF view layer and represent the behavior and structure of the application. A developer would use these UIComponents to construct an application by nesting components within each other.

Controller

JSF comes with a simple controller—the FacesServlet. The FacesServlet acts as a gatekeeper, controlling navigation flow and dispatching requests to the appropriate JSF page.

What is the main feature of JSF ?

JSF offers a long list of features.

However, so as to not bore you by describing them all here We will just cover the two most important features: user interface components and events.

User Interface Components

UI components are the main feature of the JSF framework. JSF ships with 26 ready-to-use user interface components. Usually referred to as standard components, they provide basic user interface widgets for input, output, commands (buttons and links), labels, and layout, as well as simple controls to display tabular data.

For example, the following tag represents an input component:

<h:inputText value="#{order.amount}"/>

This is an input component that is bound (connected) to some Java object. You would place this tag on a JSF page instead of directly writing HTML code.The component behind the tag knows how to generate all the necessary and correct HTML, CSS, and JavaScript.

Component Rendering

The JSF framework allows the separation of a component from how it is presented (encoding) and how input is processed (decoding). The appearance of the component can be easily varied for the type of display device available (for example, a mobile phone). JSF provides out of the box, HTML 4.0 rendering kit.

Events

JSF takes you beyond the request/response paradigm and provides a powerful event-based model. The UI components that you use to build the user interface are sending events (when activated or clicked) to the server. Listeners then process the events.

For instance, in the #{simpleBean.save} expression defined in an action attribute, save is a method inside simpleBean bean. It is usually referred to as a JSF action and will be invoked when the button is clicked:

<h:commandButton value="Submit" action="#{simpleBean.save}"/>

Before we enter in a practical way in JSF 2, you must understand the six phases  show in the figure bellow which illustrate the life cycle of a JSF request and can give you lot of benefices in debugging :

lifecycle-conv-val-overview

The phases are :

  • Restore View
  • Apply Request Values
  • Process Validations
  • Update Model Values
  • Invoke Application
  • Render Response

For more details on these fundamental phases, I will recommend the nice article Request Processing Lifecycle phases in JSF available in the JavaBeat web site.

Ajax and JSF 2 specification

When JSF 1.x was developed, it didn’t have any Ajax features simply because Ajax didn’t exist as we know it to day.

Luckily in 2006 RichFaces came along and made it very easy to add Ajax functionality to existing or new JSF applications. For example, if you had a standard input text component like the following:

<<h:inputText value="#{order.amount}"/>

To send an Ajax request based on some event was very easy with RichFaces. All you had to do is add the <a4j:support> tag, specify the event to fire the Ajax request, and specify which components to rerender, as follows:

<h:inputText value="#{order.amount}">
<a4j:support event="onkeyup" reRender="id1"/>
</h:inputText/>
<h:outputText value="#{order.total}" id="id1"/>

When JSF EG (Expert Group) started working on JSF version 2, they introduced basic Ajax support into the specification. The Ajax behavior <f:ajax> in JSF 2 is closely based on the <a4j:support> tag.

Taking the above example, adding Ajax support in JSF 2 is done like this:

<h:inputText value="#{order.amount}">
<f:ajax event="keyup" render="id1"/>
</h:inputText/>
<h:outputText value="#{order.total}" id="id1"/>

This example looks very similar to the RichFaces 3 example.

The obvious changes are the new behavior (<f:ajax>), the event is specified without the on-part and instead of reRender, the render attribute is used. However, the core Ajax concepts are very similar. In addition to using <f:ajax> behavior, it’s also possible to send an Ajax request in a programmatic way, as follows:

<h:form id="form">
<h:commandButton id="button" value="Update"
onclick="jsf.ajax.request(this,event, {render:'form:out'}); 
return false;" />
<h:output Text value="#{timeBean.now}" id="out"/>
</h:form>

Even though basic, Ajax is now part of the JSF 2 standard.

An overview of RichFaces

If you are wondering why we need RichFaces if there is now Ajax functionality in JSF 2, it’s because the Ajax functionality in JSF 2 is very basic.

You only get <f:ajax> behavior. That’s not enough to build real rich enterprise Ajax applications. That’s exactly why you need RichFaces, a rich framework for JSF.

It consists of the following parts:

  • Rich and Ajax components divided into two tag libraries (a4j:, rich:)
  • Skins
  • Client-side and object validation extension for Bean Validation (JSR 303)
  • CDK (Component Development Kit)

RichFaces 4 is full compliant with JSF 2  and adds various rendering optimization attributes that we will cover in this section.

RichFaces’s Component Tag Libraries

RichFaces components are divided into two tag libraries: one tag library is called a4j:, and the other is called rich:.

The a4j: tag library provides page-level Ajax support and other utility tags. It basically provides foundation-like controls where you decide how to send a request, what to send to the server, and what to update.

The rich: tag library provides rich UI components. Rich components are anything beyond what the standard HTML tags provide; for example, a tab panel. There is no standard JSF nor HTML tag for a tab panel, so RichFaces provides one that makes it a rich component (beyond out-of-the-box HTML).

RichFaces Skins

RichFaces includes a number of predefined skins. These skins can be used in RichFaces web applications by specifying the skin name in the org.richfaces.skin context parameter in the web.xml settings file.

The predefined skins are as follows:

  • DEFAULT
  • plain, which contains no skin parameters and is intended for embedding RichFaces components into existing projects with their own styles.
  • emeraldTown
  • blueSky
  • wine
  • japanCherry
  • ruby
  • classic
  • deepMarine

Example (skin-chosser.xhtml)

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">

<ui:composition>
<rich:panel>
<a4j:repeat var="skin" value="#{skinBean.skins}" iterationStatusVar="iterStatus">
<h:link value="#{skin}" includeViewParams="true">
<f:param name="skin" value="#{skin}"/>
<f:attribute name="style" value="#{(skin==skinBean.skin) ? 'color:orange' : ''}"/>
</h:link>
<h:outputText value = " | " rendered="#{not iterStatus.last}" />
</a4j:repeat>
</rich:panel>
</ui:composition>

</html>

Here the result of the treeview component and classic style using the skins features:

RichFacesMenus

RichFaces Client-side Validation

JSF comes with a number of out-of-the-box validators and JSF 2 now also supports Bean Validation (JSR 303). RichFaces 4 takes validation a step further and adds client-side validation based on Bean validation. With this feature, basic client-side validation no longer requires creating and plugging custom JavaScript validators to components; it just synchronizes them for different layers at the framework level. We will see that in action in a future post .

RichFaces’ Component Development Kit

Another part of the framework is the Component Development Kit (CDK). The CDK includes various Maven archetypes, a code generation facility, descriptors and tests generation facility, and a templating facility that allows the creation of renderer classes using only page code.

Creating and starting a Jetty Project with Jetty WTP Plugin

Description

In this short post we will begin by creating a web project using a JEE Web Archetype.

Creating a Web project

Launch the Maven Archetypes Wizard :

Click on the Finish button.

We will add some specific plugins in the generated project:

Read More

Bonjour tout le monde !

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!