JBoss RichFaces

  • submit to reddit

JBoss RichFaces

By Nick Belaevski, Ilya Shaikovsky, Jay Balunas and Max Katz

22,648 Downloads · Refcard 44 of 203 (see them all)

Download
FREE PDF


The Essential JBoss RichFaces Cheat Sheet

JBoss RichFaces is a JSF component library that consists of two main parts: Ajax enabled JSF components and the CDK (Component Development Kit). It allows easy integration of Ajax capabilities into enterprise application development. This DZone Refcard is a great start for any developer looking to learn more about JBoss RichFaces. You will find plenty of examples and code samples that will help with your Rich Internet Applications. This Refcard also covers the following topics: What is RichFaces?, Basic Concepts, Controlling Traffic, Tags, Hot Tips and more.
HTML Preview
JBoss RichFaces

JBoss RichFaces

By Nick Belaevski, Ilya Shaikovsky Jay Balunas, and Max Katz

What is Richfaces?

RichFaces is a JSF component library that consists of two main parts: AJAX enabled JSF components and the CDK (Component Development Kit). RichFaces UI components are divided into two tag libraries a4j: and rich:. Both tag libraries offer out-of-the-box AJAX enabled JSF components. The CDK is a facility for creating, generating and testing you own rich JSF components (not covered in this card).

Installing Richfaces

See the RichFaces Project page for the latest version- http:// www.jboss.org/jbossrichfaces/.

Add these jar files to your WEB-INF/lib directory: richfacesapi. jar, richfaces-impl.jar, richfaces-ui.jar, commons-beanutils.jar, commons-collections.jar, commons-digester.jar, commons-logging.jar

RichFaces Filter

Update the web.xml file with 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>
  <dispatcher>ERROR</dispatcher>
</filter-mapping>

Hot Tip

