JBoss.orgCommunity Documentation
Copyright © 2008, 2009 Red Hat
RichFaces is an open source framework that adds Ajax capability into existing JSF applications without resorting to JavaScript.
RichFaces leverages JavaServer Faces framework including lifecycle, validation, conversion facilities and management of static and dynamic resources. RichFaces components with built-in Ajax support and a highly customizable look-and-feel can be easily incorporated into JSF applications.
RichFaces allows to:
Intensify the whole set of JSF benefits while working with Ajax. RichFaces is fully integrated into the JSF lifecycle. While other frameworks only give you access to the managed bean facility, RichFaces advantages the action and value change listeners, as well as invokes server-side validators and converters during the Ajax request-response cycle.
Add Ajax capability to the existing JSF applications. Framework provides two components libraries (Core Ajax and UI). The Core library sets Ajax functionality into existing pages, so there is no need to write any JavaScript code or to replace existing components with new Ajax ones. RichFaces enables page-wide Ajax support instead of the traditional component-wide support and it gives the opportunity to define the event on the page. An event invokes an Ajax request and areas of the page which become synchronized with the JSF Component Tree after changing the data on the server by Ajax request in accordance with events fired on the client.
Create quickly complex View basing on out of the box components. RichFaces UI library contains components for adding rich user interface features to JSF applications. It extends the RichFaces framework to include a large (and growing) set of powerful rich Ajax-enabled components that come with extensive skins support. In addition, RichFaces components are designed to be used seamlessly with other 3d-party component libraries on the same page, so you have more options for developing your applications.
Write your own custom rich components with built-in Ajax support. We're always working on improvement of Component Development Kit (CDK) that was used for RichFaces UI library creation. The CDK includes a code-generation facility and a templating facility using a JSP-like syntax. These capabilities help to avoid a routine process of a component creation. The component factory works like a well-oiled machine allowing the creation of first-class rich components with built-in Ajax functionality even more easily than the creation of simpler components by means of the traditional coding approach.
Package resources with application Java classes. In addition to its core, Ajax functionality of RichFaces provides an advanced support for the different resources management: pictures, JavaScript code, and CSS stylesheets. The resource framework makes possible to pack easily these resources into Jar files along with the code of your custom components.
Easily generate binary resources on-the-fly. Resource framework can generate images, sounds, Excel spreadsheets etc.. on-the-fly so that it becomes for example possible to create images using the familiar approach of the "Java Graphics2D" library.
Create a modern rich user interface look-and-feel with skins-based technology. RichFaces provides a skinnability feature that allows easily define and manage different color schemes and other parameters of the UI with the help of named skin parameters. Hence, it is possible to access the skin parameters from JSP code and the Java code (e.g. to adjust generated on-the-fly images based on the text parts of the UI). RichFaces comes with a number of predefined skins to get you started, but you can also easily create your own custom skins.
Test and create the components, actions, listeners, and pages at the same time. An automated testing facility is in our roadmap for the near future. This facility will generate test cases for your component as soon as you develop it. The testing framework will not just test the components, but also any other server-side or client-side functionality including JavaScript code. What is more, it will do all of this without deploying the test application into the Servlet container.
RichFaces UI components come ready to use out-of-the-box, so developers save their time and immediately gain the advantage of the mentioned above features in Web applications creation. As a result, usage experience can be faster and easily obtained.
RichFaces was developed with an open architecture to be compatible with the widest possible variety of environments.
This is what you need to start working with RichFaces 3.3.3:
Java
JavaServer Faces
Java application server or servlet container
Browser (on client side)
RichFaces framework
Sun JSF-RI - 1.2_x (1.2_14 recommended), 2.x
MyFaces 1.2.x (1.2.5 recommended), 2.x
Facelets 1.1.x
Seam 2.x
Apache Tomcat 5.5 - 6.0
BEA WebLogic 9.1 - 10.0
Resin 3.1.x
Jetty 6.1.x
Sun Application Server 9 (J5EE)
Glassfish V2, V3
JBoss 4.2.x - 5
Websphere 7.0. and higher
Geronimo 2.0 and higher
Linux environments
Firefox 3.0 and higher
Opera 9.5 and higher
Windows environments
Firefox 3.0 and higher
Google Chrome
Internet Explorer 6.0 and higher
Opera 9.5 and higher
Safari 3.0 and higher
Mac OS environments
Safari 3.0 and higher
Firefox 3.5 and higher
This list is composed basing on reports received from our users. We assume the list can be incomplete and absence of your environment in the list doesn't mean incompatibility.
We appreciate your feedback on platforms and browsers that aren't in the list but are compatible with RichFaces. It helps us to keep the list up-to-date.
This chapter describes all necessary actions and configurations that should be done for plugging the RichFaces components into a JSF appplication. The description relies on a simple JSF with RichFaces application creation process from downloading the libraries to running the application in a browser. The process of application creation described here is common and does not depend on used IDE.
The latest release of RichFaces components is available for download at
JBoss RichFaces Downloads area at JBoss community.
Binary files (uploaded there in *.bin.zip
or
*.bin.tar.gz
archives) contains compiled,
ready-to-use version of RichFaces with set of basic skins.
To start with RichFaces in computer file system create new folder with name "RichFaces", download and unzip the archive with binaries there.
For those who want to download and compile the RichFaces by themselfs there is an article at JBoss community that describes the RichFaces repository's structure overview and some aspects of working with it.
"RichFaces Greeter"—the simple application—is hello-world like application but with one difference: the world of RichFaces will say "Hello!" to user first.
Create standard JSF 1.2 project with all necessary libraries; name the project "Greeter" and follow the decription.
Go to the folder with unzipped earlier RichFaces binary files
and open lib
folder. This folder contains three
*.jar
files with API, UI and
implementation libraries. Copy that "jars" from
lib
folder to WEB-INF/lib
folder
of "Greeter" JSF application.
A JSF application with RichFaces assumes that the following JARs are available in the project: commons-beanutils-1.7.0.jar, commons-collections-3.2.jar, commons-digester-1.8.jar, commons-logging-1.0.4.jar, jhighlight-1.0.jar.
After RichFaces libraries where added into the project it is
necessary to register them in project web.xml
file. Add following lines in web.xml
:
...
<!-- Plugging the "Blue Sky" skin into the project -->
<context-param>
<param-name>org.richfaces.SKIN</param-name>
<param-value>blueSky</param-value>
</context-param>
<!-- Making the RichFaces skin spread to standard HTML controls -->
<context-param>
<param-name>org.richfaces.CONTROL_SKINNING</param-name>
<param-value>enable</param-value>
</context-param>
<!-- Defining and mapping the RichFaces filter -->
<filter>
<display-name>RichFaces Filter</display-name>
<filter-name>richfaces</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>richfaces</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
...
For more information on how to work with RichFaces skins read "Skinnabilty" chapter.
Finally the web.xml
should look like this:
<?xml version="1.0"?>
<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>Greeter</display-name>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.SKIN</param-name>
<param-value>blueSky</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.CONTROL_SKINNING</param-name>
<param-value>enable</param-value>
</context-param>
<filter>
<display-name>RichFaces Filter</display-name>
<filter-name>richfaces</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>richfaces</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<!-- Faces Servlet -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Faces Servlet Mapping -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
The "RichFaces Greeter" application needs a managed bean. In
project JavaSource
folder create a new managed
bean with name user
in demo
package and paste there the following simple code:
package demo;
public class user {
private String name="";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
With the next step the user
bean should be
registered in faces-config.xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="1.2"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude"
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>
<description>UsernName Bean</description>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>demo.user</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>name</property-name>
<property-class>java.lang.String</property-class>
<value/>
</managed-property>
</managed-bean>
</faces-config>
The "RichFaces Greeter" application has only one JSP page.
Create index.jsp
page in root of WEB
CONTENT
folder and add there following
code:
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<!-- RichFaces tag library declaration -->
<%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>
<html>
<head>
<title>RichFaces Greeter</title>
</head>
<body>
<f:view>
<a4j:form>
<rich:panel header="RichFaces Greeter" style="width: 315px">
<h:outputText value="Your name: " />
<h:inputText value="#{user.name}" >
<f:validateLength minimum="1" maximum="30" />
</h:inputText>
<a4j:commandButton value="Get greeting" reRender="greeting" />
<h:panelGroup id="greeting" >
<h:outputText value="Hello, " rendered="#{not empty user.name}" />
<h:outputText value="#{user.name}" />
<h:outputText value="!" rendered="#{not empty user.name}" />
</h:panelGroup>
</rich:panel>
</a4j:form>
</f:view>
</body>
</html>
The application uses three RichFaces components: <rich:panel> is used as visual container for information; <a4j:commandButton> with built-in Ajax support allows rendering a greeting dynamically after a response comes back and <a4j:form> helps the button to perform the action.
Note, that the RichFaces tag library should be declared on each JSP page.
For Facelets you should add the following lines for tag library declaration:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
...
</ui:composition>
That's it. Run the application on server. Point your browser to index.jsp
page in browser:
http://localhost:8080/Greeter/index.jsf
In this section we will tell how you can create a simple JSF application with RichFaces using Maven.
In the first place you need to make sure that Maven is installed on you local machine. We will run the JSF application on Tomcat 6.0 server, so please download and install it if you haven't done already so.
Now we can move on to creating the application. To create the project structure and fill it with minimal content we will use the "maven-archetype-jsfwebapp" Maven archetype which is a part of RichFaces CDK.
The "maven-archetype-jsfwebapp" archetype and the project itself require extra repositories to be provided, namely "http://snapshots.jboss.org/maven2/" and "http://repository.jboss.com/maven2/".
The easiest way to make the repositories visible for Maven is to create a profile in "maven_installation_folder/conf/settings.xml" in <profiles>
element. This is the content of the profile:
<profile>
<id>jsf-app-profile</id>
<repositories>
<repository>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
<id>snapshots.jboss.org</id>
<name>Snapshot Jboss Repository for Maven</name>
<url>http://snapshots.jboss.org/maven2/</url>
<layout>default</layout>
</repository>
<repository>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
<id>repository.jboss.com</id>
<name>Jboss Repository for Maven</name>
<url>http://repository.jboss.com/maven2/</url>
<layout>default</layout>
</repository>
</repositories>
</profile>
When the profile is added you need to activate it in the <activeProfiles>
element. It can be done like this:
...
<activeProfiles>
<activeProfile>jsf-app-profile</activeProfile>
</activeProfiles>
...
Now you have everything to create the project using the "maven-archetype-jsfwebapp" archetype. Create a folder that will house your project and run the this command in it:
...
mvn archetype:generate -DarchetypeGroupId=org.richfaces.cdk -DarchetypeArtifactId=maven-archetype-jsfwebapp -DarchetypeVersion=3.3.3-SNAPSHOT -DgroupId=org.docs.richfaces -DartifactId=jsf-app
...
You can adjust some parameters of the command.
Table 3.1. Title of the table
Parameter | Description |
---|---|
-DgroupId | Defines the package for the Managed beans |
-DartifactId | Defines the name of the project |
This command generates a JSF project that has the following structure:
jsf-app
|-- pom.xml
`-- src
|-- main
| |-- java
| | `-- org
| | `-- docs
| | `-- richfaces
| | `-- Bean.java
| |-- resources
| `-- webapp
| |-- WEB-INF
| | |-- faces-config.xml
| | `-- web.xml
| |-- index.jsp
| `-- pages
| |-- index.jsp
| `-- index.xhtml
`-- test
`-- java
`-- org
`-- docs
`-- richfaces
`-- BeanTest.java
Now go to "jsf-app" folder, it contains a project descriptor(pom.xml). Open the project descriptor to edit and add dependencies to the <dependencies>
element. Your <dependencies>
element content should be the following:
...
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>1.2_12</version>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>1.2_12</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>el-impl</groupId>
<artifactId>el-impl</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
<!-- RichFaces libraries -->
<dependency>
<groupId>org.richfaces.framework</groupId>
<artifactId>richfaces-api</artifactId>
<version>3.3.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.richfaces.framework</groupId>
<artifactId>richfaces-impl</artifactId>
<version>3.3.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.richfaces.ui</groupId>
<artifactId>richfaces-ui</artifactId>
<version>3.3.3-SNAPSHOT</version>
</dependency>
</dependencies>
...
The last three dependences add RichFaces libraries to the project. You can now build the project with the mvn install
command.
When you see the "BUILD SUCCESSFUL" message, the project is assembled and can be imported to a IDE and run on the server.
The project can be built for Eclipse IDE with mvn eclipse:eclipse -Dwtpversion=2.0
command.
Then you can import the project into Eclipse. After importing to Eclipse open the "jsf-app/src/main/webapp/WEB-INF/web.xml" to configure it according to the listing in the Registering RichFaces in web.xml section of the guide.
The project is configured and now you can start using RichFaces. Open "jsf-app/src/main/webapp/pages/index.jsp" file and add the tag library declaration.
...
<%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>
...
Add some RichFaces component to the "index.jsp" page, for instance <rich:calendar>. Your "index.jsp" page will look like this:
...
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>
<html>
<head>
<title>JSF Application with RichFaces built by Maven</title>
</head>
<body>
<f:view>
<rich:calendar />
</f:view>
</body>
</html>
...
Now run the application on Tomcat server and open it in your favourite browser by pointing it to "http://localhost:8080/jsf-app/" .
The Photo Album Application is designed and developed with RichFaces.
Maven Resource Dependency Plugin Reference article discusses plugin configuration and usage.
See also the "How to start RichFaces application with NetBeans IDE" article in the RichFaces Cookbook.
JBoss Developer Studio comes with a tight integration with RichFaces component framework. Following links might be useful for those who already use this IDE and RichFaces for developing applications and those who wish to improve their development process:
"Rich Components" chapter in "Getting Started with JBoss Developer Studio Guide" describes how to add RichFaces components into a CRUD application;
"JBoss Tools Palette" chapter in "Visual Web Tools Reference Guide" describes advantages that gives Tools Pallete (comes together with JBDS) for quick and easy pages creation processs including RichFaces applications;
"RichFaces Toolkit for developing Web application" video tutorial demonstrates some aspects of interaction with JBoss Developer Studio while working with RichFaces.
"How to Configure Maven for RichFaces" article shortly discusses Maven configuration for RichFaces.
" RichFaces Release Procedure " article describes how RichFaces release builds are made.
Read "RichFaces installing and configuration" article to find out how to integrate RichFaces and Trinidad and possible problems that may occur while launching the RichFaces sample on the JBoss server.
Read also the quick overview to "Practical RichFaces " book by Max Katz at his blog.
RichFaces comes with support for all tags (components) included in the JavaServer Faces specification. To add RichFaces capabilities to the existing JSF project you should just put the RichFaces libraries into the lib folder of the project and add filter mapping. The behavior of the existing project doesn't change just because of RichFaces.
RichFaces doesn't require any parameters to be defined in your web.xml. But the RichFaces parameters listed below may help with development and may increase the flexibility of RichFaces usage.
Table 4.1. Initialization Parameters
Name | Default | Description |
---|---|---|
org.richfaces.SKIN | DEFAULT | Is a name of a skin used in an
application. It can be a
literal string with a skin
name, or the
EL
expression
(#{...} )
pointed to a
String
property (skin
name) or a property of a
org.richfaces.framework.skin
type. Skin in last case, this
instance is used as a current
skin |
org.richfaces.LoadScriptStrategy | DEFAULT | Defines how the RichFaces script files are loaded to application. Possible values are: ALL, DEFAULT, NONE. For more information see "Scripts and Styles Load Strategy". |
org.richfaces.LoadStyleStrategy | DEFAULT | Defines how the RichFaces style files are loaded to application. Possible values are: ALL, DEFAULT, NONE. For more information see "Scripts and Styles Load Strategy". |
org.ajax4jsf.LOGFILE | none | Is an URL to an application or a container log file (if possible). If this parameter is set, content from the given URL is shown on a Debug error page in the iframe window |
org.ajax4jsf.VIEW_HANDLERS | none | Is a comma-separated list of custom ViewHandler instances for inserting in chain. Handlers are inserted BEFORE RichFaces viewhandlers in the given order. For example, in facelets application this parameter must contain com.sun.facelets.FaceletViewHandler, instead of declaration in faces-config.xml |
org.ajax4jsf.CONTROL_COMPONENTS | none | Is a comma-separated list of names for a component as a special control case, such as messages bundle loader, alias bean components, etc. Is a type of component got by a reflection from the static field COMPONENT_TYPE . For components with such types encode methods always are called in rendering Ajax responses, even if a component isn't in an updated part |
org.ajax4jsf.ENCRYPT_RESOURCE_DATA | false | For generated resources, such as encrypt generation data, it's encoded in the resource URL. For example, URL for an image generated from the mediaOutput component contains a name of a generation method, since for a hacker attack, it is possible to create a request for any JSF baked beans or other attributes. To prevent such attacks, set this parameter to "true" in critical applications (works with JRE > 1.4 ) |
org.ajax4jsf.ENCRYPT_PASSWORD | random | Is a password for encryption of resources data. If isn't set, a random password is used |
org.ajax4jsf.COMPRESS_SCRIPT | true | It doesn't allow framework to reformat JavaScript files (makes it impossible to debug) |
org.ajax4jsf.RESOURCE_URI_PREFIX | a4j | Defines prefix which is added to all URIs of generated resources. This prefix designed to handle RichFaces generated resources requests |
org.ajax4jsf.GLOBAL_RESOURCE_URI_PREFIX | a4j/g | Defines prefix which is added to URIs of global resources. This prefix designed to handle RichFaces generated resources requests |
org.ajax4jsf.SESSION_RESOURCE_URI_PREFIX | a4j/s | Defines prefix which is used for session tracking for generated resources. This prefix designed to handle RichFaces generated resources requests |
org.ajax4jsf.DEFAULT_EXPIRE | 86400 | Defines in seconds how long streamed back to browser resources can be cached |
org.ajax4jsf.SERIALIZE_SERVER_STATE | false | If enabled the component state
(not the tree) will be
serialized before being stored
in the session. This may be
desirable for applications
that may have issues with view
state being sensitive to model
changes. Instead of this
parameter can use
com.sun.faces.serializeServerState
and
org.apache.myfaces.SERIALIZE_STATE_IN_SESSION
parameters for
corresponding environments.
|
org.richfaces.SKIN
is used in the same way as
org.ajax4jsf.SKIN
Table 4.2. org.ajax4jsf.Filter Initialization Parameters
Name | Default | Description |
---|---|---|
log4j-init-file | - | Is a path (relative to web application context) to the log4j.xml configuration file, it can be used to setup per-application custom logging |
enable-cache | true | Enable caching of framework-generated resources (JavaScript, CSS, images, etc.). For debug purposes development custom JavaScript or Style prevents to use old cached data in a browser |
forcenotrf | true | Force parsing by a filter HTML syntax checker on any JSF page. If "false", only Ajax responses are parsed to syntax check and conversion to well-formed XML. Setting to "false" improves performance, but can provide visual effects on Ajax updates |
RichFaces works with implementation of JSF (JSF 1.2_12) and with most JSF component libraries without any additional settings. For more information look at:
java.sun.com |
Additional information how to get ViewExpiredExceptions
when using RichFaces with JSF
1.2_12 you can find in RichFaces Cookbook article.
RichFaces works with Apache MyFaces 1.2.5 version including specific libraries like TOMAHAWK Sandbox and Trinidad (the previous ADF Faces). However, there are some considerations to take into account for configuring applications to work with MyFaces and RichFaces.
There are some problems with different filters defined in the web.xml file clashing. To avoid these problems, the RichFaces filter must be the first one among other filters in the web.xml configuration file.
For more information look at: http://myfaces.apache.org
There's one more problem while using MyFaces + Seam . If you use this combination you should use <a4j:page> inside <f:view> (right after it in your code) wrapping another content inside your pages because of some problems in realization of <f:view> in myFaces.
The problem is to be overcome in the nearest future.
A high-level support for Facelets is one of our main support features. When working with RichFaces, there is no difference what release of Facelets is used.
You should also take into account that some JSF frameworks such as
Facelets use their own
ViewHandler
and need to have it first in the
chain of ViewHandlers and the RichFaces AjaxViewHandler is not an
exception. At first RichFaces installs its ViewHandler in any case, so
in case of two frameworks, for example RichFaces + Facelets, no
changes in settings are required. Although, when more then one
framework (except RichFaces) is used, it's possible to use
the VIEW_HANDLERS
parameter defining these frameworks
view handlers according to its usage order in it. For example, the
declaration:
Example:
...
<context-param>
<param-name>org.ajax4jsf.VIEW_HANDLERS</param-name>
<param-value>com.sun.facelets.FaceletViewHandler</param-value>
</context-param>
...
says that Facelets will officially be the first,
however AjaxViewHandler
will be a little ahead
temporarily to do some small, but very important job.
In this case you don't have to define
FaceletViewHandler
in the
WEB-INF/faces-config.xml.
RichFaces now works out-of-the-box with JBoss Seam and Facelets running inside JBoss AS 4.0.4 and higher. There is no more shared JAR files needed. You just have to package the RichFaces library with your application.
Your web.xml for Seam 1.2 must be like this:
<?xml version="1.0" ?>
<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">
<!-- richfaces -->
<filter>
<display-name>RichFaces Filter</display-name>
<filter-name>richfaces</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>richfaces</filter-name>
<url-pattern>*.seam</url-pattern>
</filter-mapping>
<!-- Seam -->
<listener>
<listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>
<servlet>
<servlet-name>Seam Resource Servlet</servlet-name>
<servlet-class>org.jboss.seam.servlet.ResourceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Seam Resource Servlet</servlet-name>
<url-pattern>/seam/resource/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>Seam Filter</filter-name>
<filter-class>org.jboss.seam.web.SeamFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Seam Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- MyFaces -->
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
<!-- JSF -->
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</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>*.seam</url-pattern>
</servlet-mapping>
</web-app>
Seam 2 supports RichFaces Filter. Thus your web.xml for Seam 2 must be like this:
<?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>org.ajax4jsf.VIEW_HANDLERS</param-name>
<param-value>com.sun.facelets.FaceletViewHandler</param-value>
</context-param>
<!-- Seam -->
<listener>
<listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>
<servlet>
<servlet-name>Seam Resource Servlet</servlet-name>
<servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Seam Resource Servlet</servlet-name>
<url-pattern>/seam/resource/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>Seam Filter</filter-name>
<filter-class>org.jboss.seam.servlet.SeamFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Seam Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- JSF -->
<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>
<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>*.seam</url-pattern>
</servlet-mapping>
</web-app>
Only one issue still persists while using Seam with MyFaces. Look at myFaces part of this section.
Detailed information on how to integrate Richfaces and Trinidad and how to hide ".seam" postfix in the URL you can find in the RichFaces Cookbook article
JBoss Portlets have support since version Ajax4jsf 1.1.1. This support is improved from RichFaces 3.2.1. Provide your feedback on compatible with RichFaces if you face some problems.
The load-on-startup for the Faces Servlet had to be set to 0 in web.xml.
Example:
...
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
...
This is because, EAServer calls servlet init()
before the
ServletContextInitializer
. Not an EAServer bug,
this is in Servlet 2.3 spec.
In order to deploy your project with RichFaces components to an Oracle AS you just have to prevent the application's class loader from importing the Oracle XML parser. Use the following notation in orion-application.xml :
...
<imported-shared-libraries>
<remove-inherited name="oracle.xml"/>
<remove-inherited name="oracle.xml.security"/>
</imported-shared-libraries>
...
The framework is implemented as a component library which adds Ajax capability into existing pages, so you don't need to write any JavaScript code or to replace existing components with new Ajax widgets. RichFaces enables page-wide Ajax support instead of the traditional component-wide support. Hence, you can define the event on the page that invokes an Ajax request and the areas of the page that should be synchronized with the JSF Component Tree after the Ajax request changes the data on the server according to the events fired on the client.
Next Figure shows how it works:
RichFaces allows to define (by means of JSF tags) different parts of a JSF page you wish to update with an Ajax request and provide a few options to send Ajax requests to the server. Also JSF page doesn't change from a "regular" JSF page and you don't need to write any JavaScript or XMLHTTPRequest objects by hands, everything is done automatically.
Next figure lists several important elements of the RichFaces framework
To get all benefits of RichFaces , you should register a Filter in web.xml file of your application. The Filter recognizes multiple request types. Necessary information about Filter configuration can be found in the "Filter configuration" section. The sequence diagram on Figure 3 shows the difference in processing of a "regular" JSF request and an Ajax request.
In the first case the whole JSF tree will be encoded, in the second one option it depends on the "size" of the Ajax region. As you can see, in the second case the filter parses the content of an Ajax response before sending it to the client side.
Have a look at the next picture to understand these two ways:
In both cases, the information about required static or dynamic resources that your application requests is registered in the ResourseBuilder class.
When a request for a resource comes (Figure 4), the RichFaces filter checks the Resource Cache for this resource and if it is there, the resource is sent to the client. Otherwise, the filter searches for the resource among those that are registered by the ResourceBuilder. If the resource is registered, the RichFaces filter will send a request to the ResourceBuilder to create (deliver) the resource.
Next Figure shows the ways of resource request processing.
There are Ajax Action Components: <a4j:commandButton> , <a4j:commandLink> , <a4j:poll> and <a4j:support> and etc. You can use them to send Ajax requests from the client side.
AjaxContainer is an interface that describes an area on your JSF page that should
be decoded during an Ajax request. AjaxViewRoot
and
AjaxRegion
are implementations of this interface.
RichFaces JavaScript Engine runs on the client-side. It knows how to update different areas on your JSF page based on the information from the Ajax response. Do not use this JavaScript code directly, as it is available automatically.
RichFaces framework enhances the JSF framework with partial rendering of the components with Ajax capability enabled. This means that only the part of the page that should be affected by some change is updated. Ajax capability of the components can be enabled by the "mode", "switchType" etc. set to "ajax". This approach prevents multiple page refreshes, which minimized server load.
A good example that can illustrate this feature is rendering of the tabs of the <rich:tabPanel>. By default the component updates the whole page to display the content of the tab which is clicked on, to enable partial rendering the "switchType" attribute set to "ajax" should be used.
...
<rich:tabPanel switchType="ajax">
<rich:tab label="Tab 1">
Content of Tab 1
</rich:tab>
<rich:tab label="Tab 2">
Content of Tab 2
</rich:tab>
<rich:tab label="Tab 3">
Content of Tab 3
</rich:tab>
</rich:tabPanel>
...
The RichFaces comes with a number of integral parts (framework, libraries):
For more information about framework and libraries loading see the following section in the FAQ.
In order to prevent JavaScript versions conflict you should use only one version of the framework or library. You could find more information about libraries exclusion in the FAQ.
In order to create RichFaces applications properly, keep the following points in mind:
Any Ajax framework should not append or delete, but only replace elements on the page. For successful updates, an element with the same ID as in the response must exist on the page. If you'd like to append any code to a page, put in a placeholder for it (any empty element). For the same reason, it's recommended to place messages in the "AjaxOutput" component (as no messages is also a message).
Don't use <f:verbatim> for self-rendered containers, since this component is transient and not saved in the tree.
Ajax requests are made by XMLHTTPRequest functions in XML format, but this XML bypasses most validations and the corrections that might be made in a browser. Thus, create only a strict standards-compliant code for HTML and XHTML, without skipping any required elements or attributes. Any necessary XML corrections are automatically made by the XML filter on the server, but lot's of unexpected effects can be produced by an incorrect HTML code.
The RichFaces ViewHandler puts itself in front of the Facelets ViewHandlers chain.
RichFaces components uses their own renderers. On the Render Response Phase RichFaces framework makes a traversal of the component tree, calls its own renderer and put the result into the Faces Response.
Ajax attributes are common for Ajax components such as <a4j:support> , <a4j:commandButton> , <a4j:jsFunction> , <a4j:poll> , <a4j:push> and so on. Also, most RichFaces components with built-in Ajax support have these attributes for a similar purpose. Ajax components attributes help RichFaces to expose its features. Most of the attributes have default values. Thus, you can start working with RichFaces without knowing the usage of these attribute. However, their usage allows to tune the required Ajax behavior very smoothly.
"reRender" is a key attribute. The attribute allows to point to area(s) on a page that should be updated as a response on Ajax interaction. The value of the "reRender" attribute is an id of the JSF component or an id list.
A simple example is placed below:
...
<a4j:commandButton value="update" reRender="infoBlock"/>
...
<h:panelGrid id="infoBlock">
...
</h:panelGrid>
...
The value of "reRender" attribute of the <a4j:commandButton> tag defines which part(s) of your page is (are) to be updated. In this case, the only part of the page to update is the <h:panelGrid> tag because its ID value matches to the value of "reRender" attribute. As you see, it's not difficult to update multiple elements on the page, only list their IDs as the value of "reRender" .
"reRender" uses UIComponent.findComponent() algorithm (with some additional exceptions) to find the component in the component tree. As can you see, the algorithm presumes several steps. Each other step is used if the previous step is not successful. Therefore, you can define how fast the component is found mentioning it more precisely. The following example shows the difference in approaches (both buttons will work successfully):
...
<h:form id="form1">
...
<a4j: commandButton value="Usual Way" reRender="infoBlock, infoBlock2" />
<a4j:commandButton value="Shortcut" reRender=":infoBlockl,:sv:infoBlock2" />
...
</h:form>
<h:panelGrid id="infoBlock">
...
</h:panelGrid>
...
<f:subview id="sv">
<h:panelGrid id="infoBlock2">
...
</h:panelGrid>
...
</f:subview>
...
It's also possible to use JSF EL expression as a value of the reRender attribute. It might be a property of types Set, Collection, Array or simple String. The EL for reRender is resolved right before the Render Response phase. Hence, you can calculate what should be re-rendered on any previous phase during the Ajax request processing.
Most common problem with using reRender is pointing it to the component that has
a
"rendered"
attribute. Note, that JSF does not mark the place in the browser DOM
where the outcome of the component should be placed in case the
"rendered"
condition returns false. Therefore, after the component becomes rendered
during the Ajax request, RichFaces delivers the rendered code to the client, but
does not update a page, because the place for update is unknown. You need to point
to one of the parent components that has no
"rendered"
attribute. As an alternative, you can wrap the component with
<a4j:outputPanel>
layout="none"
.
"ajaxRendered" attribute of the <a4j:outputPanel> set to "true" allows to define the area of the page that will be re-rendered even if it is not pointed in the reRender attribute explicitly. It might be useful if you have an area on a page that should be updated as a response on any Ajax request. For example, the following code allows to output error messages regardless of what Ajax request causes the Validation phase failed.
...
<a4j:outputPanel ajaxRendered="true">
<h:messages />
</a4j:outputPanel>
...
"limitToList"
attribute allows to dismiss the behavior of the
<a4j:outputPanel>
"ajaxRendered"
attribute. limitToList = "true"
means to update
only the area(s) that mentioned in the
"reRender"
attribute explicitly. All output panels with
ajaxRendered="true"
is ignored. An example is placed
below:
...
<h:form>
<h:inputText value="#{person.name}">
<a4j:support event="onkeyup" reRender="test" limitToList="true"/>
</h:inputText>
<h:outputText value="#{person.name}" id="test"/>
</form>
...
"eventsQueue" attribute defines the name of the queue that will be used to order upcoming Ajax requests. By default, RichFaces does not queue Ajax requests. If events are produced simultaneously, they will come to the server simultaneously. JSF implementations (especially, the very first ones) does not guaranty that the request that comes first will be served or passed into the JSF lifecycle first. The order how the server-side data will be modified in case of simultaneous request might be unpredictable. Usage of eventsQueue attribute allows to avoid possible mess. Define the queue name explicitly, if you expect intensive Ajax traffic in your application.
The next request posted in the same queue will wait until the previos one is not processed and Ajax Response is returned back if the "eventsQueue" attribute is defined. In addition, RichFaces starts to remove from the queue "similar" requests. "Similar'"requests are the requests produced by the same event. For example, according to the following code, only the newest request will be sent to the server if you type very fast and has typed the several characters already before the previous Ajax Response is back.
...
<h:inputText value="#{userBean.name}">
<a4j:support event="onkeyup" eventsQueue="foo" reRender="bar" />
</h:inputText>
...
"requestDelay" attribute defines the time (in ms) that the request will be wait in the queue before it is ready to send. When the delay time is over, the request will be sent to the server or removed if the newest "similar" request is in a queue already .
"ignoreDupResponses"
attribute orders to ignore the Ajax Response produced by the request if
the newest "similar" request is in a queue already.
ignoreDupResponses"="true"
does not cancel the
request while it is processed on the server, but just allows to avoid unnecessary
updates on the client side if the response loses the actuality.
Defining the "eventsQueue" along with "requestDelay" allows to protect against unnecessary traffic flood and synchronizes Ajax requests order. If you have several sources of Ajax requests, you can define the same queue name there. This might be very helpful if you have Ajax components that invoke request asynchronously from the ones produced by events from users. For example, <a4j:poll> or <a4j:push> . In case the requests from such components modify the same data, the synchronization might be very helpful.
More information can be found on the RichFaces Users Forum .
"timeout" attribute is used for setting response waiting time on a particular request. If a response is not received during this time, the request is aborted.
Starting from 3.3.0 version RichFaces has an improved queue.
There are some reasons why the queue has been improved. In previous versions the queue had quite simple implementation: it sent to the server only the last Ajax request out of all requests coming in the queue during request delay.
The improved queue allows to
Eliminate the possibility of collisions when several JSF requests pass the JSF lifecycle at the same time. The queue prevents sending such requests. Only one request is processed. The rest ones are waiting.
Reduce the traffic between browser and the server. The "similar" requests came within request delay are absorbed. Only the last one is actually sent. Reducing the number of request reduces the server load.
There are 4 types of the queue:
Global default queue, defined in the web.xml file
View scoped default queue
View scoped named queue
Form-based default queue
In this section we will take a closer look at the listed above types of the queue and see in more detail how they differ. Usage details are covered in the <a4j:queue> chapter.
Design details
Only one global queue will ever exist on a view
If you define more than one with this name while attempting to set its attributes a warning will appear in server console during rendering. All the same named queues after the first instance are ignored.
The queue class name is "org.richfaces.queue.global"
Global default queue has application scope and is defined in the web.xml
It can be done as follows:
...
<context-param>
<param-name>org.richfaces.queue.global.enabled</param-name>
<param-value>true</param-value>
</context-param>
...
The global default queue is disabled by default, because artificial serializing of all Ajax requests on a page can significantly affect expected behavior. The global default queue causes all Asynchronous JavaScript And XML requests becoming synchronous via the single global queue. If the global queue is turned on it can change the behavior on all views of the application without any visible or obvious setting.
Design details
Only one default queue is ever active at one time for a given view or form.
If ever more are detected a warning will appears in server console during rendering. All the same named queues after the first instance are ignored.
View scoped default queue is also created for components which have the following Ajax attributes: (in this case queue has a component scope)
"requestDelay"
"ignoreDupResponce"
View scoped default queue is created automatically if the "eventsQueue" attribute is defined with some name in a component but not found in the view. It has a scope the same as defined in corresponding context param.
The view scoped default, named and formed-based types of queue utilize the <a4j:queue> tag to override the settings of the global queue defined in the web.xml file.
You can also programmatically enable/disable the global queue on a single view using the following:
...
<a4j:queue name="org.richfaces.queue.global" disabled="true"... />
...
Hence, to enable the queue for a single view page you need to define the "disable" attribute with "false".
Now, you can override the default settings using the attributes of the <a4j:queue> component. The full list of attributes is given in the "6.20. <a4j:queue>" chapter of the guide.
Example:
...
<a4j:queue name="org.richfaces.queue.global" requestDelay="1000" />
...
View scoped queue can be also added by just definition of the queue without name specified. In this case it should be placed anywhere outside the forms in order not to be recognized as a form-based queue.
...
<a4j:queue ... />
...
Design details
Named queues must have a unique name, if a second queue with the same name is defined all the same named queues after the first instance are ignored.
Form elements are used as naming container for the queue i.e. custom queue defined within the form cannot be used by the components outside this concrete form.
You can reference a named queue from any Ajax4JSF or RichFaces component that supports the "eventsQueue" attribute. Below there is an example of how the components can reference a named queue.
Example:
...
<a4j:queue name="sampleQueue"/>
<h:inputText value="#{bean.inputValue}" >
<a4j:support id="inputSupport" event="onkeyup" eventsQueue="sampleQueue"/>
</h:inputText>
<rich:comboBox value="#{bean.state}" suggestionValues="#{bean.suggestions}" eventsQueue="sampleQueue" />
...
In this example, two components(<a4j:queue>, <rich:comboBox>,) reference the named ( "sampleQueue") queue via the "eventsQueue" attribute.
Design details
Only one enabled form based default queue can be active at a time.
A warning appears in server console during rendering if more than one enabled form based queue exists. All queues with the same name after the first instance should be ignored.
Users can define more than one form queue, however all but one must be disabled.
Queues are often used within forms, but defining the "eventsQueue" attribute on every component within a form can be tedious work. To avoid that you can create a default queue for a form (overriding the global default queue ).
You can use either a JSF <h:form> or an Ajax4JSF <a4j:form>.
Example:
...
<h:form ... >
<a4j:queue ... /><!-- note no name specified -->
...
</h:form>
...
Though, using an Ajax4JSF <a4j:form> you can refrence a named queue via the "eventsQueue".
Example:
...
<a4j:form eventsQueue="fooQueue" ...>
...
</a4j:form>
...
However the implementation of the queue allows you to reference a named queue from the form with a form-based queue.
Example:
...
<a4j:queue name="sampleQueue" ... /> <!-- named queue -->
...
<h:form ... >
<a4j:queue ... /><!-- form-based queue-->
<a4j:commandButton ... /> <!-- uses the form-based queue -->
<a4j:commandButton eventsQueue="sampleQueue" /> <!-- uses named queue -->
</h:form>
...
This section will cover some queue's functionality aspects.
By default all the events raised by the same component are similar to the queue (according to client Id of event source). This means that if new requests come from the same component they are combined with the previous ones. For example: if we use a4j:support on an input field and the user types frequently all the request raised by key up during requestDelay will be combined into one.
You can also manually specify multiple components which will produce similar requests. The "similarityGroupingId" attribute is added to all the Ajax action components with 3.3.0 release. Hence, for example, you can add two <a4j:support/> components to the input (one for key up and the second for blur) and define that request events are similar by specifying the same "similarityGroupingId".
As written above requests are collected in the queue during requestDelay and similar ones are combined. But similar requests can only be combined if they are raised sequentially. This is done in order not to block the queue and not to change the requests order.
Example:
A request with some delay comes to the queue, let it be A1 the delay counter for this request is started. If similar request(e.g. from the same component - A2) appears - these two requests are combined(A1A2 to Acombined ) and the counter is reset.
But if some not similar request comes to the queue B1 - it is placed after the first one(Acombined,B1). And if the Acombined request doesn't exit the queue and another request similar to A (let is be A3) appears again - these requests are not combined with the first one. The request is placed after B1. (Acombined, B1, A3).
Such behavior allows
to maximize similar requests throughput
to send only the latest fields state for similar requests
not to block the queue if the different types of requests comes to queue and should wait one for another
The <a4j:poll> component has delay time 0 by default staring from 3.3.0 version in order not to use the queue delay(its own value for this parameter redefines queue's parameter) to avoid blocking periodical update in the queue. You can redefine this on the component level if need.
RichFaces uses form based approach for Ajax request sending. This means each time, when you click an Ajax button or <a4j:poll> produces an asynchronous request, the data from the closest JSF form is submitted with the XMLHTTPRequest object. The form data contains the values from the form input element and auxiliary information such as state saving data.
When "ajaxSingle" attribute value is "true" , it orders to include only a value of the current component (along with <f:param> or <a4j:actionparam> values if any) to the request map. In case of <a4j:support> , it is a value of the parent component. An example is placed below:
...
<h:form>
<h:inputText value="#{person.name}">
<a4j:support event="onkeyup" reRender="test" ajaxSingle="true"/>
</h:inputText>
<h:inputText value="#{person.middleName}"/>
</form>
...
In this example the request contains only the input component causes the request
generation, not all the components contained on a form, because of
ajaxSingle="true"
usage.
Note, that ajaxSingle="true"
reduces the upcoming traffic,
but does not prevent decoding other input components on the server side. Some JSF
components, such as
<h:selectOneMenu>
do recognize the missing data in the request map value as a null value
and try to pass the validation process with a failed result. Thus, use
<a4j:region>
to limit a part of the component tree that will be processed on the
server side when it is required.
"immediate"
attribute has the same purpose as any other non-JSF component. The
default
"ActionListener"
should be executed immediately (i.e. during the Apply Request Values
phase of a request processing lifecycle), rather than waiting until the Invoke
Application phase. Using immediate="true"
is one of the ways
to have some data model values updated when other cannot be updated because of a
problem with passing the Validation phase successfully. This might be important
inside the
<h:dataTable>
like components where using
<a4j:region>
is impossible due to the
<h:dataTable>
component architecture.
"bypassUpdates" attribute allows to bypass the Update Model phase. It might be useful if you need to check your input against the available validator, but not to update the model with those data. Note, that an action will be invoked at the end of the Validation phase only if the Validation phase is passed successfully. The listeners of the Application phase will not be invoked in any case.
Ajax component is similar to any other non-Ajax JSF component like <h:commandButton> . It allows to submit the form. You can use "action" and "actionListener" attributes to invoke the action method and define the action event.
"action"
method must return null if you want to have an Ajax Response with a
partual page update. This is regular mode called "Ajax request generates
Non-Ajax Response"
. In case of action does not return null, but the
action outcome that matches one of navigation rules, RichFaces starts to work in
"Ajax request generates Non-Ajax Response"
mode. This
mode might be helpful in two major cases:
RichFaces allows to organize a page flow inside the <a4j:include> component. This is a typical scenario for Wizard like behavior. The new content is rendered inside the <a4j:include> area. The content is taken from the navigation rule of the faces configuration file (usually, the faces-config.xml). Note, that the content of the "wizard" is not isolated from the rest of the page. The included page should not have own <f:view> (it does not matter if you use facelets). You need to have an Ajax component inside the <a4j:include> to navigate between the wizard pages. Otherwize, the whole page update will be performed.
If you want to involve the server-side validators and navigate to the next page only if the Validation phase is passed successfully, you can replace <h:commandButton> with <a4j:commandButton> and point to the action method that navigates to the next page. If Validation process fails, the partial page update will occur and you will see an error message. Otherwize, the application proceeds to the next page. Make sure, you define <redirect/> option for the navigation rule to avoid memory leaks.
RichFaces allows writing Ajax-enabled JSF application without writing any Javascript code. However, you can still invoke the JavaScript code if you need. There are several Ajax attributes that helps to do it.
"onsubmit" attribute allows to invoke JavaScript code before an Ajax request is sent. If "onsubmit" returns "false" , the Ajax request is canceled. The code of "onsubmit" is inserted before the RichFaces Ajax call. Hence, the "onsubmit" should not has a "return" statement if you want the Ajax request to be sent. If you are going to invoke a JavaScript function that returns "true" or "false" , use the conditional statement to return something only when you need to cancel the request. For example:
...
onsubmit="if (mynosendfunct()==false){return false}"
...
"onclick" attribute is similar to the "onsubmit" , but for clickable components such as <a4j:commandLink> and <a4j:commandButton> . If it returns "false" , the Ajax request is canceled also.
The "oncomplete"
attribute is used for passing JavaScript that would be invoked right
after the Ajax response returns back and DOM is updated. It is not recommended to
use use keyword this
inside the EL-expression, because it will not
always point to the component where Ajax request was initiated.
"onbeforedomupdate" attribute defines JavaScript code for call after Ajax response receiving and before updating DOM on a client side.
"data" attribute allows to get the additional data from the server during an Ajax call. You can use JSF EL to point the property of the managed bean and its value will be serialized in JSON format and be available on the client side. You can refer to it using the "data" variable. For example:
...
<a4j:commandButton value="Update" data="#{userBean.name}" oncomplete="showTheName(data.name)" />
...
RichFaces allows to serialize not only primitive types into JSON format, but also complex types including arrays and collections. The beans should be serializable to be refered with "data" .
There is a number of useful functions which can be used in JavaScript:
rich:clientId('id')
- returns client id by short id or null if
the component with the id specified hasn't been found
rich:element('id')
- is a shortcut for
document.getElementById(#{rich:clientId('id')})
rich:component('id')
- is a shortcut for
#{rich:clientId('id')}.component
rich:findComponent('id')
- returns an instance of UIComponent
taking the short ID of the component as a parameter.
...
<h:inputText id="myInput">
<a4j:support event="onkeyup" reRender="outtext"/>
</h:inputText>
<h:outputText id="outtext" value="#{rich:findComponent('myInput').value}" />
...
"ajaxKeys" attribute defines strings that are updated after an Ajax request. It provides possibility to update several child components separately without updating the whole page.
...
<a4j:poll intervall="1000" action="#{repeater.action}" reRender="text">
<table>
<tbody>
<a4j:repeat value="#{bean.props}" var="detail" ajaxKeys="#{repeater.ajaxedRowsSet}">
<tr>
<td>
<h:outputText value="detail.someProperty" id="text"/>
</td>
</tr>
</a4j:repeat>
</tbody>
</table>
</a4j:poll>
...
"status" attribute for Ajax components (such as <a4j:commandButton> , <a4j:poll> , etc.) points to an ID of <a4j:status> component. Use this attribute if you want to share <a4j:status> component between different Ajax components from different regions. The following example shows it.
...
<a4j:region id="extr">
<h:form>
<h:outputText value="Status:" />
<a4j:status id="commonstatus" startText="In Progress...." stopText=""/>
<h:panelGrid columns="2">
<h:outputText value="Name"/>
<h:inputText id="name" value="#{userBean.name}">
<a4j:support event="onkeyup" reRender="out" />
</h:inputText>
<h:outputText value="Job"/>
<a4j:region id="intr">
<h:inputText id="job" value="#{userBean.job}">
<a4j:support event="onkeyup" reRender="out" status="commonstatus"/>
</h:inputText>
</a4j:region>
</h:panelGrid>
<a4j:region>
<h:outputText id="out" value="Name: #{userBean.name}, Job: #{userBean.job}" />
<br />
<a4j:commandButton ajaxSingle="true" value="Clean Up Form" reRender="name, job, out" status="commonstatus">
<a4j:actionparam name="n" value="" assignTo="#{userBean.name}" />
<a4j:actionparam name="j" value="" assignTo="#{userBean.job}" />
</a4j:commandButton>
</a4j:region>
</h:form>
</a4j:region>
...
In the example <a4j:support> and <a4j:commandButton> are defined in different regions. Values of "status" attribute for these components points to an ID of <a4j:support> .Thus, the <a4j:support> component is shared between two components from different regions.
More information could be found on the RichFaces Live Demo .
Other useful attribute is "focus" . It points to an ID of a component where focus will be set after an Ajax request.
This section of the guide summarizes all Ajax-related attributes that both rich and a4j components have.
Table 5.2. Title of the table
Attribute | Description | A4J Components | Rich Components |
---|---|---|---|
ajaxSingle | Limits JSF tree processing (decoding, conversion, validation and model updating) only to a component that sends the request. Boolean. Default value is "false". |
<a4j:form> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:poll> <a4j:push> |
<rich:dataFilterSlider> <rich:dataFilterSlider> <rich:datascroller> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:treeNode> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tab> <rich:toggleControl> <rich:toolTip> <rich:calendar> <rich:fileUpload> <rich:suggestionbox> |
bypassUpdates | If "true", after process validations phase it skips updates of model beans on a force render response. It can be used for validating components input |
<a4j:form> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:poll> <a4j:push> |
<rich:dataFilterSlider> <rich:datascroller> <rich:scrollableDataTable> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:treeNode> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:calendar> <rich:suggestionbox> |
limitToList | If "true", then of all AJAX-rendered on the page components only those will be updated, which ID's are passed to the "reRender" attribute of the describable component. "false"-the default value-means that all components with ajaxRendered="true" will be updated. | <a4j:form> <a4j:support> <a4j:commandButton> <a4j:jsFunction> <a4j:poll> <a4j:push> | <rich:ajaxValidator> <rich:dataFilterSlider> <rich:datascroller> <rich:dragSupport> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:treeNode> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tab> <rich:toggleControl> <rich:calendar> <rich:suggestionbox> |
reRender | Id['s] (in format of call UIComponent.findComponent()) of components, rendered in case of AjaxRequest caused by this component. Can be single id, comma-separated list of Id's, or EL Expression with array or Collection | <a4j:form> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:poll> <a4j:push> | <rich:ajaxValidator> <rich:dataFilterSlider> <rich:datascroller> <rich:dataTable> <rich:extendedDataTable> <rich:scrollableDataTable> <rich:dragSupport> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:treeNode> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tab> <rich:calendar> <rich:suggestionbox> |
process | Id['s] (in format of call UIComponent.findComponent()) of components, processed at the phases 2-5 in case of AjaxRequest caused by this component. Can be single id, comma-separated list of Id's, or EL Expression with array or Collection | <a4j:form> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:poll> <a4j:push> | <rich:dataFilterSlider> <rich:datascroller> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:treeNode> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tab> <rich:toggleControl> <rich:calendar> <rich:suggestionbox> |
status | ID (in format of call UIComponent.findComponent()) of Request status component | <a4j:form> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:poll> <a4j:push> <a4j:queue> | <rich:ajaxValidator> <rich:dataFilterSlider> <rich:datascroller> <rich:scrollableDataTable> <rich:dragSupport> <rich:dropSupport> <rich:tree> <rich:treeNode> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tab> <rich:toggleControl> <rich:calendar> <rich:fileUpload> <rich:suggestionbox> |
eventsQueue | Name of requests queue to avoid send next request before complete other from same event. Can be used to reduce number of requests of frequently events (key press, mouse move etc.) | <a4j:form> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:poll> <a4j:push> | <rich:ajaxValidator> <rich:dataFilterSlider> <rich:datascroller> <rich:scrollableDataTable> <rich:dragSupport> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tab> <rich:toggleControl> <rich:calendar> <rich:suggestionbox> |
requestDelay | Attribute defines the time (in ms.) that the request will be wait in the queue before it is ready to send. When the delay time is over, the request will be sent to the server or removed if the newest 'similar' request is in a queue already | <a4j:form> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:queue> | <rich:ajaxValidator> <rich:dataFilterSlider> <rich:datascroller> <rich:scrollableDataTable> <rich:dragSupport> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:simpleTogglePanel> <rich:tab> <rich:calendar> <rich:suggestionbox> |
data | Serialized (on default with JSON) data passed on the client by a developer on AJAX request. It's accessible via "data.foo" syntax | <a4j:form> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:poll> <a4j:push> | <rich:ajaxValidator> <rich:dataFilterSlider> <rich:datascroller> <rich:scrollableDataTable> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:treeNode> <rich:paint2D> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tab> <rich:toggleControl> <rich:calendar> |
ignoreDupResponses | Attribute allows to ignore an Ajax Response produced by a request if the newest 'similar' request is in a queue already. ignoreDupResponses="true" does not cancel the request while it is processed on the server, but just allows to avoid unnecessary updates on the client side if the response isn't actual now | <a4j:form> <a4j:support> <a4j:commandButton> <a4j:jsFunction> <a4j:poll> <a4j:push> <a4j:queue> | <rich:ajaxValidator> <rich:dataFilterSlider> <rich:datascroller> <rich:scrollableDataTable> <rich:dragSupport> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:treeNode> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tab> <rich:toggleControl> <rich:calendar> <rich:suggestionbox> |
timeout | Response waiting time on a particular request. If a response is not received during this time, the request is aborted | <a4j:form> <a4j:form> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:poll> <a4j:push> <a4j:queue> | <rich:ajaxValidator> <rich:dataFilterSlider> <rich:datascroller> <rich:scrollableDataTable> <rich:dragSupport> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:treeNode> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tab> <rich:toggleControl> <rich:suggestionbox> |
similarityGroupingId | If there are any component requests with identical IDs then these requests will be grouped. | <a4j:form> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:poll> | <rich:ajaxValidator> <rich:dataFilterSlider> <rich:datascroller> <rich:scrollableDataTable> <rich:dragSupport> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:treeNode> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tab> <rich:toggleControl> <rich:calendar> <rich:suggestionbox> <rich:message> <rich:messages> |
keepTransient | Flag for mark all child components to non-transient. If "true", all children components will be set to non-transient state and keep in saved components tree. For output in self-renderer region all content (By default, all content in <f:verbatim> tags and non-jsf elements in facelets, marked as transient - since, self-rendered ajax regions don't plain output for ajax processing). The default value is "false". | <a4j:include> <a4j:outputPanel> | |
ajaxListener | MethodExpression representing an action listener method that will be notified when this component is activated by the ajax Request and handle it. The expression must evaluate to a public method that takes an AjaxEvent parameter, with a return type of void. | <a4j:include> <a4j:outputPanel> | |
selfRendered | if "true", self-render subtree at InvokeApplication ( or Decode, if immediate property set to true ) phase | <a4j:page> <a4j:region> | <rich:suggestionbox> |
immediate | Flag indicating that, if this component is activated by ajaxrequest, notifications should be delivered to interested listeners and actions immediately (that is, during Apply Request Values phase) rather than waiting until Invoke Application phase | <a4j:region> <a4j:region> <a4j:support> <a4j:commandButton> <a4j:commandLink> <a4j:jsFunction> <a4j:poll> <a4j:push> <a4j:page> <a4j:htmlCommandLink> | <rich:dataFilterSlider> <rich:datascroller> <rich:dragSupport> <rich:dropSupport> <rich:menuItem> <rich:tree> <rich:panelBar> <rich:panelMenu> <rich:panelMenuGroup> <rich:panelMenuItem> <rich:progressBar> <rich:simpleTogglePanel> <rich:tabPanel> <rich:tab> <rich:togglePanel> <rich:toggleControl> <rich:toolTip> <rich:calendar> <rich:colorPicker> <rich:comboBox> <rich:editor> <rich:inplaceInput> <rich:inplaceSelect> <rich:inputNumberSlider> <rich:inputNumberSpinner> <rich:suggestionbox> <rich:listShuttle> <rich:orderingList> <rich:pickList> |
mode | Defines the submission type: Ajax or Sever | <rich:panelMenu> <rich:panelMenuItem> <rich:progressBar> <rich:toolTip> <rich:calendar> | |
switchType | Defines the re-rendering mode: Ajax, server, client. |
<rich:simpleTogglePanel> <rich:tabPanel> <rich:tab> <rich:togglePanel> <rich:tree> <rich:simpleTogglePanel> |
There are different ways to send Ajax requests from your JSF page. For example you can use <a4j:commandButton> , <a4j:commandLink> , <a4j:poll> or <a4j:support> tags or any other.
All these tags hide the usual JavaScript activities that are required for an XMHTTPRequest object building and an Ajax request sending. Also, they allow you to decide which components of your JSF page are to be re-rendered as a result of the Ajax response (you can list the IDs of these components in the "reRender" attribute).
<a4j:commandButton> and <a4j:commandLink> tags are used to send an Ajax request on "onclick" JavaScript event.
<a4j:poll> tag is used to send an Ajax request periodically using a timer.
The <a4j:support> tag allows you to add Ajax functionality to standard JSF components and send Ajax request onto a chosen JavaScript event: "onkeyup" , "onmouseover" , etc.
You may describe a region on the page you wish to send to the server, in this way you can control what part of the JSF View is decoded on the server side when you send an Ajax request.
The easiest way to describe an Ajax region on your JSF page is to do nothing, because the content between the <f:view> and </f:view> tags is considered the default Ajax region.
You may define multiple Ajax regions on the JSF page (they can even be nested) by using the <a4j:region> tag.
If you wish to render the content of an Ajax response outside of the active region then the value of the "renderRegionOnly" attribute should be set to "false" ("false" is default value). Otherwise, your Ajax updates are limited to elements of the active region.
Using IDs in the
"reRender"
attribute to define "AJAX zones"
for update works
fine in many cases.
But you can not use this approach if your page contains, e.g. a <f:verbatim> tag and you wish to update its content on an Ajax response.
The problem with the <f:verbatim/> tag as described above is related to the value of the transientFlag of JSF components. If the value of this flag is true, the component must not participate in state saving or restoring of process.
In order to provide a solution to this kind of problems, RichFaces uses the concept of an output panel that is defined by the <a4j:outputPanel> tag. If you put a <f:verbatim> tag inside of the output panel, then the content of the <f:verbatim/> tag and content of other panel's child tags could be updated on Ajax response. There are two ways to control this:
By setting the "ajaxRendered" attribute value to "true".
By setting the "reRender" attribute value of an Action Component to the output panel ID.
The "process" attribute allows to define the ids of components to be processed together with the component which is marked as ajaxSingle or wrapped to region.
You could make use of the "process" attribute when you need to process only two components in the different parts of view.
Imagine you need to process only two input fields but not all the view. If you
wrap the first input to region or make
<a4j:support>
component with ajaxSingle="true"
nested the
second input will not be processed.
Here is a simple solution:
...
<h:inputText value="#{bean.name}" id="name">
<a4j:support ajaxSingle="true" process="email" event="onblur" reRender="someOut"/>
</h:inputText>
<h:inputTextarea value="#{bean.description}" id="desc" />
<h:inputText value="#{bean.email}" id="email">
<a4j:support ajaxSingle="true" process="name" event="onblur" reRender="someOut"/>
</h:inputText>
...
In the example above when the input field with the
id="name"
looses focus, an Ajax request is sent. So only
two input fields (with id="name"
and additionally with
id="email"
) are processed: decoding,
conversion/validation, value applying phases are executed. The input field with the
id="email"
is handled the same way on blur event.
RichFaces uses a filter for a correction of code received on an Ajax request. In case of a "regular" JSF request a browser makes correction independently. In case of Ajax request in order to prevent layout destruction it's needed to use a filter, because a received code could differ from a code validated by a browser and a browser doesn't make any corrections.
An example of how to set a Filter in a web.xml file of your application is placed below.
Example:
...
<filter>
<display-name>RichFaces Filter</display-name>
<filter-name>richfaces</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
...
Fast Filter is deprecated and available only for backward compatibility with previous RichFaces versions. Fast Filter usage isn't recomended, because there is another way to use its functionality by means of Neko filter type .
From RichFaces 3.2 filter configuration becomes more flexible. It's possible to configure different filters for different sets of pages for the same application.
The possible filter types are:
TIDY
"TIDY" filter type based on the Tidy parser. This filter is recommended for applications with complicated or non-standard markup when all necessary code corrections are made by the filter when a response comes from the server.
"NEKO" filter type corresponds to the former "Fast Filter" and it's based on the Neko parser. In case of using this filter code isn't strictly verified. Use this one if you are sure that your application markup is really strict for this filter. Otherwise it could cause lot's of errors and corrupt a layout as a result. This filter considerably accelerates all Ajax requests processing.
NONE
No correction.
An example of configuration is placed below.
Example:
...
<context-param>
<param-name>org.ajax4jsf.xmlparser.ORDER</param-name>
<param-value>NONE,NEKO,TIDY</param-value>
</context-param>
<context-param>
<param-name>org.ajax4jsf.xmlparser.NONE</param-name>
<param-value>/pages/performance\.xhtml,/pages/default.*\.xhtml</param-value>
</context-param>
<context-param>
<param-name>org.ajax4jsf.xmlparser.NEKO</param-name>
<param-value>/pages/repeat\.xhtml</param-value>
</context-param>
<filter>
<display-name>RichFaces Filter</display-name>
<filter-name>richfaces</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>richfaces</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
...
The example shows that ORDER
parameter defines the order in which
particular filter types are used for pages code correction.
First of all "NONE" type is specified for the filter. Then two different sets of pages are defined for which two filter types (NONE and NEKO) are used correspondingly. If a page relates to the first set that is defined in the following way:
<param-value>/pages/performance\.xhtml,/pages/default.*\.xhtml</param-value>
it's not corrected, because filter type for this page is defined as "NONE". If a page is not from the first set, then "NEKO" type is set.
If a page relates to the second set that is defined in the following way:
<param-value>/pages/repeat\.xhtml</param-value>
then "NEKO" filter type is used for correction. If it's not related to the second set, "TIDY" type is set for the filter ("TIDY" filter type is used for code correction).
Before the version 3.1.3, RichFaces loaded styles and script on demand. I.e. files are loaded only if they are required on a particular page. Since RichFaces 3.1.3, it's possible to manage how the RichFaces script and style files are loaded to application.
org.richfaces.LoadScriptStrategy
The following declaration in your web.xml allows loading the integrated script files.
...
<context-param>
<param-name>org.richfaces.LoadScriptStrategy</param-name>
<param-value>ALL</param-value>
</context-param>
...
If you do not declare the org.richfaces.LoadScriptStrategy
in the
web.xml, it equals to:
...
<context-param>
<param-name>org.richfaces.LoadScriptStrategy</param-name>
<param-value>DEFAULT</param-value>
</context-param>
...
The third possible value is "NONE". You have no a special reason to use it unless you obtain the newest (or modified) version of the script and want to include it manually in a page header.
org.richfaces.LoadStyleStrategy
The following declaration allows to load only one integrated style sheet file.
...
<context-param>
<param-name>org.richfaces.LoadStyleStrategy</param-name>
<param-value>ALL</param-value>
</context-param>
...
The integrated style sheet contains style for all shipped components. The skinnability feature still works.
The "DEFAULT" value is a classical on-demand variant.
The "NONE" stops loading the styles at all. The earlier introduced plain
skin resets all color and font parameters to null. The "NONE" value for
org.richfaces.LoadStyleStrategy
means that predefined styles for
RichFaces are not used.
For more information see RichFaces User Forum .
RichFaces allows to redefine standard handlers responsible for processing of different exceptional situations. It helps to define own JavaScript, which is executed when these situations occur.
Add the following code to web.xml:
<context-param>
<param-name>org.ajax4jsf.handleViewExpiredOnClient</param-name>
<param-value>true</param-value>
</context-param>
To execute your own code on the client in case of an error during Ajax request,
it's necessary to redefine the standard
"A4J.AJAX.onError"
method:
A4J.AJAX.onError = function(req, status, message){
window.alert("Custom onError handler "+message);
}
The function defined this way accepts as parameters:
req
- a params string of a request that calls an error
status
- the number of an error returned by the server
message
- a default message for the given error
Thus, it's possible to create your own handler that is called on timeouts, internal server errors, and etc.
It's possible to redefine also the "onExpired" framework method that is called on the "Session Expiration" event.
Example:
A4J.AJAX.onExpired = function(loc, expiredMsg){
if(window.confirm("Custom onExpired handler "+expiredMsg+" for a location: "+loc)){
return loc;
} else {
return false;
}
}
Here the function receives in params:
loc
- URL of the current page (on demand can be updated)
expiredMsg
- a default message on
"Session Expiration"
event.
Note that custom "onError", "onExpire" handlers do not work under MyFaces. MyFaces handles exception by its internals generating debug page. You could use the following code to prevent such behavior:
...
<context-param>
<param-name>org.apache.myfaces.ERROR_HANDLING</param-name>
<param-value>false</param-value>
</context-param>
...
If you have a look at a CSS file in an enterprise application, for example, the one you're working on now, you'll see how often the same color is noted in it. Standard CSS has no way to define a particular color abstractly for defining as a panel header color, a background color of an active pop-up menu item, a separator color, etc. To define common interface styles, you have to copy the same values over and over again and the more interface elements you have the more copy-and-paste activity that needs to be performed.
Hence, if you want to change the application palette, you have to change all interrelating values, otherwise your interface can appear a bit clumsy. The chances of such an interface coming about is very high, as CSS editing usually becomes the duty of a general developer who doesn't necessarily have much knowledge of user interface design.
Moreover, if a customer wishes to have an interface look-and-feel that can be adjusted on-the-fly by an end user, your work is multiplied, as you have to deal with several CSS files variants, each of which contains the same values repeated numerous times.
These problems can be solved with the skinnability system built into the RichFaces project and implemented fully in RichFaces. Every named skin has some skin-parameters for the definition of a palette and the other parameters of the user interface. By changing just a few parameters, you can alter the appearance of dozens of components in an application in a synchronized fashion without messing up user interface consistency.
The skinnability feature can't completely replace standard CSS and certainly doesn't eliminate its usage. Skinnability is a high-level extension of standard CSS, which can be used together with regular CSS declarations. You can also refer to skin parameters in CSS via JSF Expression Language. You have the complete ability to synchronize the appearance of all the elements in your pages.
RichFaces skinnability is designed for mixed usage with:
Skin parameters defined in the RichFaces framework
Predefined CSS classes for components
User style classes
The color scheme of the component can be applied to its elements using any of three style classes:
A default style class inserted into the framework
This contains style parameters linked to some constants from a skin. It is defined for every component and specifies a default representation level. Thus, an application interface could be modified by changing the values of skin parameters.
A style class of skin extension
This class name is defined for every component element and inserted into the framework to allow defining a class with the same name into its CSS files. Hence, the appearance of all components that use this class is extended.
User style class
It's possible to use one of the styleClass parameters for component elements and define your own class in it. As a result, the appearance of one particular component is changed according to a CSS style parameter specified in the class.
Here is a simple panel component:
Example:
<rich:panel> ... </rich:panel>
The code generates a panel component on a page, which consists of two elements: a wrapper <div> element and a <div> element for the panel body with the particular style properties. The wrapper <div> element looks like:
Example:
<div class="dr-pnl rich-panel">
...
</div>
dr-pnl is a CSS class specified in the framework via skin parameters:
background-color is defined with generalBackgroundColor
border-color is defined with panelBorderColor
It's possible to change all colors for all panels on all pages by changing these skin parameters.
However, if a <rich:panel> class is specified somewhere on the page, its parameters are also acquired by all panels on this page.
A developer may also change the style properties for a particular panel. The following definition:
Example:
<rich:panel styleClass="customClass" />
Could add some style properties from customClass to one particular panel, as a result we get three styles:
Example:
<div class="dr_pnl rich-panel customClass">
...
</div>
RichFaces provides eight predefined skin parameters (skins) at the simplest level of common customization:
DEFAULT
plain
emeraldTown
blueSky
wine
japanCherry
ruby
classic
deepMarine
To plug one in, it's necessary to specify a skin name in the
org.richfaces.SKIN
context-param.
Here is an example of a table with values for one of the main skins, "blueSky" .
Table 5.3. Colors
Parameter name | Default value |
---|---|
headerBackgroundColor | #BED6F8 |
headerGradientColor | #F2F7FF |
headTextColor | #000000 |
headerWeightFont | bold |
generalBackgroundColor | #FFFFFF |
generalTextColor | #000000 |
generalSizeFont | 11px |
generalFamilyFont | Arial, Verdana, sans-serif |
controlTextColor | #000000 |
controlBackgroundColor | #ffffff |
additionalBackgroundColor | #ECF4FE |
shadowBackgroundColor | #000000 |
shadowOpacity | 1 |
panelBorderColor | #BED6F8 |
subBorderColor | #ffffff |
tabBackgroundColor | #C6DEFF |
tabDisabledTextColor | #8DB7F3 |
trimColor | #D6E6FB |
tipBackgroundColor | #FAE6B0 |
tipBorderColor | #E5973E |
selectControlColor | #E79A00 |
generalLinkColor | #0078D0 |
hoverLinkColor | #0090FF |
visitedLinkColor | #0090FF |
Table 5.4. Fonts
Parameter name | Default value |
---|---|
headerSizeFont | 11px |
headerFamilyFont | Arial, Verdana, sans-serif |
tabSizeFont | 11px |
tabFamilyFont | Arial, Verdana, sans-serif |
buttonSizeFont | 11px |
buttonFamilyFont | Arial, Verdana, sans-serif |
tableBackgroundColor | #FFFFFF |
tableFooterBackgroundColor | #cccccc |
tableSubfooterBackgroundColor | #f1f1f1 |
tableBorderColor | #C0C0C0 |
Skin "plain" was added from 3.0.2 version. It doesn't have any parameters. It's necessary for embedding RichFaces components into existing projecst which have its own styles.
To get detailed information on particular parameter possibilities, see the chapter where each component has skin parameters described corresponding to its elements.
In order to create your own skin file, do the following:
Create a file and define in it skin constants which are used by style
classes (see section
"Skin Parameters Tables in RichFaces"
). The name of skin file should correspond to the following format:
<name>.skin.properties
. As an example of such file
you can see RichFaces predefined skin parameters (skins): blueSky, classic,
deepMarine, etc. These files are located in the
richfaces-impl-xxxxx.jar
inside the /META-INF/skins folder.
Add a skin definition <contex-param>
to the web.xml of
your application. An example is placed below:
Example:
...
<context-param>
<param-name>org.richfaces.SKIN</param-name>
<param-value>name</param-value>
</context-param>
...
Put your <name>.skin.properties
file in one of the
following classpath elements: META-INF/skins/ or classpath folder (e.g.
WEB-INF/classes).
RichFaces gives an opportunity to incorporate skinnability into UI design. With this framework you can easily use named skin parameters in properties files to control the appearance of the skins that are applied consistently to a whole set of components. You can look at examples of predefined skins at:
http://livedemo.exadel.com/richfaces-demo/ |
You may simply control the look-and-feel of your application by using the skinnability service of the RichFaces framework. With the means of this service you can define the same style for rendering standard JSF components and custom JSF components built with the help of RichFaces.
To find out more on skinnability possibilities, follow these steps:
Create a custom render kit and register it in the faces-config.xml like this:
<render-kit>
<render-kit-id>NEW_SKIN</render-kit-id>
<render-kit-class>org.ajax4jsf.framework.renderer.ChameleonRenderKitImpl</render-kit-class>
</render-kit>
Then you need to create and register custom renderers for the component based on the look-and-feel predefined variables:
<renderer>
<component-family>javax.faces.Command</component-family>
<renderer-type>javax.faces.Link</renderer-type>
<renderer-class>newskin.HtmlCommandLinkRenderer</renderer-class>
</renderer>
Finally, you need to place a properties file with skin parameters into the class path root. There are two requirements for the properties file:
The file must be named
<skinName>.skin.properties
, in this case, it
would be called newskin.skin.properties
.
The first line in this file should be
render.kit=<render-kit-id>
in this case, it would be called
render.kit=NEW_SKIN
.
Extra information on custom renderers creation can be found at:
http://java.sun.com/javaee/javaserverfaces/reference/docs/index.html |
It's possible to change skins in runtime. In order to do that, define the EL-expression in the web.xml. For example:
<context-param>
<param-name>org.richfaces.SKIN</param-name>
<param-value>#{skinBean.skin}</param-value>
</context-param>
The skinBean
code looks as follows:
public class SkinBean {
private String skin;
public String getSkin() {
return skin;
}
public void setSkin(String skin) {
this.skin = skin;
}
}
Further, it is necessary to set the skin property to the initial value in the configuration file. For example, "classic":
<managed-bean>
<managed-bean-name>skinBean</managed-bean-name>
<managed-bean-class>SkinBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>skin</property-name>
<value>classic</value>
</managed-property>
</managed-bean>
You can also change the default skin, for instance, change the default color. To do this, edit the file properties of the skin. Here is an example of the code for page:
<h:form>
<div style="display: block; float: left">
<h:selectOneRadio value="#{skinBean.skin}" border="0" layout="pageDirection" title="Changing skin" style="font-size: 8; font-family: comic" onchange="submit()">
<f:selectItem itemLabel="plain" itemValue="plain" />
<f:selectItem itemLabel="emeraldTown" itemValue="emeraldTown" />
<f:selectItem itemLabel="blueSky" itemValue="blueSky" />
<f:selectItem itemLabel="wine" itemValue="wine" />
<f:selectItem itemLabel="japanCherry" itemValue="japanCherry" />
<f:selectItem itemLabel="ruby" itemValue="ruby" />
<f:selectItem itemLabel="classic" itemValue="classic" />
<f:selectItem itemLabel="laguna" itemValue="laguna" />
<f:selectItem itemLabel="deepMarine" itemValue="deepMarine" />
<f:selectItem itemLabel="blueSky Modified" itemValue="blueSkyModify" />
</h:selectOneRadio>
</div>
<div style="display: block; float: left">
<rich:panelBar height="100" width="200">
<rich:panelBarItem label="Item 1" style="font-family: monospace; font-size: 12;">
Changing skin in runtime
</rich:panelBarItem>
<rich:panelBarItem label="Item 2" style="font-family: monospace; font-size: 12;">
This is a result of the modification "blueSky" skin
</rich:panelBarItem>
</rich:panelBar>
</div>
</h:form>
This is result:
The feature is designed to unify the look and feel of standard HTML element and RichFaces components. Skinning can be applied to all controls on a page basing on elements' name and attribute type (where applicable). Also this feature provides a set of CSS styles so that skinning can be applied assigning rich-* classes to particular elements or to container of elements that nests controls.
Standard controls skinning feature provides 2 levels of skinning: Standard and Extended. The level is based
on detecting the browser type. If browser type is not identified, Advanced level is
used. However, if you want to explicitly specify the level of skinning you want to be applied, you need to add a context parameter to your web.xml
with org.richfaces.CONTROL_SKINNING_LEVEL
as the parameter name
and value set to either basic
or extended
.
Standard level provides customization for only basic style properties.
To the following browsers Standard level of skinning is applied:
Internet Explorer 6
Internet Explorer 7 in BackCompat mode (see document.compatMode property in MSDN )
Opera
Safari
Extended level extends basic level introducing broader number of style properties and is applied to browsers with rich visual styling capability of controls
The following browsers support Extended level of skinning:
Mozilla Firefox
Internet Explorer 7 in Standards-compliant mode (CSS1Compat mode)
These are the elements that affected by skinning:
input
select
textarea
keygen
isindex
legend
fieldset
hr
a (together with a:hover, a:visited "pseudo"-elements)
Skinning for standard HTML controls can be initialized in two ways:
by adding org.richfaces.CONTROL_SKINNING
parameter to web.xml.
Values: "enable" and "disable". This way implies that
skinning style properties are applied to elements by element name and
attribute type (where applicable). No additional steps required. Please find
below the table that contains the list of elements to which skinning is
applicable.
by adding org.richfaces.CONTROL_SKINNING_CLASSES
parameter to
web.xml file. Possible values "enable" and "disable".
When this option is enabled you are provided with a set of predefined CSS classes
that you can use for skinning your HTML components.
By setting org.richfaces.CONTROL_SKINNING_CLASSES
to
"enable" you are provided with style classes applicable to:
Basic elements nested inside element having rich-container class, e.g.:
Example:
...
.rich-container select {
//class content
}
...
Elements that have class name corresponding to one of the basic elements
name/type mapped by the following scheme
rich-<elementName>[-<elementType>]
. See the
example:
Example:
...
.rich-select {
//class content
}
.rich-input-text {
//class content
}
...
Elements have classes based on "link" and pseudo class name, e.g.: rich-link, rich-link-hover, rich-link-visited
Additionally, the predefined rich CSS classes that we provide can be used not only as classes for basic HTML elements but also as classes for creation of complex elements .
There is a snippet with some of them for example:
...
<u:selector name=".rich-box-bgcolor-header">
<u:style name="background-color" skin="headerBackgroundColor" />
</u:selector>
<u:selector name=".rich-box-bgcolor-general">
<u:style name="background-color" skin="generalBackgroundColor" />
</u:selector>
...
//gradient elements
...
<u:selector name=".rich-gradient-menu">
<u:style name="background-image">
<f:resource f:key="org.richfaces.renderkit.html.gradientimages.MenuGradientImage"/>
</u:style>
<u:style name="background-repeat" value="repeat-x" />
</u:selector>
<u:selector name=".rich-gradient-tab">
<u:style name="background-image">
<f:resource f:key="org.richfaces.renderkit.html.gradientimages.TabGradientImage"/>
</u:style>
<u:style name="background-repeat" value="repeat-x" />
</u:selector>
...
To get a better idea of standard component skinning we recommend to explore CSS files located in ui/core/src/main/resources/org/richfaces/ folder of RichFaces svn.
Table 5.5. Html Elements Skin Bindings for input, select, textarea, button, keygen, isindex, legend
CSS Properties | Skin parameters |
---|---|
font-size | generalSizeFont |
font-family | generalFamilyFont |
color | controlTextColor |
Table 5.6. Html Elements Skin Bindings for fieldset
CSS Properties | Skin parameters |
---|---|
border-color | panelBorderColor |
Table 5.7. Html Elements Skin Bindings for hr
CSS Properties | Skin parameters |
---|---|
border-color | panelBorderColor |
Table 5.9. Html Elements Skin Bindings for a:hover
CSS Properties | Skin parameters |
---|---|
color | hoverLinkColorgeneralLinkColor |
Table 5.10. Html Elements Skin Bindings for a:visited
CSS Properties | Skin parameters |
---|---|
color | visitedLinkColor |
Table 5.11. Rich Elements Skin Bindings for .rich-input, .rich-select, .rich-textarea, .rich-keygen, .rich-isindex, .rich-link
CSS Properties | Skin parameters |
---|---|
font-size | generalSizeFont |
font-family | generalFamilyFont |
color | controlTextColor |
Table 5.12. Rich Elements Skin Bindings for .rich-fieldset
CSS Properties | Skin parameters |
---|---|
border-color | panelBorderColor |
Table 5.13. Rich Elements Skin Bindings for .rich-hr
CSS Properties | Skin parameters/Value |
---|---|
border-color | panelBorderColor |
border-width | 1px |
border-style | solid |
Table 5.14. Rich Elements Skin Bindings for .rich-link
CSS Properties | Skin parameters |
---|---|
color | generalLinkColor |
Table 5.15. Rich Elements Skin Bindings for .rich-link:hover
CSS Properties | Skin parameters |
---|---|
color | hoverLinkColor |
Table 5.16. Rich Elements Skin Bindings for .rich-link:visited
CSS Properties | Skin parameters |
---|---|
color | visitedLinkColor |
Table 5.17. Rich Elements Skin Bindings for .rich-field
CSS Properties | Skin parameters/Value |
---|---|
border-width | 1px |
border-style | inset |
border-color | panelBorderColor |
background-color | controlBackgroundColor |
background-repeat | no-repeat |
background-position | 1px 1px |
Table 5.18. Rich Elements Skin Bindings for .rich-field-edit
CSS Properties | Skin parameters/Value |
---|---|
border-width | 1px |
border-style | inset |
border-color | panelBorderColor |
background-color | editBackgroundColor |
Table 5.19. Rich Elements Skin Bindings for .rich-field-error
CSS Properties | Skin parameter/Value |
---|---|
border-width | 1px |
border-style | inset |
border-color | panelBorderColor |
background-color | warningBackgroundColor |
background-repeat | no-repeat |
background-position | center left |
padding-left | 7px |
Table 5.20. Rich Elements Skin Bindings for .rich-button, .rich-button-disabled, .rich-button-over
CSS Properties | Skin parameter/Value |
---|---|
border-width | 1px |
border-style | solid |
border-color | panelBorderColor |
background-color | trimColor |
padding | 2px 10px 2px 10px |
text-align | center |
cursor | pointer |
background-repeat | repeat-x |
background-position | top left |
Table 5.21. Rich Elements Skin Bindings for .rich-button-press
CSS Properties | Skin parameter/Value |
---|---|
background-position | bottom left |
Table 5.22. Rich Elements Skin Bindings for .rich-container fieldset, .rich-fieldset
CSS Properties | Skin parameters/Value |
---|---|
border-color | panelBorderColor |
border-width | 1px |
border-style | solid |
padding | 10px |
padding | 10px |
Table 5.23. Rich Elements Skin Bindings for .rich-legend
CSS Properties | Skin parameter/Value |
---|---|
font-size | generalSizeFont |
font-family | generalFamilyFont |
color | controlTextColor |
font-weight | bold |
Table 5.24. Rich Elements Skin Bindings for .rich-form
CSS Properties | Skin parameters/Value |
---|---|
padding | 0px |
margin | 0px |
Table 5.25. Html Elements Skin Bindings for input, select, textarea, button, keygen, isindex
CSS properties | Skin parameters/Value |
---|---|
border-width | 1px |
border-color | panelBorderColor |
color | controlTextColor |
Table 5.26. Html Elements Skin Bindings for *|button
CSS properties | Skin parameters |
---|---|
border-color | panelBorderColor |
font-size | generalSizeFont |
font-family | generalFamilyFont |
color | headerTextColor |
background-color | headerBackgroundColor |
background-image | org.richfaces.renderkit.html.images.ButtonBackgroundImage |
Table 5.27. Html Elements Skin Bindings for button[type=button], button[type=reset], button[type=submit], input[type=reset], input[type=submit], input[type=button]
CSS properties | Skin parameters |
---|---|
border-color | panelBorderColor |
font-size | generalSizeFont |
font-family | generalFamilyFont |
color | headerTextColor |
background-color | headerBackgroundColor |
background-image | org.richfaces.renderkit.html.images.ButtonBackgroundImage |
Table 5.28. Html Elements Skin Bindings for *|button[disabled], .rich-container *|button[disabled], .rich-button-disabled
CSS properties | Skin parameters |
---|---|
color | tabDisabledTextColor |
border-color | tableFooterBackgroundColor |
background-color | tableFooterBackgroundColor |
background-image | org.richfaces.renderkit.html.images.ButtonDisabledBackgroundImage |
Table 5.29. Html Elements Skin Bindings for .rich-button-disabled, .rich-container button[type="button"][disabled], .rich-button-button-disabled, .rich-container button[type="reset"][disabled], .rich-button-reset-disabled, .rich-container button[type="submit"][disabled], .rich-button-submit-disabled, .rich-container input[type="reset"][disabled], .rich-input-reset-disabled, .rich-container input[type="submit"][disabled], .rich-input-submit-disabled, .rich-container input[type="button"][disabled], .rich-input-button-disabled
CSS properties | Skin parameters |
---|---|
color | tabDisabledTextColor |
background-color | tableFooterBackgroundColor |
border-color | tableFooterBackgroundColor |
background-image | org.richfaces.renderkit.html.images.ButtonDisabledBackgroundImage |
Table 5.30. Html Elements Skin Bindings for *button[type="button"][disabled], button[type="reset"][disabled], button[type="submit"][disabled], input[type="reset"][disabled], input[type="submit"][disabled], input[type="button"][disabled]
CSS properties | Skin parameters |
---|---|
color | tabDisabledTextColor |
border-color | tableFooterBackgroundColor |
background-color | tableFooterBackgroundColor |
Table 5.31. Html Elements Skin Bindings for *|textarea
CSS properties | Skin parameters |
---|---|
border-color | panelBorderColor |
font-size | generalSizeFont |
font-family | generalFamilyFont |
color | controlTextColor |
background-color | controlBackgroundColor |
background-image | org.richfaces.renderkit.html.images.InputBackgroundImage |
Table 5.32. Html Elements Skin Bindings for textarea[type=textarea], input[type=text], input[type=password], select
CSS properties | Skin parameters |
---|---|
border-color | panelBorderColor |
font-size | generalSizeFont |
font-family | generalFamilyFont |
color | controlTextColor |
background-color | controlBackgroundColor |
background-image | org.richfaces.renderkit.html.images.InputBackgroundImage |
Table 5.33. Html Elements Skin Bindings for *|textarea[disabled], .rich-container *|textarea[disabled]
CSS properties | Skin parameters |
---|---|
color | tableBorderColor |
Table 5.34. textarea[type="textarea"][disabled], input[type="text"][disabled], input[type="password"][disabled]
CSS properties | Skin parameters |
---|---|
color | tableBorderColor |
Table 5.35. textarea[type="textarea"][disabled], input[type="text"][disabled], input[type="password"][disabled]
CSS properties | Skin parameters |
---|---|
color | tableBorderColor |
Standard skinning level can fail if configuration of
ajaxPortlet
is as following:
...
<portlet>
<portlet-name>ajaxPortlet</portlet-name>
<header-content>
<script src="/faces/rfRes/org/ajax4jsf/framework.pack.js" type="text/javascript" />
<script src="/faces/rfRes/org/richfaces/ui.pack.js" type="text/javascript" />
<link rel="stylesheet" type="text/css" href="/faces/rfRes/org/richfaces/skin.xcss" />
</header-content>
</portlet>
...
Attention.
The <a4j:portlet> component is DEPRECATED as far as JSR-301 was defined the same functionality for a UIViewRoot
component.
Thus, it is implicitly defined by mandatory <f:view> component.
As it was mentioned earlier in the guide, extended skinning of standard HTML controls is applied automatically: the browser type is detected and if a browser doesn't fully support extended skinning feature, only basic skinning is applied.
However, if you don't want the RichFaces components and standard HTML controls to be skinned automatically and perform the skinnability implementation yourself, you might encounter with a problem, namely standard HTML controls in such browsers as Opera and Safari will be affected by standard controls skinning. ( In this section you can get more details on how to disable skinnability.)
In brief, to disable the skinnability mechanism of RichFaces you need to set the
"org.richfaces.LoadStyleStrategy" parameter to "NONE" in the
web.xml
file.
...
<context-param>
<param-name>org.richfaces.LoadStyleStrategy</param-name>
<param-value>NONE</param-value>
</context-param>
...
Additionally, you should include the style sheets that perform skinning of the RichFaces component and standard HTML controls.
In order to resolve the problem with extended skinning in Opera and Safari a
client script (skinning.js
) is added to the RichFaces library. The script detects
the browser type and enables extended skinning only for those browsers that fully
support it.
The script can be activated by inserting this JavaScript code to the page:
<script type="text/javascript">
window.RICH_FACES_EXTENDED_SKINNING_ON = true;
</script>
When NO script loading strategy is used and extended skinning is turned on then corresponding warning message will appears in the console.
You also need to specify "media" attribute in the <link> tag which includes the "extended_both.xcss" style sheet with "rich-extended-skinning".
This is how you can include the style sheets to the page, in case automatic skinnability implementation is disabled.
<link href='/YOUR_PROJECT_NAME/a4j_3_2_2-SNAPSHOTorg/richfaces/renderkit/html/css/basic_both.xcss/DATB/eAF7sqpgb-jyGdIAFrMEaw__.jsf' type='text/css' rel='stylesheet' class='component' />
<link media='rich-extended-skinning' href='/ YOUR_PROJECT_NAME /a4j_3_2_2-SNAPSHOTorg/richfaces/renderkit/html/css/extended_both.xcss/DATB/eAF7sqpgb-jyGdIAFrMEaw__.jsf' type='text/css' rel='stylesheet' class='component' />
<link href='/ YOUR_PROJECT_NAME /a4j_3_2_2-SNAPSHOT/org/richfaces/skin.xcss/DATB/eAF7sqpgb-jyGdIAFrMEaw__.jsf' type='text/css' rel='stylesheet' class='component' />
Now it's necessary to use a4j/versionXXX
resources prefix instead of
a4j_versionXXX
. Base64 encoder changed to use
'!
' instead of '.
'.
XCSS files are the core of RichFaces components skinnability.
XCSS is an XML formatted CSS that adds extra functionality to the skinning process. XCSS extends skinning possibilities by parsing the XCSS file that contains all look-and-feel parameters of a particular component into a standard CSS file that a web browser can recognize.
XCSS file contains CSS properties and skin parameters mappings. Mapping of a CSS selector to a skin parameter is performed using < u:selector > and < u:style> XML tags that form the mapping structure. Please study the example below.
...
<u:selector name=".rich-component-name">
<u:style name="background-color" skin="additionalBackgroundColor" />
<u:style name="border-color" skin="tableBorderColor" />
<u:style name="border-width" skin="tableBorderWidth" />
<u:style name="border-style" value="solid" />
</u:selector>
...
During processing the code in the shown example is parsed into a standard CSS format.
...
.rich-component-name {
background-color: additionalBackgroundColor; /*the value of the constant defined by your skin*/
border-color: tableBorderColor; /*the value of the constant defined by your skin*/
border-width: tableBorderWidth; /*the value of the constant defined by your skin*/
border-style: solid;
}
...
The "name" attribute of <u:selector> tag defines the CSS selector, while "name" attribute of the <u:style> tag defines what skin constant is mapped to a CSS property. The "value" attribute of the <u:style> tag can also be used to assign a value to a CSS property.
CSS selectors with identical skinning properties can be set as a comma separated list.
...
<u:selector name=".rich-ordering-control-disabled, .rich-ordering-control-top, .rich-ordering-control-bottom, .rich-ordering-control-up, .rich-ordering-control-down">
<u:style name="border-color" skin="tableBorderColor" />
</u:selector>
...
Plug-n-Skin is a feature that gives you an opportunity to easily create, customize and plug into your project a custom skin. The skin can be created basing on parameters of some predefined RichFaces skin.
The feature also provides an option to unify the appearance of rich controls with standard HTML elements.
In order to create your own skin using Plug-n-Skin feature, you can follow these step by step instructions.
First of all, you need to create a template for the new skin. Creation of the template can be performed using Maven build and deployment tool. More information on how to configure Maven for RichFaces you can find out from JBoss wiki article . You can copy and paste these Maven instructions to command line and execute them.
...
mvn archetype:create -DarchetypeGroupId=org.richfaces.cdk -DarchetypeArtifactId=maven-archetype-plug-n-skin -DarchetypeVersion=RF-VERSION -DartifactId=ARTIFACT-ID -DgroupId=GROUP-ID -Dversion=VERSION
...
Primary keys for the command:
archetypeVersion
indicates the RichFaces version. For example,
"3.3.3-SNAPSHOT"
artifactId
artifact id of the project
groupId
group id of the project
version
the version of the project you create, by default it
is "1.0.-SNAPSHOT"
After this operation, a folder with the name of your
"ARTIFACT-ID"
appears. The folder contains a template of
Maven project.
Next steps will guide you though creating of the skin itself.
In the root folder of Maven project (the one that contains "pom.xml" file) you should run the following command in the command line:
...
mvn cdk:add-skin -Dname=SKIN-NAME -Dpackage=SKIN-PACKAGE
...
Primary keys for the command:
name
defines the name of the new skin
package
base package of the skin. By default
"groupId" of the project is used.
Additional optional keys for the command:
baseSkin
defines the name of the base skin.
createExt
if set to "true", extended CSS classes are
added. For more information, please, see
"Standard controls skinning"
As a result of the performed operations the following files and folders are created:
BaseImage.java - the base class to store images. Location: "\src\main\java\SKIN-PACKAGE\SKIN-NAME\images\"
BaseImageTest.java - a test version of a class that stores images. Location: "\src\test\java\SKIN-PACKAGE\SKIN-NAME\images\"
XCSS files - XCSS files define the new look of RichFaces components affected by the new skin. Location: "\src\main\resources\SKIN-PACKAGE\SKIN-NAME\css\"
SKIN-NAME.properties - a file that contains properties of the new skin. Location: "\src\main\resources\SKIN-PACKAGE\SKIN-NAME\css\"
The following properties are used to configure the SKIN-NAME.properties file:
baseSkin – the name of the base skin to be used as basis. The look of the skin you define will be affected by new style properties.
generalStyleSheet - a path to the style sheet (SKIN-NAME.xcss) that imports style sheets of the components to be affected by the new skin.
extendedStyleSheet - a path to a style sheet that is used to unify the appearance of RichFaces components and standard HTML controls. For additional information please read "Standard controls skinning" chapter.
gradientType - a predefined property to set the type of gradient applied to the new skin. Possible values are glass, plastic, plain. More information on gradient implementation you can find further in this chapter.
SKIN-NAME.xcss - a XCSS file that imports XCSS files of the components to be affected by the new skin. Location: "src\main\resources\META-INF\skins "
XCSS files If the command is executed with the "DcreateExt" key set to "true", the XCSS (extended_classes.xcss and extended.xcss) files that define style for standard controls will be created. Location: "\src\main\resources\SKIN-PACKAGE\SKIN-NAME\css\".
SKIN-NAME-ext.xcss If the command is executed with the "DcreateExt" key set to "true", the configuration SKIN-NAME-ext.xcss file that imports XCSS file defining styles for the standard controls will be created. Location: "src\main\resources\META-INF\skins ".
SKIN-NAME-resources.xml - the file contains the description of all listed above files. Location: "src\main\config\resources ".
Now you can start editing the XCSS files located in "\src\main\resources\SKIN-PACKAGE\SKIN-NAME\css\". New style properties can be assigned to the selectors (the selectors listed in the XCSS files) in two ways, which are both valid, and it'up to you what way to choose.
Standard CSS coding approach, i.e. you can add CSS properties
to the given selectors. The only
thing, you have to keep in mind is that the selectors must be inside
<f:verbatim> <![CDATA[ ...]]>
</f:verbatim>
tags.
For example
...
.rich-calendar-cell {
background: #537df8;
}
...
Using XCSS coding approach, the same way as XCSS files are normally
formed in RichFaces. The XCSS tags have to be placed outside
<f:verbatim> <![CDATA[ ...]]>
</f:verbatim>
tags.
...
<u:selector name=".rich-calendar-cell">
<u:style name="border-bottom-color" skin="panelBorderColor"/>
<u:style name="border-right-color" skin="panelBorderColor"/>
<u:style name="background-color" skin="tableBackgroundColor"/>
<u:style name="font-size" skin="generalSizeFont"/>
<u:style name="font-family" skin="generalFamilyFont"/>
</u:selector>
...
Having performed described above steps and edited the XCSS files you can proceed to building the new skin and to plugging it into the project. Building the new skin can be done by executing the given below command in the command line in the root folder of you skin project (the one that contains pom.xml file).
...
mvn clean install
...
In addition Plug-n-Skin has a number of predefined gradients that you can also use to make your application look nicer. The given below code snippet shows how a gradient can be used
...
<u:selector name=".rich-combobox-item-selected">
<u:style name="border-width" value="1px" />
<u:style name="border-style" value="solid" />
<u:style name="border-color" skin="newBorder" />
<u:style name="background-position" value="0% 50%" />
<u:style name="background-image">
<f:resource f:key="org.richfaces.renderkit.html.CustomizeableGradient">
<f:attribute name="valign" value="middle" />
<f:attribute name="gradientHeight" value="17px" />
<f:attribute name="baseColor" skin="headerBackgroundColor" />
</f:resource>
</u:style>
</u:selector>
...
So, as you can see, the background-image CSS property is
defined with <f:resource
f:key="org.richfaces.renderkit.html.CustomizeableGradient">
that sets the gradient. While the gradient type can be specified in the
SKIN-NAME.properties file with gradientType property. The gradientType
property can be set to one of the possible values glass, plastic, plain. The
gradient in it's turn can be can be adjusted using baseColor, gradientColor,
gradientHeight, valign attributes. Their usage is shown in the snippet above.
Now, you can use your newly-created and customized skin in your project by adding your new skin parameters to web.xml file and placing the jar file with your skin ( the jar file is located in "target" folder of your skin project) to "\WebContent\WEB-INF\lib\".
...
<context-param>
<param-name>org.ajax4jsf.SKIN</param-name>
<param-value>SKIN-NAME</param-value>
</context-param>
...
This section will cover some practical aspects of Plug-n-Skin implementation. It's assumed that you have read the section of the guide that tells how the new skin using Plug-n-Skin prototype can be created.
Above all, we need to create a new skin, in order to do that we just have to follow the steps described in the previous section.
This command will be used to create a template of the new skin project.
mvn archetype:create -DarchetypeGroupId=org.richfaces.cdk -DarchetypeArtifactId=maven-archetype-plug-n-skin -DarchetypeVersion=3.3.3-SNAPSHOT -DartifactId=P-n-S -DgroupId=GROUPID -Dversion=1.0.-SNAPSHOT
Now you can browse the "P-n-S" folder to view what files and folders were created there.
Next, we will use Maven to add all needed files to the skin project. This will done by the following command:
mvn cdk:add-skin -DbaseSkin=blueSky -DcreateExt=true -Dname=PlugnSkinDemo -Dpackage=SKINPACKAGE
As you remember from the previous section "-DbaseSkin" key defines what RichFaces built-in skin to be used as a base one, "-DcreateExt=true" determines that the new skin will come with XCSS files that unify the look of the rich components with standard HTML controls.
So, now the files and folder with all needed resources are created and redefining/editing the new skin can be started.
Now we can start editing XCSS files of the rich components. In order to see how the Plug-n-Skin feature works we will change some style attributes of <rich:calendar> and some basic HTML controls to see how they are affected by standard controls skinning.
Thus, it will be demonstrated how to:
Recolor the current day's cell background of the <rich:calendar> to see how the new skin created with the help of Plug-n-Skin feature affects the style of the component;
Recolor a standard HTML submit button;
In oder to edit the style properties of
<rich:calendar>
you need to open the "calendar.xcss" file located in
"P-n-S\src\main\resources\skinpackage\plugnskindemo\css\". Once, you
have opened the file, please find ".rich-calendar-today" selector and amend it
as follows: background-color: #075ad1;
. The current day's
background color can be considered recolored.
Now we will see how font style of a standard HTML submit button can be
changed. Please, open "extended.xcss" file located in
"P-n-S\src\main\resources\skinpackage\plugnskindemo\css\" and put in
font-weight: bold;
inside the curly braces of these coma
separated selectors button[type="button"],
button[type="reset"], button[type="submit"],
input[type="reset"], input[type="submit"],
input[type="button"]
. So, the CSS code should look like
this.
button[type="button"], button[type="reset"], button[type="submit"], input[type="reset"], input[type="submit"], input[type="button"] { font-weight: bold;
}
All the changes that were planned to be preformed are done and now you can
proceed to building the new PlugnSkinDemo skin and import it into the project.
As you read in the previous section, the skin should be built in the
"P-n-S" folder of the skin project by executing mvn clean
install
command. This procedure results in creating a
"target" folder that contains a .jar file with a compiled new skin, it
our case the file is named "P-n-S-1.0.-SNAPSHOT.jar". The next step is
to import the new PlugnSkinDemo skin into the project.
What you need to do, in order to have the new skin imported to the project is to
Copy the "P-n-S-1.0.-SNAPSHOT.jar" file to the "\WebContent\WEB-INF\lib\" folder.
Add the new skin's name to the "web.xml" file. It is done like this
<context-param>
<param-name>org.ajax4jsf.SKIN</param-name>
<param-value>PlugnSkinDemo</param-value>
</context-param>
Please, do not forget that standard controls skinning has to be enabled in the "web.xml" file, which can be done by adding the following code to the "web.xml" file:
<context-param>
<param-name>org.richfaces.CONTROL_SKINNING</param-name>
<param-value>enable</param-value>
</context-param>
The result of both operations is displayed on the figure below.
In the "Reference Data" section for most of the visual components (see "The RichFaces Components" chapter)
there are the tables with rich-*
classes definitions. These classes allow to redefine styles for a specific component by means of CSS.
Actually, you should create classes with the same names and define new properties in them.
Let's consider the <rich:modalPanel> component.
To change the background color for the mask, it's enough to redefine the .rich-mpnl-mask-div
class.
Example:
...
.rich-mpnl-mask-div{
background-color:#fae6b0;
}
...
This is a result:
If you have multiple components on the page, the redefined styles will be applied to all of them. To change styles for a particular component on the page, create your own style classes and use them in corresponding style class attributes. An example on how to change the font style for the header of a particular modal panel is placed below:
Example:
...
.myClass{
font-style:italic;
}
...
Next specify myClass as the value of the "headerClass" attribute for <rich:modalPanel> :
<rich:modalPanel ... headerClass="myClass"/>
This is a result:
JSF has an advanced navigation mechanism that allows you to define navigation from view to view. Navigation happens in a Web Application when a user tries to switch from one page to another page either by clicking a button, a hyperlink, or another command component. But there is no switch mechanism between some logical states of the same view. For example in Login/Register dialog an existing user signs in with his user name and password, but if a new user registers an additional field "Confirm" is displayed, buttons labels and methods are changed when the user clicks "To register" link:
RichFaces State API allows easily to define some set of states for the pages and any properties for this states.
Actually States is a map where the entry key is a name of the State and the value is a State map. Particular State map has entries with some names as keys and any objects as values that are used after the state activation. Thus, in the State map you could define any values, method bindings, or just some simple state variables (constants) which have different values for every State.
One of the most convenience features of the RichFaces State API is a navigation between states. The RichFaces State API implements states change as the standard JSF navigation. Action component just returns outcome and the RichFaces State API extension for the JSF navigation handler checks whether this outcome is registered as a state change outcome or not. If the state change outcome is found the corresponding state is activated. Otherwise the standard navigation handling is called.
In order to use RichFaces State API you should follow the next steps:
Register State Manager EL resolver and navigation handler in the faces-config.xml:
...
<application>
<navigation-handler>org.richfaces.ui.application.StateNavigationHandler</navigation-handler>
<el-resolver>org.richfaces.el.StateELResolver</el-resolver>
</application>
...
Register an additional application factory in the faces-config.xml:
...
<factory>
<application-factory>org.richfaces.ui.application.StateApplicationFactory</application-factory>
</factory>
...
Register two managed beans in the faces-config.xml:
...
<managed-bean>
<managed-bean-name>state</managed-bean-name>
<managed-bean-class>org.richfaces.ui.model.States</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>states</property-name>
<property-class>org.richfaces.ui.model.States</property-class>
<value>#{config.states}</value>
</managed-property>
</managed-bean>
<managed-bean>
<managed-bean-name>config</managed-bean-name>
<managed-bean-class>org.richfaces.demo.stateApi.Config</managed-bean-class>
<managed-bean-scope>none</managed-bean-scope>
</managed-bean>
...
One bean ("config") defines and stores states as it is shown in the following example:
...
public class Config {
/**
* @return States
*/
public States getStates() {
FacesContext facesContext = FacesContext.getCurrentInstance();
States states = new States();
// Registering new User State definition
states.setCurrentState("register"); // Name of the new state
// Text labels, properties and Labels for controls in "register" state
states.put("showConfirm", Boolean.TRUE); // confirm field rendering
states.put("link", "(To login)"); // Switch State link label
states.put("okBtn", "Register"); // Login/Register button label
states.put("stateTitle", "Register New User"); // Panel title
ExpressionFactory expressionFactory = facesContext.getApplication()
.getExpressionFactory();
// Define "registerbean" available under "bean" EL binding on the page
ValueExpression beanExpression = expressionFactory
.createValueExpression(facesContext.getELContext(),
"#{registerbean}", Bean.class);
states.put("bean", beanExpression);
// Define "registeraction" available under "action" EL binding on the
// page
beanExpression = expressionFactory.createValueExpression(facesContext
.getELContext(), "#{registeraction}", RegisterAction.class);
states.put("action", beanExpression);
// Define method expression inside registeraction binding for this state
MethodExpression methodExpression = expressionFactory.createMethodExpression(
facesContext.getELContext(), "#{registeraction.ok}",
String.class, new Class[] {});
states.put("ok", methodExpression);
// Outcome for switching to login state definition
states.setNavigation("switch", "login");
// Login Existent User State analogous definition
states.setCurrentState("login");
states.put("showConfirm", Boolean.FALSE);
states.put("link", "(To register)");
states.put("okBtn", "Login");
states.put("stateTitle", "Login Existing User");
beanExpression = expressionFactory.createValueExpression(facesContext
.getELContext(), "#{loginbean}", Bean.class);
states.put("bean", beanExpression);
beanExpression = expressionFactory.createValueExpression(facesContext
.getELContext(), "#{loginaction}", LoginAction.class);
states.put("action", beanExpression);
methodExpression = expressionFactory.createMethodExpression(
facesContext.getELContext(), "#{loginaction.ok}",
String.class, new Class[] {});
states.put("ok", methodExpression);
states.setNavigation("switch", "register");
return states;
}
}
...
The other bean ("state") with the type
org.richfaces.ui.model.States
has the "states"
managed property that is bound to the "config" bean which defines
states.
Use state bindings on the page. See the following example:
...
<h:panelGrid columns="3">
<h:outputText value="username" />
<h:inputText value="#{state.bean.name}" id="name" required="true" />
<h:outputText value="password" />
<h:inputSecret value="#{state.bean.password}" id="password" required="true" />
<h:outputText value="confirm" rendered="#{state.showConfirm}" />
<h:inputSecret value="#{state.bean.confirmPassword}" rendered="#{state.showConfirm}" id="confirm" required="true" />
</h:panelGrid>
<a4j:commandButton actionListener="#{state.action.listener}" action="#{state.ok}" value="#{state.okBtn}" id="action"/>
...
To get full Login/Register dialog example, please, have a look at RichFaces Live Demo.
RichFaces provides a function to check whether the logged-in user belongs to a certain user role. The function is rich:isUserInRole(Object)
, it takes a String, a comma-separated list String, Collection etc. as arguments and returns a boolean value.
For example, you need to render some controls only for administrators.
To do this you need to create a role "admin" in web.xml and implement authorisation that assigns the "admin" role to the user that loggged-in as an administrator. Afterwards, you can use the rich:isUserInRole(Object)
function with the "rendered" attribute of any component.
Example:
...
<rich:editor value="#{bean.text}" rendered="#{rich:isUserInRole('admin')}" />
...
In the example above only a logged-in user with the role "admin" can see the text editor while for the user with other roles the component will not be rendered.
The library encompasses ready-made components built based on the Rich Faces CDK.
The component in this section lets you easily add Ajax capabilities to other components as well as manage Ajax requests.
The <a4j:ajaxListener> component adds an action listener to a parent component and works like the <f:actionListener> or <f:valueChangeListener> JSF components but for the whole Ajax container.
The <a4j:ajaxListener> component adds an action listener to a parent component. That listener is invoked on each Ajax request during the "Render Response" JSF phase. In comparison with standard JSF <f:actionListener> and <f:valueChangeListener> components the invocation of the <a4j:ajaxListener> is not skipped in case when validation of "Update Model" fails. The <a4j:ajaxListener> is guarantied to be invoked for each Ajax response.
The
"type"
attribute defines the fully qualified Java class name for the listener.
This Java class should implement
org.ajax4jsf.event.AjaxListener
interface which is base interface for all listeners, capable for receiving Ajax events.
The object on which the Event initially occurred could be accessed using the
java.util.EventObject.getSource()
method.
The <a4j:ajaxListener> is not invoked for non-Ajax requests and when RichFaces works in the "Ajax Request generates Non-Ajax Response" mode, so <a4j:ajaxListener> invocation is a good indicator that Ajax Response is going to be processed. Let's check it in the following example.
Example:
...
<rich:messages/>
<h:form id="form">
<a4j:commandLink value="Click to send Ajax request">
<a4j:ajaxListener type="org.docs.richfaces.actionListenerBean"/>
</a4j:commandLink>
</h:form>
...
Example:
...
public class ActionListenerBean implements org.ajax4jsf.event.AjaxListener {
public void processAjax(AjaxEvent event) {
FacesContext.getCurrentInstance().addMessage("form", new FacesMessage("Ajax request is sent"));
}
}
...
There is a result:
Table of <a4j:ajaxListener> attributes.
Table 6.1. Component Identification Parameters
Name | Value |
---|---|
listener-class | org.ajax4jsf.event.AjaxListener |
event-class | org.ajax4jsf.event.AjaxEvent |
tag-class | org.ajax4jsf.taglib.html.jsp.AjaxListenerTag |
Visit AjaxListener page at RichFaces Livedemo for examples of component usage and their sources.
Check Sun JSF TLD documentation for more information on <f:valueChangeListener> tag.
The <a4j:actionparam> component combines the functionality of <f:param> and <f:actionListener> and allows to assign the value to the property of the managed bean directly using the "assignTo" attribute.
The <a4j:actionparam> component has 3 main attributes:
"name" defines a name of this parameter
"value" defines initial value of this parameter or a value binding
"assignTo"
defines updatable bean property. This property will be updated if the parent
command component performs an actionEvent. The update occurs in the same phase as the actionEvent is processed (INVOKE_APPLICATION
, PROCESS_VALIDATIONS
, or APPLY_REQUEST_VALUES
, depending on the values of the
"immediate"
and
"bypassUpdates"
attributes).
Example:
...
<h:form id="form">
<a4j:commandButton value="Set Name to Alex" reRender="rep">
<a4j:actionparam name="username" value="Alex" assignTo="#{actionparamBean.name}"/>
</a4j:commandButton>
<br/>
<h:outputText id="rep" value="Name: #{actionparamBean.name}"/>
</h:form>
...
There is a managed bean:
...
public class ActionparamBean {
private String name = "John";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
...
You can use <a4j:actionparam> not only with Ajax components, but with non-ajax command component also. This feature allows to update model values without invoking even a single line of Java code on the server side. The usage of this feature you can find at ActionParameter Usage page of RichFaces LiveDemo.
If you need to convert the value before the "Update Model" phase you can specify the converter in the "converter" attribute.
The property is assigned with a parameter value on the "Update Model" phase. Therefore if the validation of the form is failed, this phase will be skipped and the property won't be updated.
It is possible to use JavaScript expression or function in the "value" attribute. In this case the "noEscape" attribute should be set to "true". The result of this JavaScript invocation is sent to the server as a value of <a4j:actionparam> .
Table of <a4j:actionparam> attributes.
Table 6.2. Component Identification Parameters
Name | Value |
---|---|
component-type | org.ajax4jsf.ActionParameter |
component-class | org.ajax4jsf.component.html.HtmlActionParameter |
Visit the ActionParameter page at RichFaces LiveDemo for examples of component usage and their sources.
More information can be found on the Ajax4jsf Users Forum.
More information about <f:param> and <f:actionListener> can be found in Sun JSF TLD documentation.
The <a4j:form> component enhances functionality of the standard JSF <h:form> component with possibility of default Ajax submission and fixes the problem with <h:commandLink> generation inside the form.
Along with a4j:htmlCommandLink , <a4j:form> component fixes the problem of <h:commandLink> component that cannot be re-rendered without re-rendering the whole form it belongs to. For the further details see the Ajax Form Usage page at RichFaces Livedemo.
The <a4j:form> component adds extra functionality to non-Ajax action/command components: submission is performed via Ajax when "ajaxSubmit" attribute set to "true".
If the <a4j:form> component works in an Ajax mode, the standard Ajax attributes such as "reRender" , "limitToList" , "requestDelay" , etc. can be used.
Example:
...
<a4j:form ajaxSubmit="true" reRender="name">
<h:panelGrid>
<h:commandButton value="Set Local Name to John (Ajax)" action="#{userBean.nameItJohn}" />
<h:outputText id="name" value="Name:#{userBean.name}" />
</h:panelGrid>
</a4j:form>
...
Here is a managed bean:
...
public class UserBean {
private String name="";
public String nameItJohn() {
setName("John");
return null;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
...
In the example above the
ajaxSubmit="true"
,
so all standard action components on this form become ajaxable.
The
"reRender"
attribute contains an Id of component for
re-rendering after an Ajax response.
If you have <h:commandButton> or <h:commandLink> inside a form, they work as <a4j:commandButton> .
You should not use
<a4j:form>
component with
ajaxSubmit="true"
if it contains other Ajax command components.
Also, due to the security reason, file upload form element cannot be convertible to the be ajaxable.
Table of <a4j:form> attributes.
Table 6.3. Component Identification Parameters
Name | Value |
---|---|
component-type | org.ajax4jsf.Form |
component-family | javax.faces.Form |
component-class | org.ajax4jsf.component.html.AjaxForm |
renderer-type | org.ajax4jsf.FormRenderer |
Visit Ajax Form page at RichFaces Livedemo for examples of component usage and their sources.
For additional information about attributes of this component read 'Ajax Attribute section.
The <a4j:region> component specifies the part of the component tree to be processed on server. If no <a4j:region> is defined the whole View functions as a region.
The <a4j:region> component specifies the part of the component tree to be processed on server. The processing includes data handling during decoding, conversion, validation and model update. Note that the whole Form is still submitted but only part taken into region will be processed.
Example:
<h:form>
...
<a4j:region>
<a4j:commandLink/>
</a4j:region>
...
<h:form>
The whole Form on the schematic listing above will be submitted by request invoked with the <a4j:commandLink> . The only part that is going to be processed on the server is enclosed with <a4j:region> and </a4j:region> tags. If no <a4j:region> is defined the whole View functions as a region.
The regions could be nested. Server picks out and decodes only the region, which contains the component that initiates the request.
Example:
<h:form>
...
<a4j:region>
<a4j:commandLink value="Link 1" id="link1"/>
<a4j:region>
<a4j:commandLink value="Link 2" id="link2"/>
</a4j:region >
</a4j:region>
...
<h:form>
The external region is decoded for link1
and the internal one is decoded for link2
.
The "renderRegionOnly" attribute is used when it is necessary to exclude all the components from the outside of the region from updating on the page during Renderer Response phase. Such manipulation allows region to be passed straight into Encode and reduces performance time. This optimization should be implemented carefully because it doesn't allow data from the outside of active region to be updated.
Example:
<h:form>
...
<a4j:region renderRegionOnly="true">
<a4j:commandLink value="Link 1" id="link1"/>
</a4j:region>
...
<a4j:region renderRegionOnly="false">
<a4j:commandLink value="Link 2" id="link2"/>
</a4j:region>
...
</h:form>
On the example above the first region only will be updated if link1
initiates a request.
When a request is initiated by link2
both regions will be updated.
In this case search for components to include them into Renderer Response will be performed on the whole component tree.
RichFaces allows setting Ajax responses rendering basing on component tree nodes directly, without referring to the JSP (XHTML) code. This speeds up a response output considerably and could be done by setting the <a4j:region> "selfRendered" attribute to "true". However, this rapid processing could cause missing of transient components that present on view and don't come into a component tree as well as omitting of <a4j:outputPanel> usage described below.
Example:
<a4j:region selfRendered ="true">
<a4j:commandLink value="Link" id="link"/>
<!--Some HTML content-->
</a4j:region>
In this case the processing is quicker and going on without referring to the page code. The HTML code is not saved in a component tree and could be lost. Thus, such optimization should be performed carefully and additional RichFaces components usage (e.g. <a4j:outputPanel> ) is required.
Starting from RichFaces 3.2.0 the <a4j:region> can be used together with iterative components (e.g. <rich:column> or <rich:scrollableDataTable> , etc.). It became possible to re-render a particular row in a table without updating the whole table and without any additional listeners.
Example:
<rich:column>
<a4j:region>
<a4j:commandLink reRender="out"/>
</a4j:region>
</rich:column>
<rich:column>
<h:outputText id="out">
</rich:column>
In most cases there is no need to use the
<a4j:region>
as ViewRoot
is a default one.
Table of <a4j:region> attributes.
Table 6.4. Component Identification Parameters
Name | Value |
---|---|
component-type | org.ajax4jsf.AjaxRegion |
component-family | org.ajax4jsf.AjaxRegion |
component-class | org.ajax4jsf.component.html.HtmlAjaxRegion |
renderer-type | org.ajax4jsf.components.AjaxRegionRenderer |
Visit <a4j:region> demo page at RichFaces live demo for examples of component usage and their sources.
Useful articles and examples:
<a4j:region> and two <h:inputTexts> in RichFaces cookbook at JBoss portal;
"A sad story about UIInput" at personal blog of I.Shabalov and exhaustive example of solving the problem with the help of <a4j:region> .
The <a4j:support> component is the most important core component in the RichFaces library. It enriches any existing non-Ajax JSF or RichFaces component with Ajax capability. All other RichFaces Ajax components are based on the same principles <a4j:support> has.
The <a4j:support> component has two key attributes:
mandatory "event" attribute that defines the JavaScript event the Ajax support will be attached to
"reRender" attribute that defines id(s) of JSF component(s) that should be rerendered after an Ajax request
As mentioned above, the <a4j:support> component adds Ajax capability to non-Ajax JSF components. Let's create ajaxed <h:selectOneMenu> called "Planets and Their Moons".
We begin with the common behavior description. When a page is rendered you see only one select box with the list of planets. When you select a planet the <h:dataTable> containing moons of the selected planet appears.
In other words we need <h:selectOneMenu> with the nested <a4j:support> component that is attached to the onchange event.
When an Ajax response comes back the <h:dataTable> is re-rendered on the server side and updated on the client.
...
<h:form id="planetsForm">
<h:outputLabel value="Select the planet:" for="planets" />
<h:selectOneMenu id="planets" value="#{planetsMoons.currentPlanet}" valueChangeListener="#{planetsMoons.planetChanged}">
<f:selectItems value="#{planetsMoons.planetsList}" />
<a4j:support event="onchange" reRender="moons" />
</h:selectOneMenu>
<h:dataTable id="moons" value="#{planetsMoons.moonsList}" var="item">
<h:column>
<h:outputText value="#{item}"/>
</h:column>
</h:dataTable>
</h:form>
...
Finally we need a backing bean:
...
public class PlanetsMoons {
private String currentPlanet="";
public List<SelectItem> planetsList = new ArrayList<SelectItem>();
public List<String> moonsList = new ArrayList<String>();
private static final String [] EARTH = {"The Moon"};
private static final String [] MARS = {"Deimos", "Phobos"};
private static final String [] JUPITER = {"Europa", "Gamymede", "Callisto"};
public PlanetsMoons() {
SelectItem item = new SelectItem("earth", "Earth");
planetsList.add(item);
item = new SelectItem("mars", "Mars");
planetsList.add(item);
item = new SelectItem("jupiter", "Jupiter");
planetsList.add(item);
}
public void planetChanged(ValueChangeEvent event){
moonsList.clear();
String[] currentItems;
if (((String)event.getNewValue()).equals("earth")) {
currentItems = EARTH;
}else if(((String)event.getNewValue()).equals("mars")){
currentItems = MARS;
}else{
currentItems = JUPITER;
}
for (int i = 0; i < currentItems.length; i++) {
moonsList.add(currentItems[i]);
}
}
//Getters and Setters
...
}
There are two properties planetsList
and moonsList
.
The planetsList
is filled with planets names in the constructor.
After you select the planet,
the planetChanged()
listener is called and
the moonsList
is populated with proper values of moons.
With the help of "onsubmit" and "oncomplete" attributes the <a4j:support> component allows to use JavaScript calls before and after an Ajax request respectively. Actually the JavaScript specified in the "oncomplete" attribute will be executed in any case whether the Ajax request is completed successfully or not.
You can easily add confirmation dialog for the planet select box and colorize <h:dataTable> after the Ajax response:
...
<h:form id="planetsForm">
<h:outputLabel value="Select the planet:" for="planets" />
<h:selectOneMenu id="planets" value="#{planetsMoons.currentPlanet}" valueChangeListener="#{planetsMoons.planetChanged}">
<f:selectItems value="#{planetsMoons.planetsList}" />
<a4j:support event="onchange" reRender="moons"
onsubmit="if(!confirm('Are you sure to change the planet?')) {form.reset(); return false;}"
oncomplete="document.getElementById('planetsForm:moonsPanel').style.backgroundColor='#c8dcf9';" />
</h:selectOneMenu>
<h:dataTable id="moons" value="#{planetsMoons.moonsList}" var="item">
<h:column>
<h:outputText value="#{item}"/>
</h:column>
</h:dataTable>
</h:form>
...
There is the result:
Information about the "process" attribute usage you can find in the " Decide what to process " guide section.
The <a4j:support> component created on a page as following
<h:inputText value="#{bean.text}">
<a4j:support event="onkeyup" reRender="output" action="#{bean.action}"/>
</h:inputText>
is decoded in HTML as
<input onkeyup="A4J.AJAX.Submit( Some request parameters )"/>
Table of <a4j:support> attributes.
Table 6.5. Component Identification Parameters
Name | Value |
---|---|
component-type | org.ajax4jsf.Support |
component-family | org.ajax4jsf.AjaxSupport |
component-class | org.ajax4jsf.component.html.HtmlAjaxSupport |
renderer-type | org.ajax4jsf.components.AjaxSupportRenderer |
Visit <a4j:support> demo page at RichFaces live demo for examples of component usage and their sources.
The <a4j:commandButton> component is very similar to JSF <h:commandButton> , the only difference is that an Ajax form submit is generated on a click and it allows dynamic rerendering after a response comes back.
The <a4j:commandButton> component is used in the same way as JSF <h:commandButton> . The difference is that in case of <a4j:commandButton> the components to be updated should be specified.
The example above generates the following HTML code:
<input type="submit" onclick="A4J.AJAX.Submit(request parameters);return false;" value="Button"/>
Сlicking the generated anchor fires the utility method A4J.AJAX.Submit()
that perfroms Ajax request.
The <a4j:commandButton> already has Ajax support built-in and there is no need to add <a4j:support> .
The usage of the keyword 'this'
in JavaScript code in the value for
"oncomplete"
attribute depends on the location of
<a4j:commandButton>
.
If the
<a4j:commandButton>
is situated outside the re-rendered region it is possible to use keyword 'this' as in the following example:
<h:form>
<a4j:commandButton action="director.rollCamera" onclick="this.disabled=true" oncomplete="this.disabled=false" />
</h:form>
Otherwise, if the
<a4j:commandButton>
is contained in a re-rendered region
than the
"oncomplete"
attribute has a problem with obtaining a reference of the
commandButton object when using the keyword 'this'
.
In this case use the
"oncomplete"
attribute as in the following example:
<h:form id="form">
<a4j:commandButton id="cbutton" action="director.rollCamera" onclick="this.disabled=true" oncomplete="document.getElementById('form:cbutton').disabled=false" />
</h:form>
Common JSF navigation could be performed after an Ajax submit and partial rendering, but Navigation Case must be defined as <redirect/> in order to avoid problems with some browsers.
As any Core Ajax component that sends Ajax requests and processes server responses the <a4j:commandButton> has all attributes that provide the required behavior of requests (delay, limitation of submit area and rendering, etc.)
When attaching a JavaScript API function to the
<a4j:commandButton>
with the help of the
<rich:componentControl>
do not use the
"attachTo"
attribute of the last one.
The attribute adds event handlers using Event.observe
but
<a4j:commandButton>
has no such event.
The example below will not work:
<a4j:commandButton value="Show Current Selection" reRender="table" action="#{dataTableScrollerBean.takeSelection}" id="button">
<rich:componentControl attachTo="button" for="panel" event="oncomplete" operation="show" />
</a4j:commandButton>
This one should work properly:
<a4j:commandButton value="Show Current Selection" reRender="table" action="#{dataTableScrollerBean.takeSelection}" id="button">
<rich:componentControl for="panel" event="oncomplete" operation="show" />
</a4j:commandButton>
Information about the "process" attribute usage you can find in the "Decide what to process" guide section.
Table of <a4j:commandButton> attributes.
Table 6.6. Component Identification Parameters
Name | Value |
---|---|
component-type | org.ajax4jsf.CommandButton |
component-family | javax.faces.Command |
component-class | org.ajax4jsf.component.html.HtmlAjaxCommandButton |
renderer-type | org.ajax4jsf.components.AjaxCommandButtonRenderer |
Visit CommandButton demo page at RichFaces live demo for examples of component usage and their sources.
The <a4j:commandLink> component is very similar to the <h:commandLink> component, the only difference is that an Ajax form submit is generated on a click and it allows dynamic rerendering after a response comes back. It's not necessary to plug any support into the component, as Ajax support is already built in.
The <a4j:commandLink> component is used in the same way as JSF <h:commandLink> . The difference is that in case of <a4j:commandLink> the components to be updated should be specified. In this chapter we will use the code from RichFaces Greeter and change there <a4j:commandButton> to <a4j:commandLink> :
...
<a4j:commandLink value="Get greeting" reRender="greeting" />
...
It's not necessary to add nested <a4j:support> as the <a4j:commandLink> has an Ajax support already built-in. As a result of our changes we will get a form with "Get greeting" link instead of the button:
The example above generates the following HTML code:
<a href="#" onclick="A4J.AJAX.Submit(?"request parameters"); return false;"><span>Get greeting</span></a>
If you click on the generated anchor the utility method A4J.AJAX.Submit()
will be fired.
Common JSF navigation could be performed after Ajax submit and partial rendering, but Navigation Case must be defined as <redirect/> in order to avoid problems with some browsers.
As any Core Ajax component that sends Ajax requests and processes server responses the <a4j:commandLink> has all attributes that provide the required behavior of requests (delay, limitation of submit area and rendering, etc.)
Information about the "process" attribute usage you can find "Decide what to process" guide section.
Table of <a4j:commandLink> attributes.
Table 6.7. Component Identification Parameters
Name | Value |
---|---|
component-type | org.ajax4jsf.CommandLink |
component-family | javax.faces.Command |
component-class | org.ajax4jsf.component.html.HtmlAjaxCommandLink |
renderer-type | org.ajax4jsf.components.AjaxCommandLinkRenderer |
Visit CommandLink demo page at RichFaces live demo for examples of component usage and their sources.
Useful articles:
How to use "window.confirm" JavaScript with <a4j:commandLink> "onclick" attribute in RichFaces cookbook at JBoss portal.
The <a4j:jsFunction> component allows to perform Ajax requests directly from JavaScript code, invoke server-side data and return it in a JSON format to use in a client JavaScript calls.
As the component uses Ajax request to get data from server it has all common Ajax Action attributes. Hence, "action" and "actionListener" can be invoked, and reRendering some parts of the page fired after calling function.
When using the <a4j:jsFunction> it's possible to initiate the Ajax request from the JavaScript and perform partial update of a page and/or invoke the JavaScript function with data returned by Ajax response.
...
<body onload="callScript()">
<h:form>
...
<a4j:jsFunction name="callScript" data="#{bean.someProperty1}" reRender="someComponent" oncomplete="myScript(data.subProperty1, data.subProperty2)">
<a4j:actionparam name="param_name" assignTo="#{bean.someProperty2}"/>
</a4j:jsFunction>
...
</h:form>
...
</body>
...
The <a4j:jsFunction> allows to use <a4j:actionparam> or pure <f:param> for passing any number of parameters of the JavaScript function into Ajax request. <a4j:jsFunction> is similar to <a4j:commandButton> , but it could be activated from the JavaScript code. It allows to invoke some server-side functionality and use the returned data in the JavaScript function invoked from "oncomplete" attribute. Hence it's possible to use <a4j:jsFunction> instead of <a4j:commandButton> . You can put it anywhere, just don't forget to use <h:form> and </h:form> around it.
Information about the "process" attribute usage you can find "Decide what to process" guide section.
Table of <a4j:jsFunction> attributes.
Table 6.8. Component Identification Parameters
Name | Value |
---|---|
component-type | org.ajax4jsf.Function |
component-family | org.ajax4jsf.components.ajaxFunction |
component-class | org.ajax4jsf.component.html.HtmlajaxFunction |
renderer-type | org.ajax4jsf.components.ajaxFunctionRenderer |
Visit the jsFunction page at RichFaces LiveDemo for component usage and sources for the given examples.
Useful articles:
"JsFunctionJson" article in the RichFaces Cookbook describes how to use "a4j:jsFunction" to call the jsonTest backing bean that generates some random data in a JSON String;
The <a4j:poll> component allows periodical sending of Ajax requests to a server and is used for a page updating according to a specified time interval.
The <a4j:poll> componet is used for periodical polling of server data. In order to use the component it's necessary to set an update interval. The "interval" attribute defines an interval in milliseconds between the previous response and the next request. The total period beetween two requests generated by the <a4j:poll> component is a sum of an "interval" attribute value and server response time. Default value for "interval" attribute is set to "1000" milliseconds (1 second). See an example of definition in the "Creating the component with a Page Tag" section.
The "timeout" attribute defines response waiting time in milliseconds. If a response isn't received during this period a connection is aborted and the next request is sent. Default value for "timeout" attribute isn't set.
The "enabled" attribute defines should the <a4j:poll> send request or not. It's necessary to render the <a4j:poll> to apply the current value of "enabled" attribute. You can use an EL-expression for "enabled" attribute to point to a bean property. An example of usage of mentioned above attributes is placed below:
Example:
...
<a4j:region>
<h:form>
<a4j:poll id="poll" interval="1000" enabled="#{userBean.pollEnabled}" reRender="poll,grid"/>
</h:form>
</a4j:region>
<h:form>
<h:panelGrid columns="2" width="80%" id="grid">
<h:panelGrid columns="1">
<h:outputText value="Polling Inactive" rendered="#{not userBean.pollEnabled}" />
<h:outputText value="Polling Active" rendered="#{userBean.pollEnabled}" />
<a4j:commandButton style="width:120px" id="control" value="#{userBean.pollEnabled?'Stop':'Start'} Polling" reRender="poll, grid">
<a4j:actionparam name="polling" value="#{!userBean.pollEnabled}" assignTo="#{userBean.pollEnabled}"/>
</a4j:commandButton>
</h:panelGrid>
<h:outputText id="serverDate" style="font-size:16px" value="Server Date: #{userBean.date}"/>
</h:panelGrid>
</h:form>
...
The example shows how date and time are updated on a page in compliance with data taken from a server.
The
<a4j:poll>
componet sends requests to the server every second.
"reRender"
attribute of the
<a4j:poll>
contains poll's own Id
.
Hence, it is self rendered for applying the current value of
"enabled"
attribute.
The form around the <a4j:poll> component is required.
To make the
<a4j:poll>
component send requests periodically when it limitToList
is set to "true",
pass the
<a4j:poll>
ID to it reRender
attribute.
Information about the "process" attribute usage you can find "Decide what to process" guide section.
Table of <a4j:poll> attributes.
Table 6.9. Component Identification Parameters
Name | Value |
---|---|
component-type | org.ajax4jsf.Poll |
component-family | org.ajax4jsf.components.AjaxPoll |
component-class | org.ajax4jsf.component.html.AjaxPoll |
renderer-type | org.ajax4jsf.components.AjaxPollRenderer |
Visit the Poll page at RichFaces LiveDemo for examples of the component usage and their sources.
Useful examples and articles:
"Create a Banner Using Effects and Poll" article at RichFaces Wiki gives an example of how to create an image banner using <rich:effect> and <a4j:poll> components;
"Create an HTML Banner Using Effects and Poll" article at RichFaces Wiki brings the code of the way of creating an HTML banner banner using <rich:effect> and <a4j:poll> components;
"RichFaces and Slideshow" thread in the RichFaces users forum contains an information and code on making a Slide Show with the help of the <a4j:poll> component;
Manage the RichFaces Users Forum for fresh issues about the component usage.
The <a4j:push> periodically perform Ajax request to server, to simulate 'push' data.
The main difference between
<a4j:push>
and
<a4j:poll>
components is that
<a4j:push>
makes request to minimal code only (not to JSF tree) in order to check the presence of messages in the queue.
If the message exists the complete request is performed. The component doesn't poll registered beans
but registers EventListener
which receives messages about events.
The <a4j:push> implements reverse Ajax technique.
The bean, for example, could be subscribed to Java Messaging Service (JMS) topic or it could be implemented as Message Driven Bean (MDB) in order to send a message to the <a4j:push> component about an event presence. In the presence of the event some action occurs.
Thus, a work paradigm with the <a4j:push> component corresponds to an anisochronous model, but not to pools as for <a4j:poll> component. See the simplest example below:
Example:
...
class MyPushEventListener implements PushEventListener {
public void onEvent(EventObject evt) {
System.out.println(evt.getSource());
//Some action
}
}
...
Code for EventListener
registration in the bean is placed
below:
Example:
...
public void addListener(EventListener listener) {
synchronized (listener) {
if (this.listener != listener) {
this.listener = (PushEventListener) listener;
}
}
}
...
A page code for this example is placed below.
Example:
...
<a4j:status startText="in progress" stopText="done"/>
<a4j:form>
<a4j:region>
<a4j:push reRender="msg" eventProducer="#{pushBean.addListener}" interval="2000"/>
</a4j:region>
<a4j:outputPanel id="msg">
<h:outputText value="#{pushBean.date}">
<f:convertDateTime type="time"/>
</h:outputText>
</a4j:outputPanel>
<a4j:commandButton value="Push!!" action="#{pushBean.push}" ajaxSingle="true"/>
</a4j:form>
...
The example shows how date is updated on a page in compliance with data taken from a server. In the example "interval" attribute has value "2000". This attribute defines an interval in milliseconds between the previous response and the next request. Default value is set to "1000" milliseconds (1 second). It's possible to set value equal to "0". In this case connection is permanent.
The "timeout" attribute defines response waiting time in milliseconds. If a response isn't received during this period a connection is aborted and the next request is sent. Default value for "timeout" attribute isn't set. Usage of "interval" and "timeout" attributes gives an opportunity to set short polls of queue state or long connections.
The form around the <a4j:push> component is required.
Table of <a4j:push> attributes.
Table 6.10. Component Identification Parameters
Name | Value |
---|---|
component-type | org.ajax4jsf.Push |
component-family | org.ajax4jsf.components.AjaxPush |
component-class | org.ajax4jsf.component.html.AjaxPush |
renderer-type | org.ajax4jsf.components.AjaxPushRenderer |
On RichFaces LiveDemo page you can found some additional information for <a4j:push> component usage.
Refer to Simple IRC Widget with <a4j:push> article to find out real-world usage of the <a4j:push> component.
The <a4j:queue> component enqueues set of Ajax requests sent from client. The RichFaces components with built-in Ajax can reference the queue to optimize Ajax requests.
The RichFaces Queue has four different types: global default, view scoped default, view scoped named and form-based default queue (general Queue principles are good documented in the "Queue Principles" section). The current section will take closer to the form based queue. The usage of other types is similar.
In order to disable or enable the <a4j:queue> component on the page you can use the "disabled" attribute.
The "requestDelay" attribute defines delay time for all the requests fired by the action components.
The "size" attribute specifies the number of requests that can be stored in the queue at a time. The attribute helps to prevent server overloading. It is also possible to determine queue's behaviour when it's size is exceeded. Use the "sizeExceededBehavior" for this purpose. There are four possible strategies of exceeded queue's behavior:
"dropNext" drops next request that should be fired
"dropNew" drops the incoming request
"fireNext" immediately fires the next request in line to be fired
"fireNew" immediately fires the incoming request.
Example:
<h:form>
<a4j:queue size="2" requestDelay="500" sizeExceededBehavior="dropNext" onsizeexceeded="alert('The size of the queue is exceeded')" />
<h:inputText value="#{bean.a}">
<a4j:support event="onkeyup" />
</h:inputText>
<h:inputText value="#{bean.b}">
<a4j:support event="onblur" />
</h:inputText>
<h:selectBooleanCheckbox value="#{bean.check}" id="checkboxID">
<a4j:support id="checkboxSupport" event="onchange" />
</h:selectBooleanCheckbox>
</h:form>
In this example if the queue has more than 2 requests waiting to be processed the next event will be dropped and a message (the "onsizeexceeded" attribute fires a JavaScript function) saying that the queues is exceeded will be displayed.
The "ignoreDupResponses" attribute that takes a boolean value can also help optimize your Ajax requests. If set to true, response processing for request will not occur if a similar request is already waiting in the queue. New request will be fired immediately when the response from the previous one returns.
Example:
<h:form>
<a4j:queue requestDelay="500" ignoreDupResponses="true" />
<h:inputText value="#{bean.a}">
<a4j:support event="onkeyup" />
</h:inputText>
</h:form>
In this example, the requests are glued together and only the last one is submitted.
Another key attribute that easies server load is "timeout" . The attribute specifies the amount of time an item can be in the queue before the sent event is be aborted and dropped from the queue.
If the request is sent and response is not returned within the time frame defined in this attribute - the request is aborted, and the next one is sent.
Example:
<h:form>
<a4j:queue timeout="1000" />
<h:inputText value="#{bean.a}">
<a4j:support event="onkeyup" />
</h:inputText>
</h:form>
In this case if the sever doesn't respond within a second the request will be aborted.
As you can see the implementation of the queue provides some custom event handlers that you may use to call JavaScript functions.
The
"oncomplete"
is fired after request completed.
In this event handler request object is be passed as a parameter.
Thus queue is be accessible using request.queue
.
And the element which was a source of the request is available using this
.
Example:
<h:form>
<a4j:queue oncomplete="alert(request.queue.getSize())" requestDelay="1000" />
<h:inputText value="#{bean.a}">
<a4j:support event="onkeyup" />
</h:inputText>
<h:selectBooleanCheckbox value="#{bean.check}">
<a4j:support event="onchange"/>
</h:selectBooleanCheckbox>
</h:form>
In this example you can see how the number of requests waiting in the queue change. You will get a message with the number of the requests in the queue.
The "onbeforedomupdate" event handler called before updating DOM on a client side.
The "onrequestqueue" event handler called after the new request has been added to queue. And the "onrequestdequeue" event handler called after the request has been removed from queue.
The "onsubmit" event handler called after request is completed. This attribute allows to invoke JavaScript code before an Ajax request is sent.
Table of <a4j:queue> attributes.
Table 6.11. Component Identification Parameters
Name | Value |
---|---|
component-family | org.ajax4jsf.Queue |
component-class | org.ajax4jsf.component.html.HtmlQueue |
renderer-type | org.ajax4jsf.QueueRenderer |
tag-class | org.ajax4jsf.taglib.html.jsp.QueueTag |
Table 6.12. JavaScript API
Function | Description |
---|---|
getSize() | Returns the current size to the queue |
getMaximumSize() | Returns the maximum size to the queue, specified in the "size" attribute |
Visit the Queue Page at the RichFaces LiveDemo for examples of component usage and their sources.
Useful articles:
"Queue Principles" section of the RichFaces developer guide describes general Queue principles.
The <a4j:status> component generates elements for displaying of the current Ajax requests status. There are two status modes: Ajax request is in process or finished.
There are two ways for the components or containers definition, which Ajax requests status is tracked by a component.
Definition with the "for" attribute on the <a4j:status> component. Here "for" attribute should point at an Ajax container ( <a4j:region> ) id, which requests are tracked by a component.
Definition with the "status" attribute obtained by any RichFaces library action component. The attribute should point at the <a4j:status> component id. Then this <a4j:status> component shows the status for the request fired from this action component.
The component creates two <span> or <div> elements depending on attribute "layout" with content defined for each status, one of the elements (start) is initially hidden. At the beginning of an Ajax request, elements state is inversed, hence the second element is shown and the first is hidden. At the end of a response processing, elements display states return to its initial values.
Example:
<a4j:status startText="Started" stopText="stopped" />
The code shown in the example above is decoded on a page as:
<span id="j_id20:status.start" style="display: none">
Started
</span>
<span id="j_id20:status.stop">