The RichFaces Filter is not needed for applications that use Seam (http://seamframework.org)

Page setup

Configure RichFaces namespaces and taglibs in your XHTML and JSP pages.

Facelets
xmlns:a4j=”http://richfaces.org/a4j”
xmlns:rich=”http://richfaces.org/rich”
JSP
<%@ taglib uri=”http://richfaces.org/a4j” prefix=”a4j”%>
<%@ taglib uri=”http://richfaces.org/rich” prefix=”rich”%>

Hot Tip

Use JBoss Tools for rapid project setup - http://www.jboss.org/tools

Basic Concepts

Sending an AJAX request

a4j:support

Sends an AJAX request based on a DHTML event supported by the parent component. In this example, the AJAX request will be triggered after the user types a character in the text box:

a4j:support

<h:inputText value=”#{echoBean.text}”>
  <a4j:support event=”onkeyup” action=”#{echoBean.count}”
	              reRender=”echo, cnt”/>
</h:inputText>
<h:outputText id=”echo” value=”Echo: #{echoBean.text}”/>
<h:outputText id=”cnt” value=”Count: #{echoBean.textCount}”/></td>

a4j:support can be attached to any html tag that supports DHTML events, such as:

</table>

a4j:commandButton, a4j:commandLink

Similar to h:commandButton and h:commandLink but with two major differences. They trigger an AJAX request and allow partial JSF component tree rendering.

The request goes through the standard JSF life cyle. During the Render Response, only components whose client ids are listed in the reRender attribute (echo, count) are rendered back the the browser.
a4j:support

<h:selectOneRadio value=”#{colorBean.color}”>
  <f:selectItems value=”#{colorBean.colorList}” />
  <a4j:support event=”onclick” reRender=”id” />
</h:selectOneRadio></td>
	
a4j:commandButton, a4j:commandLink

<h:inputText value=”#{echoBean.text}”/>
  <h:outputText id=“echo” value=“Echo: #{echoBean.text}”/>
  <h:outputText id=“cnt” value=“Count: #{echoBean.textCount}”/>
  <a4j:commandButton value=“Submit” action=“#{echoBean.count}”
     reRender=“echo, cnt”/>

Basic Concepts, continued

When the response is received, the browser DOM is updated with the new data i.e ‘RichFaces is neat’ and ‘17’.

New Data

a4j:commandLink works exactly the same but renders a link instead of a button.

a4j:poll

Enables independent periodic polling of the server via an AJAX request. Polling interval is defined by the interval attribute and enable/disable polling is configured via enabled attribute (true|fase).

a4j:poll

<a4j:poll id=”poll” interval=”500” enabled=”#{pollBean.enabled}”
reRender=”now” />
  <a4j:commandButton value=”Start” reRender=”poll”
	 action=”#{pollBean.start}” />
  <a4j:commandButton value=”Stop” reRender=”poll”
	 action=”#{pollBean.stop}” />
  <h:outputText id=”now” value=”#{pollBean.now}” />

a4j:poll

public class PollBean {
	private Boolean enabled=false; // setter and getter
	public void start () {enabled = true;}
	public void stop () {enabled = false;}
	public Date getNow () {return new Date();}
}

a4j:jsFunction

Allows sending an AJAX request directly from any JavaScript function (built-in or custom).

a4j:jsFunction

<td onmouseover=”setdrink(‘Espresso’)”
    onmouseout=”setdrink(‘’)”>Espresso</td>
...
<h:outputText id=”drink” value=”I like #{bean.drink}” />
<a4j:jsFunction name=”setdrink” reRender=”drink”>
<a4j:actionparam name=”param1” assignTo=”#{bean.drink}”/>
</a4j:jsFunction>

When the mouse hovers or leaves a drink, the setdrink() JavaScript function is called. The function is defined by an a4j:jsFunction tag which sets up the AJAX call. It can call listeners and perform partial page rendering. The drink parameter is passed to the server via a4j:actionparam tag.

a4j:push

a4j:push works similarly to a4j:poll; however, in order to check the presence of a message in a queue, it only makes a minimal HEAD request(ping-like) to the server without invoking the JSF life cycle. If a message exists, a sandard JSF request is sent to the server.

Partial view (page) rendering

There are two ways to perform partial view rendering when AJAX requests return.

ReRender attribute

Most RichFaces components support the reRender attribute to define the set of client ids to reRender.

Attribute Can bind to
reRender/td> Set, Collection, Array, comma-delimited String

ReRender can be set statically as in the examples above or with EL:


<a4j:commandLink reRender=”#{bean.renderControls}”/>

Basic Concepts, continued

It’s also possible to point to parent components to rerender all child components:


<a4j:commandLink value=”Submit” reRender=”panel” />
<h:panelGrid id=”panel”>
   <h:outputText />
   <h:dataTable>...</h:dataTable>
</h:panelGrid>

In the example above the child components of the outputPanel will be rerendered when the commandLink is submitted.

a4j:outputPanel

All child components of an a4j:outputPanel will be rerendered automatically for any AJAX request.


<a4j:commandLink value=”Submit” />
<a4j:outputPanel ajaxRendered=”true”>
   <h:outputText/>
   <h:dataTable></h:dataTable>
</a4j:outputPanel>

In the example above the child components of the outputPanel will be rerendered when the commandLink is submitted.

Hot Tip

If ajaxRendered=”false” (default) the a4j:outputPanel behaves just like h:panelGroup.

To limit rendering to only components set in the reRender attribute, set limitToList=”true”. In this example, only h:panelGrid will be rendered:


<a4j:commandLink reRender=”panel” limitToList=”true”/>
<h:panelGrid id=”panel”>
<h:dataTable>...</h:dataTable>
   </h:panelGrid>
<a4j:outputPanel ajaxRendered=”true”>
   lt;h:dataTable>...</h:dataTable>
</a4j:outputPanel>

Deciding what to process on the server

When an AJAX request is sent to the server, the full HTML form is always submitted. However, once on the server we can decide what components to decode or process during the Apply Request, Process Validations and Update Model phases. Selecting which components to process is important in validation. For example, when validating a component (field) via AJAX, we don’t want to process other components in the form (in order not to display error messages for components where input hasn’t been entered yet). Controlling what is processed will help us with that.

The simplest way to control what is processed on the server is to define an AJAX region using the a4j:region tag (by default the whole page is an AJAX region).


<h:inputText>
  <a4j:support event=”onblur” />
</h:inputText>
<a4j:region>
  <h:inputText>
    <a4j:support event=”onblur” />
  </h:inputText>
</a4j:region>

When the user leaves the 2nd input component (onblur event), an AJAX request will be sent where only this input field will be processed on the server. All other components outside this region will not be processed (no conversion/validation, update model, etc). It’s also possible to nest regions:


<a4j:region>
  ...
  <a4j:region>
    ...
  </a4j:region>
</a4j:region>

Basic Concepts, continued

When the request is invoked from the inner region, only components in the inner region will be processed. When invoked from outer region, all components (including inner region) will be processed.

When sending a request from a region, processing is limited to components inside this region. To limit rendering to a region, the renderRegionOnly attribute can be used:


<a4j:region renderRegionOnly=”true”>
   <h:inputText />
   <a4j:commandButton reRender=”panel”/>
   <h:panelGrid id=”panel”>
</a4j:region>
<a4j:outputPanel ajaxRendered=”true”>
   <h:dataTable></h:dataTable>
</a4j:outputPanel>

When the AJAX request is sent from the region, rendering will be limited to components inside that region only because renderRegionOnly=”true”. Otherwise, components inside a4j:outputPanel would be rendered as well.

To process a single input or action component, instead of wrapping inside a4j:region, it’s possible to use the ajaxSingle attribute:

<h:inputText> <a4j:support event=”onblur” ajaxSingle=”true”/> <<

When using ajaxSingle=”true” and a need arises to process additional components on a page, the process attribute is used to include id’s of components to be processed.


<h:inputText>
   <a4j:support event=”onblur” ajaxSingle=”true” process=”mobile”/>
</h:inputText>
<h:inputText id=”mobile”/>


The process can also point to an EL expression or container
component id in which case all components inside the
container will be processed.


When just validating form fields, it is usually not necessary
to go through the Update Model and Invoke Application
phases. Setting bypassUpdates=”true”, will skip these phases,
improving response time, and allowing you to perform
validation without changing the model’s state.


<h:inputText>
  <a4j:support event=”onblur” ajaxSingle=”true”
bypassUpdates=”true”/>
</h:inputText>

JavaScript interactions

RichFaces components send an AJAX request and do partial page rendering without writing any direct JavaScript code. If you need to use custom JavaScript functions, the following attributes can be used to trigger them.

Tag Attributte Description
a4j:commandButton,
a4j:commandLink,
a4j:support,
a4j:poll,
a4j:jsFunction
onbeforedomupdate: JavaScript code to be invoked after
response is received but before browser DOM update
oncomplete: JavaScript code to be invoked after browser DOM
updatedata. Allows to get the additional data from the server
during an AJAX call. Value is serialized in JSON format.
a4j:commandButton,
a4j:commandLink
onclick: JavaScript code to be invoked before AJAX request is sent.
a4j:support,
a4j:poll
onsubmit: JavaScript code to be invoked before AJAX request is sent.

Controlling Traffic

Flooding a server with small requests can cripple a web application, and any dependent services like databases.

Controlling Traffic, continued
Richfaces 3.3.0.GA and Higher

Queues can be defined using the<a4j:queue .../> component and are referred to as Named or Unnamed queues. Unnamed queues are also referred to as Default queues because components within a specified scope will use an unnamed queue by default.

Notable Attributes

Attribute Description
name Optional Attribute that determines if this is a named or unnamed queue
sizeExceededBehavior When the size limit reached: dropNext, DropNew, fireNext, fireNew
ignoreDupResponses If true then responses from the server will be ignored if there are queued evens of the same type waiting.
requestDelay Time in ms. events should wait in the queue incase more events of the same type are fired
Event Triggers onRequestDequeue, onRequestQueue, onSizeExeeded, onSubmit

Other notable attributes include: disabled, id, binding, status, size, timeout.

Named Queues

Named queues will only be used by components that reference them by name as below:


<a4j:queue name=”fooQueue” ... />
	<h:inputText … >
<a4j:support eventsQueue=”fooQueue” .../>
</h:inputText>

Unnamed Queues

Unnamed queues are used to avoid having to specifically reference named queues for every component.

Queue Scope Description
Global All views of the application will have a view scoped queue that does not need to be defined and that all components will use.
View Components within the parent will use this queue
Form Component within the parent or will use this queue

Global Queue

To enable the global queue for an application you must add this to the web.xml file.


<context-param>
<param-name>org.richfaces.queue.global.enabled</param-name>
  <param-value>true</param-value>
</context-param>

It is possible to disable or adjust the global queue’s settings in a particular view by referencing it by its name.


<a4j:queue name=”org.richfaces.global_queue” disabled=”true”... />

View Scoped Default Queues

Defined the <a4j:queue> as a child to the <f:view>.


<f:view>
  ...
  <a4j:queue ... />

Hot Tip

Performance Tips:

  • Control the number of requests sent to the server.
  • Limit the size of regions that are updated per request using <a4j:region/>
  • Cache or optimize database access for AJAX requests
  • Don’t forget to refresh the page when needed

Controlling Traffic, continued

Form Scoped Default Queue

This can be useful for separating behavior and grouping requests in templates.


<h:form>
   ...
<a4j:queue ... />
      ...


A4j:* Tags

The a4j:* tags provide core AJAX components that allow developers to augment existing components and provide plumbing for custom AJAX behavior.

a4j:repeat

This component is just like ui:repeat from Facelets, but also allows AJAX updates for particular rows. In the example below the component is used to output a list of numbers together with controls to change (the value is updated for the clicked row only):


<a4j:repeat value=”#{items}” var=”item”>
	<h:outputText value=”#{item.value} “ id=”value”/>
	<a4j:commandLink action=”#{item.inc}” value=” +1 “
reRender=”value”/>
  </a4j:repeat>

#{items} could be any of the supported JSF data models. var identifies a request-scoped variable where the data for each iteration step is exposed. No markup is rendered by the component itself so a4j:repeat cannot serve as a target for reRender.

The component can be updated fully (by usual means) or partially. In order to get full control over partial updates you should use the ajaxKeys attribute. This attribute points to a set of model keys identifying the element sequence in iteration. The first element has Integer(0) key, the second – Integer(1) key, etc. Updates of nested components will be limited to these elements.

a4j:include

Defines page areas that can be updated by AJAX according to application navigation rules. It has a viewId attribute defining the identifier of the view to include:


<a4j:include viewId=”/first.xhtml” /> 

One handy usage of a4j:include is for building multi-page wizards. Ajax4jsf command components put inside the included page (e.g. first.xhtml for our case) will navigate users to another wizard page via AJAX:


<a4j:commandButton action=”next” value=”To next page” />

(The “next” action should be defined in the faces-config.xml navigation rules for this to work). Setting ajaxRendered true will cause a4j:include content to be updated on every AJAX request, not only by navigation. Currently, a4j:include cannot be created dynamically using Java code.

a4j:keepAlive

Allows you to keep bean state (e.g. for request scoped beans) between requests:


<a4j:keepAlive beanName=”searchBean” />

Standard JSF state saving is used so in order to be portable

a4j:* Components, continued

it is recommended that bean class implements either java. io.Serializable or javax.faces.component.StateHolder.

a4j:keepAlive cannot be created programmatically using Java. Mark managed bean classes using the org.ajax4jsf. model.KeepAlive annotation in order to keep their states.JBoss Seam’s page scope provides a more powerful analog to ths behavior.

a4j:loadXXX
RichFaces provides several ways to load bundles, scripts, and styles into your application.

Tag Description
a4j:loadBundle a4j:loadBundle loads a resource bundle localized for the locale of the current view
a4j:loadScript loads an external JavaScript file into the current view
a4j:loadStyle loads an external .css file into the current view

a4j:status
Used to display the current status of AJAX requests such as “loading...” text and images. The component uses “start” and “stop” facets to define behavior. It is also possible to invoke Javascript or set styles based on status mode changes.

a4j:actionparam
Adds additional request parameters and behavior to command components (like a4j:commandLink or h:commandLink). This component can also add actionListeners that will be fired after the model has been updated.

rich:* tags

The rich: tags are ready-made or self-contained components. They don’t require any additional wiring or page control components to function.

Input Tags

Tag Description
rich:calendar Advanced Date and Time input with many options such as
inline/popup, locale, and custom date and time patterns.
rich:editor A complete WYSIWYG editor component that supports
HTML and Seam Text
rich:inplaceInput Inline inconspicuous input fields
rich:inputNumberSlider min/max values slider

Components include: comboBox, fileUpload, inplaceSelect, inputNumberSpinner

Output Tags

Tag Description
rich:modalPanel Blocks interactions with the rest of the page while active
rich:panelMenu Collapsable grouped panels with subgroup support
rich:progressBar AJAX polling of server state
rich:tabPanel Tabbed panel with client, server, or ajax switching
rich:toolBar Complex content and settings

Components include: paint2D, panel, panelBar,simpleTogglePanel, togglePanel, toolTip

Data Grids, Lists, and Tables

RichFaces has support for AJAX-based data scrolling, complex cell content, grid/list/table formats, filtering, sorting, etc....

rich:* Tags, continued

Tag Description
rich:dataTable Supports complex content, AJAX updates, sortable, and filterable columns
rich:extendedDataTable Adds scrollable data, row selection options, adjustable column locations, and row/column grouping
rich:dataGrid Complex grid rendering of grouped data from a model

Complex Content Sample

Tags Table

Menus

Hierarchical menus available in RichFaces include:

Tag Description Menus
rich:contextMenu Based on page location
and can be attached to
most components link
images, labels, etc...
rich:dropDownMenu Classic application style
menu that supports
icons and submenus.

Components include: rich:menItem, rich:menuGroup,rich:menuSeparator

Trees

RichFaces has tree displays that support many options such as switching (AJAX client or server), drag-drop and are dynamically generated from data models.

Tag Description Menus2
rich:tree Core parent component for a tree
rich:treeNode Creates sets of tree elements
rich:treeNodeAdaptor Defines data model sources for trees
rich:recursiveTree NodeAdaptor Adds recursive node definition from models

Selects

Provides visually appealing list manipulation options for the UI.

Tag Description Menus3
rich:listShuttle Advanced data list manipulation (figure x)
rich:orderingList Visually manipulate a lists order

Validation Tags

AJAX endabled validation including hibernate validation.

Tag Description
rich:ajaxValidator Event triggered validation without updating the model- this skips all JSF phases except validation.
rich:beanValidator Validate individual input fields using hibernate validators in your bean/model classes
rich:graphValidator Validate whole subtree of components using hibernate validators. can also validate the whole bean after model updates.

Drag-Drop

Allows many component types to support drag and drop features.

Tag Description
rich:dragSupport Add as a child to components you want to drag.
righ:dropSupport Define components that support dropped items.
rich:dragIndicator Allows for custom visualizations while dragging an item.
rich:dndParam To pass parameters during a drag-n-drop action.

Miscellaneous

Tag Description
rich:componentControl Attach triggers to call JS API functions on the components after defined events.
rich:effect Scriptaculous visual effect support
rich:gmap Embed GoogleMaps with custom controls
rich:hotKey Define events triggered by hot key (example: alt-z)
rich:insert Display and format files from the file system
rich:virtualEarth Embed Virtual Earth images and controls

Components include: rich:message, rich:messages, rich:jQuery

Skinning

Using out-of-the-box skins

RichFaces ships with a number of built-in skins.

Out-of-the-box Skins
default, classic, emeraldTown, blueSky, ruby, wine, deepMarine, sakura, plain, default, laguna*, glassx*, darkx*
* Require a separate jar file to function

Add the org.richfaces.SKIN context parameter to web.xml and set the skin name.


<context-param>
  <param-name>org.richfaces.SKIN</param-name>
  <param-value>blueSky</param-value>
</context-param>

Sample blueSky skin Sample ruby skin
sample 1 sample 2

Using skin property values on the page

You can use skinBean implicit object to use any value from the skin file on your page.


<h:commandButton value=”Next”
  style=”backgroundcolor:#{
skinBean.
  tabBackgroundColor}”/>

sample 3

The button color is set according to the current skin[Ruby].s

Loading different skins at runtime

You can define an applications skin with EL expression like this:


<context-param>
  <param-name>org.richfaces.SKIN</param-name>
  <param-value>#(skinBean.currentSkin)</param-value>
</context-param>

Define a session scoped skinBean and manage its currentSkin property at runtime with your skin names values. Every time a page is rendered, RichFaces will resolve the value in #{skinBean.currentSkin} to get the current skin. Changing Skins should not be done via AJAX but with a full page refresh. A full page refresh will ensure that all CSS links are correctly updated based on the new skin

Hot Tip

Advanced Skinning Features

  • Create custom skins, or extend the default skins
  • Override or extend styles per page as needed
  • Automatically skin the standard JSF components
  • Plug'n'Skin feature used to generate whole new skins using Maven archetypes

Customizing redefined CSS classes

Under the hood all RichFaces components are equipped with a set of predefined rich-* CSS classes that can be extended to allow customization of a components style (see documentation for details). By modifying these CSS classes you can update all components that use them such as:


.rich-input-text {
   color: red;
}

Project links for more information or questions:

Project page (http://www.jboss.org/jbossrichfaces)
Documentation (http://jboss.org/jbossrichfaces/docs)

About The Author

Photo of author Nick Belaevski

NickBelaevski

Nick Belaevski Nick Belaevski is the team leader of the RichFaces project working for Exadel Inc. He has more than four years of experience in development of middleware products including JBoss Tools and RichFaces.

Projects: RichFaces

Photo of author Ilya Shaikovski

Ilya Shaikovski

Ilya Shaikovsky is the Exadel product manager working on the RichFaces project since Exadel began ajax4jsf. He’s responsible for requirements gathering, specification development, JSF related product analysis and supporting RichFaces and JSF related technologies for business applications. Prior to this he worked on the Exadel Studio Pro product.

Projects: RichFaces

Photo of author Jay Balunas

Jay Balunas

Jay Balunas works as the RichFaces Project Lead and core developer at JBoss, a division of Red Hat. He has been architecting and developing enterprise applications for over ten years specializing in web tier frameworks, UI design, and integration. Jay blogs about Seam, RichFaces, and other technologies at http://in.relation.to/Bloggers/Jay

Projects: RichFaces, Seam Framework, and JBoss Tattletale

Photo of author Max Katz

Max Katz

Max Katz is a senior system engineer at Exadel. He is the author of “Practical Rich- Faces” (Apress). He has been involved with RichFaces since its inception. He has written numerous articles, provided training, and presented at many conferences and webinars about RichFaces. Max blogs about RichFaces and RIA technologies at http://mkblog.exadel.com.

Projects: RichFaces

Recommended Book

PracticalRichFaces

JBoss RichFaces is a rich JSF component library that helps developers quickly develop next–generation web applications. Practical RichFaces describes how to best take advantage of RichFaces, the integration of the Ajax4jsf and RichFaces libraries, to create a flexible and powerful programs. Assuming some JSF background, it shows you how you can radically reduce programming time and effort to create rich AJAX based applications.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.