Using RichFaces with JSF 2

Migrating your web page components to RichFaces 4

JavaServer Faces (JSF) 2, released in 2009, contains major changes and additions in many areas, including system events, resources, and standardization of both Facelets and Ajax handling (see Related topics). Although this evolution was welcome in general, an unfortunate and significant side-effect is that virtually all rich component frameworks written for JSF 1.2 — including RichFaces version 3.x and below — no longer function reliably, if at all. In response, the RichFaces team embarked on an extensive rewrite for version 4. As you'll see in this article, some component names have changed; other components have been removed and new ones added.

In my 2008 article "An introduction to RichFaces," I presented several RichFaces version 3.1 components and explained the setup requirements for RichFaces and JavaServer Faces (JSF) 1.2. This follow-up article serves both as a guide for developers new to RichFaces and as an aid for migrating from previous versions to version 4.x. I have provided a WAR with demonstration code (see Download).

If you are new to RichFaces and want to use it with JSF 2, read just this article (although you may want to review the previous article's resources). If you've used RichFaces before version 4, I suggest that you view the two articles side by side. To make it easier to compare version differences, I've used the same section headers in both. I've also worked to duplicate the components' appearance and functionality.

From this point on, I'll use RichFaces to refer to version 4.x if I don't mention a specific version. I'll start with a look at some necessary infrastructure elements for development with RichFaces.

From the beginning

The minimum infrastructure requirements for developing with RichFaces are:

  • Java™ SE 6
  • A Servlet 2.5 container
  • A minimally current browser, such as Firefox 3.5 or Internet Explorer 7 or above

For my development and testing, I used JDK 7, Apache Tomcat 7.0.22, and GlassFish 3.1.1. The browsers I used were Firefox 7.0.1 and Internet Explorer 8.

You shouldn't experience any issues in general from my setup and the minimums noted above. However, there are some things to keep in mind regarding the demo code:

  • If you use a container that supports only Servlet 2.5, in web.xml you must change <web-app version="3.0"...> to <web-app version="2.5"...>.
  • For GlassFish V3 and other containers with JEE 6 / JSF 2 support, you can remove javax.faces.jar from the demo project. The version used in the demo is mojarra-2.1.4.
  • On a mailing list, I have seen mention of occasional problems with Expression Language (EL) on some JSF 2 versions and older containers. If you get odd results, try downloading the latest EL JARs.

This article assumes readers have a basic knowledge of JSF 2 and of Tomcat or GlassFish. If you need more background on these technologies, see Related topics for appropriate links.

Not small faces

Facelets, despite its name, is not a smaller version of JSF; instead, at its core Facelets provides an alternative to JavaServer Pages (JSP) as a JSF ViewHandler. Facelets supports all of the JSF UI components and builds its own component tree, reflecting the view for a JSF application. The JSF 2 specification deprecates JSP as a view-definition language (VDL) and includes a standard version of Facelets as the preferred VDL. For that reason, RichFaces dropped JSP support and requires Facelets.

I prefer keeping things as clean and straightforward as possible. In the example project, you'll see that virtually all of the page code (as opposed to markup) is composed of EL expressions for getters, setters, and method bindings. Although more complex projects may call for more complex expressions, in general Facelets makes it easy to keep Java code separate from your web page markup.

The primary differences you'll notice here from pre-JSF 2 development using JSP are:

  • Some additional notations in web.xml and faces-config.xml are required or defaulted.
  • Web pages are XHTML documents.
  • XML namespaces are used rather than JSP taglibs.

As far as formatting goes, other than the initial portions (see Listing 1), everything in the web page code should look familiar. I view that aspect as an understated Facelets feature. For this article's project — and many others in which the primary use of Facelets is for handling the view — that's really all you need to know. Facelets also includes a number of other useful features, such as easy templating and elements to make life easier for web page designers. (To learn more about Facelets, see Related topics.)

Listing 1. Initial portion of a Facelets XHTML document
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns=""

The demonstration components

RichFaces can seem initially overwhelming; the average component has more than 20 specific attributes, plus general attributes that can be overridden. However, in typical usage the components are not difficult to set up, with most attributes having reasonable defaults. Version 4 has introduced changed and additional defaults, and it's worthwhile to check the documentation.

The primary components demonstrated in this article (with replacements for Version 4 noted) are:

  • Calendar : A pop-up component that allows date selections. Figure 1 shows an example. < and > roll the month; << and >> roll the year. Clicking Today at the bottom selects today's date. Clean clears the date selection. The first column of numbers on the left shows the week of the year.
    Figure 1. RichFaces Calendar component
    Screen shot of RichFaces Calendar component
  • Pick List : A selection and ordering component. Pick List is a version 4 replacement for List Shuttle that can move items between available and selected areas, and up and down in the selected area. Figure 2 shows an example:
    Figure 2. RichFaces Pick List component
    Screen shots of RichFaces Pick List component
    Screen shots of RichFaces Pick List component
  • AutoComplete : A version 4 replacement for the Suggestion Box input component that provides clickable suggestions to fill or complete an entry. Figure 3 shows an example:
    Figure 3. RichFaces AutoComplete component
    Screen shot of RichFaces AutoComplete Component
  • Tab Panel : An output component that creates tabbed pages. Figure 4 shows an example:
    Figure 4. RichFaces Tab Panel component
    Screen shot of RichFaces Tab Panel Component
    Screen shot of RichFaces Tab Panel Component
  • Accordion : A version 4 replacement for the Panel Bar input component. The sample project uses an Accordion for instructions. Figure 5 shows an example:
    Figure 5. RichFaces Accordion component
    Screen shot of RichFaces Accordion Component
  • Collapsible Panel : A version 4 replacement for the Simple Toggle Panel component. The sample project uses Collapsible Panels for results. Figure 6 shows an example:
    Figure 6. RichFaces Collapsible Panel component
    Screen shot of RichFaces Collapsible Panel component
    Screen shot of RichFaces Collapsible Panel component

RichFaces is built on Ajax4jsf (see Related topics). Thanks to that foundation, any component can be Ajax enabled in several different ways. In version 4, Ajax functionality is often automatic or the default. The example application uses Ajax capabilities for the AutoComplete and Collapsible Panel components.

My brave face

The dwRichFaces4Demo1 example application is minimal; its only real purpose is to demonstrate setup and usage of the selected components. For that reason, all it does is collect and display input data. I'll leave to your imagination how to use the data and components in a production application. Aside from necessary JARs, images, a properties file backing a resource bundle, and Cascading Style Sheets (CSS) files, the application consists of two XHTML pages and two Java classes.

The URL for the input page displayed in Figure 7, assuming default setup for Tomcat or GlassFish, is http://localhost:8080/dwRichFaces4Demo1. On the input page, you can select a date using the Calendar component. The Pick List component lets you move and reorder the available items. The City AutoComplete component lets you key in a city name. City is Ajax-enabled; if you press the space bar, all available cities are shown. If you key city names beginning with an A or a J, lists of the appropriate cities are shown. The available cities on the list narrow as you key more characters. You can click on the Accordion items on the left for basic component instructions.

Figure 7. dwRichFaces4Demo1 input page
Screen shot of dwRichFaces4Demo1 input page
Screen shot of dwRichFaces4Demo1 input page

Once you've made your entries, click the Submit button. The application is so minimal that no editing is performed. Because manual input is disabled for the Calendar component, you can't even enter an invalid date. The Submit button causes the results page to display, as shown in Figure 8:

Figure 8. dwRichFaces4Demo1 results page
Screen shot of dwRichFaces4Demo1 Result Page
Screen shot of dwRichFaces4Demo1 Result Page

On the results page, click on the Result tab, then click the appropriate Collapsible Panel item to see the input value. Click the Edit button to return to the input page.

Notice that the background color of the Submit button in Figure 7 and the Edit button in Figure 8 matches that of the other elements even though those buttons are standard JSF, not RichFaces, components. I'll cover the reason in the next section.

Set me up

The very first things necessary for an application are the JSF, Facelets, and RichFaces enablers — that is, the JARs that implement their capabilities. For migration, note that the dependencies have changed completely in version 4.x. These JARs, with the versions noted below, are included in the lib directory of the downloadable WAR (see Download). The list assumes that your web container supports current EL and Servlet API versions. If you have issues running the demonstration, check JSF, Facelets, and RichFaces requirements (see Related topics.) You should also read the Download note.

The JARs required for any RichFaces project are:

  • JSF 2 (included in JEE 6 containers like GlassFish V3.x)
    • javax.faces.jar
  • Facelets
    • Included in the JSF 2 JAR
  • RichFaces
    • richfaces-components-api-ver.jar
    • richfaces-components-ui-ver.jar
    • richfaces-core-api-ver.jar
    • richfaces-core-impl-ver.jar
  • Other required dependencies:
    • cssparser-ver.jar
    • guava-ver.jar
    • sac-ver.jar

In my project and included in the download WAR (see Related topics for download sites), the versions used are:

  • JSF 2
    • javax.faces.jar — mojarra-2.1.4
  • Facelets
    • Included in javax.faces.jar
  • RichFaces
    • richfaces-components-api-
    • richfaces-components-ui-
    • richfaces-core-api-
    • richfaces-core-impl-
  • Other required dependencies:
    • cssparser-0.9.5.jar
    • guava-10.0.1.jar
    • sac-1.3.jar

Next are web.xml entries, shown in Listing 2, needed to enable JSF. Note that when you use JSF 2 with a Servlet 3.0 container, these entries are optional. I prefer to be explicit. If omitted, *.faces, *.jsf, and /faces/* <url-pattern />s are automatically mapped.

Listing 2. Minimum JSF entries in web.xml
   <servlet-name>Faces Servlet</servlet-name>
   <servlet-name>Faces Servlet</servlet-name>

Prior to JSF 2, a javax.faces.DEFAULT_SUFFIX entry was needed for Facelets to make .xhtml override the .jsp default suffix. This entry is no longer required, because Facelets is now the default VDL.

RichFaces 4 no longer requires org.ajax4jsf.VIEW_HANDLERS, filter, or filter-mapping elements in web.xml. You can just drop in the JARs and use it.

Listing 3 shows the web.xml entries related to RichFaces as used in the demo application:

Listing 3. RichFaces-related entries in web.xml

Listing 3 includes two context parameters:

  • <param-name></param-name> defines the color scheme (skin) for the application. RichFaces has several built-in skins. The classic skin is a moderate blue. The default is light grey if this element is omitted.
  • The <param-name>org.richfaces.enableControlSkinning</param-name> value has an impact on the appearance of both RichFaces and, unexpectedly, standard JSF components. If its value is true, standard controls are skinned. This is why, for example, the Submit and Edit buttons in Figures 7 and 8 have the same color as the RichFaces theme. The default is true if this element is omitted.

The good news about the entries in Listings 2 and 3 is that they are virtually the same in all of your applications and essentially boilerplate code. If you're willing to accept the defaults and don't care about being explicit, you can dispense with them altogether.

There's one more piece that you'll see in every application: the RichFaces namespace in application XHTML pages. Listing 4 is a modification of Listing 1 that includes the RichFaces namespace:

Listing 4. Initial portion of a Facelets/RichFaces XHTML document
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns=""
     xmlns:rich="" >

Ready to rock

Now you're ready to see how to use RichFaces components. I'll begin with Accordion and Accordion Items (see Figure 5). These replaced the Panel Bar and Panel Bar Items in versions prior to RichFaces 4. You probably won't use them often, but they are easy to work with and provide a good first use case for RichFaces syntax.

The idea here is that an Accordion is a container for Accordion Items. An Accordion Item has a header and can contain any other component. Accordion Items stack on top of one another; the actual content is shown when the bar for the item is clicked. Only one item's content is shown at a time. In this case, as you can see from Listing 5, I'm just using text. Notice that all components have a rich: prefix, which refers to the namespace entry included in Listing 4. In the demo, the Accordion is contained in a standard JSF PanelGrid:

Listing 5. RichFaces Accordion component
<rich:accordion style="width: 256px;" styleClass="floatLeft">
    <rich:accordionItem header="#{dwRF4D1.calComp} #{}">
        <h:outputText value="#{dwRF4D1.calCompText}" style="font: menu;" />
    <rich:accordionItem header="#{dwRF4D1.plComp} #{}">
        <h:outputText value="#{dwRF4D1.plCompText}" style="font: menu;" />
    <rich:accordionItem header="#{dwRF4D1.acComp} #{}">
        <h:outputText value="#{dwRF4D1.acCompText}" style="font: menu;" />

The basic <rich:accordionItem /> element doesn't require much more than a header, which is pulled here from a resource bundle, using an EL expression.

The actual content for the demonstration Accordion Items is just an <h:outputText /> element, again with text from the resource bundle. I use a font style element for consistent readability, and also to show that RichFaces allows CSS flexibility.

Notice that no programmer involvement with the generated JavaScript is necessary. In just a few steps, you can create a nice-looking, multipanel, clickable component. This is one of RichFaces' great strengths. Even components as simple as this one allow Ajax (via the switchType attribute), active/inactive styles, events, and more.

Let's make a date

The Calendar component (see Figure 1) should be familiar; date selection was probably one of the earliest JavaScript enhancements to web pages. The RichFaces Calendar has more than 80 available attributes but, as you can see from Listing 6, you can enable a lot of functionality in just a few lines:

Listing 6. RichFaces Calendar component
<label for="CalendarID" >#{dwRF4D1.calendar}:</label>
<rich:calendar id="CalendarID"
               datePattern="#{dwRF4D1.datePattern}" >

The datePattern attribute wants a standard date pattern as defined by java.text.SimpleDateFormat. The example again uses the resource bundle for the value, which defines the datePattern key as yyyy-MM-dd. The value and timeZone attributes are loaded using methods from a managed bean, which is defined in faces-config.xml, as shown in Listing 7:

Listing 7. Managed-bean definition for dwRF4D1Handler

The com.dw.dwRF4D1Handler class is basic — consisting mostly of an initializer, getters, and setters — and it shouldn't require much further discussion. The getSelectedDate() and setSelectedDate() methods expect a java.util.Date. The getTimeZone() method just returns java.util.TimeZone.getDefault(); whether that is appropriate in production depends on your application requirements.

If you also want to allow the user to key in date values, set the enableManualInput attribute to true. If you just want to show the Calendar, set the popup attribute to false. Obviously, many other settings are available, but that's about all you need for basic Calendar functionality.

If you are migrating from previous RichFaces versions, setting up the Calendar component for the functionality in the demo code is virtually identical in version 4.

One way or another

The Pick List component with the orderable attribute — version 4's replacement for List Shuttle (see Figure 2 and the RichFaces 4.1 sidebar) — is ideal for selecting and ordering items from an initial group. Listing 8 demonstrates that it is also easier to use than you might initially think:

Listing 8. RichFaces Pick List component
<label for="plID">#{}:</label>
<rich:pickList id="plID
               orderable="true" listWidth="10em" 
               targetCaption="#{dwRF4D1.selected}" >
     <f:selectItems value="#{dwRF4D1Handler.orderBySource}" />

The XHTML markup in the example code includes additional attributes to override some default labels, but typical usage requires only value, <f:selectItems />, and usually orderable.

The value for selected values and <f:selectItems /> for available selections are java.util.List classes containing any type of object. In JSF 2, the value of <f:selectItems /> can be a collection or array containing objects of any type; toString() is called to provide labels. As with the demo code, you'll probably use lists containing Strings most of the time. Other than the List initialization for the <f:selectItems /> attribute value, Listing 9 shows all of the Java source related to the example Pick List. The Java code is virtually unchanged from that used in "An introduction to RichFaces."

Listing 9. Relevant dwRF4D1Handler Pick List code
private List<String> lOrderBySource = new ArrayList<String>(),
                     lOrderByTarget = new ArrayList<String>();
public List getOrderBySource()
  return lOrderBySource;

public List getOrderByTarget()
  return lOrderByTarget;
public void setOrderBySource( List<String> orderBySource )
  lOrderBySource = orderBySource;

public void setOrderByTarget( List<String> orderByTarget )
  lOrderByTarget = orderByTarget;

After the user has made the desired selection(s), on submittal your handler receives the list containing the choice(s).

Tell me to my face

If you frequent forums and mailing lists, sooner or later you will see a question that asks how to handle downloading thousands or millions of entries to a drop-down list. The AutoComplete component (see Figure 3), which replaces Suggestion Box, offers a way to show valid input selections without attempting that unworkable extreme. In fact, that concern was a major reason I began investigating RichFaces and similar suites: several entry items in an in-progress application, such as cities, had too many possibilities for a drop-down list to be practical. The AutoComplete functionality is similar to the familiar autocomplete components available in many desktop applications. It should be apparent that Ajax submittals would probably have to be involved for that sort of capability to have any chance of working efficiently in a web application.

Listing 10 shows the markup for the AutoComplete component. The field's input is either keyed or selected from the drop-down list.

Listing 10. RichFaces AutoComplete component
  <a4j:queue ignoreDupResponses="true"/> 


<label for="CityID">#{}:</label>
<rich:autocomplete id="CityID" mode="ajax" 
                   selectedItemClass="selCtl" > 

If you used Suggestion Box previously, you'll appreciate the simplifications with AutoComplete. The minimum attributes required are mode, value, and autocompleteMethod:

  • mode is typically ajax, causing an Ajax request on each keystroke — very nice and essentially automatic. Other values are: Cached Ajax, Client, and Lazy Client.
  • The value is the same as for most other components: typically getters and setters from a managed bean.
  • The autocompleteMethod method is suggest() in another managed bean based on the second Java class in the demo code, com.dw.City. The method signature is public List suggest(Object anObject).

In the demo code, a list of cities beginning with A and J is created on initialization. If the user presses the space bar in the City text field, the entire list is returned. If A is pressed, a sublist containing the cities starting with A is returned; J cities are handled in the same way. Results are narrowed with each keystroke. In your own code, you can do anything you want that is appropriate to the input. In my production application, the results came from a limited database set, which is probably most typical. If you are familiar with the data, you can usually take steps in the method to optimize results. I have cases, for example, in which certain keystrokes can be ignored, so the method just returns, eliminating a trip to the database.

In version 4.x, RichFaces builds on the standard JSF queue. The <a4j:queue /> attribute is not required, but you will probably want to use it frequently. Its use here is for ignoreDupResponses; review the documentation for other capabilities. Note that an <a4j:queue /> is used only for RichFaces component events. You can use it at the view or form level. A global application queue can be enabled in web.xml via a <param-name></param-name> context parameter.

You can also create a named queue, which components reference using <a4j:attachQueue name="myRequestQueue" />.

selectedItemClass is a CSS class to be applied to the component. RichFaces uses the skins concept. This is carried through to the selection background on components. My own application had several standard JSF drop-down lists that used the system color for the background. The AutoComplete component used the classic skins color, which made things appear inconsistent. The SelCtl class tells the component to use the lightgrey background color instead.

Keeping tabs

The Tab Panel component (see Figure 4) is straightforward to use, although for migration you should note some changes. The typical RichFaces attributes are available, but the primary one you will use is switchType. Its default value is server. For constant information, you'll probably most often want client; ajax is also available. As you can see from Listing 11, a typical RichFaces "sandwich" of <rich:tabPanel /> elements and stacked "sandwiches" of <rich:tab /> elements are used to make a set of tabbed pages:

Listing 11. RichFaces Tab Panel component
<rich:tabPanel switchType="client" >
        <rich:tab >
          <f:facet name="header">
            <h:panelGrid columns="2">
              <h:outputText value="#{}" />
              <h:graphicImage value="/images/roseTab.jpg" height="20" width="25" />

        <rich:tab header="#{dwRF4D1.result}">

A header attribute is used for each tab's display name. In the demo code, as usual, the header value is pulled from the resource bundle. Like Accordion Items, a tab can contain any kind of component. For the demo, I used resource bundle text for the Info tab content, and Collapsible Panels for the Result tab content.

As an alternative to the header attribute, you can use an <f:facet /> named "header" to include additional content. The demo code uses an <h:panelGrid /> containing text and an image for the Info tab header.

Whenever I see your smiling face

Collapsible Panel is a version 4.x replacement for Simple Toggle Panel. It consists of a bar and a content display, which can be any component (see Figure 6). Use the header attribute for the title. Clicking on the bar shows or hides the content, much like an Accordion with only one item. Listing 12 shows the demo project's Collapsible Panel markup:

Listing 12. RichFaces Collapsible Panel component
<h:panelGrid columns="1" width="50%">
  <rich:collapsiblePanel switchType="ajax" 
                         header="#{dwRF4D1.calComp} #{dwRF4D1.value}" 
                         expanded="false" >
  <rich:collapsiblePanel switchType="ajax" 
                         header="#{dwRF4D1.plComp} #{dwRF4D1.value}" 
                         expanded="false" >
  <rich:collapsiblePanel switchType="ajax" 
                         header="#{dwRF4D1.acComp} #{dwRF4D1.value}" 
                         expanded="false" >
  <rich:collapsiblePanel switchType="ajax" 
                         expanded="false" >
       <img src="images/myphoto.jpg" 
            height="80" width="64"/>

Notice that the switchType attribute makes a reappearance. client and server values are available in addition to the ajax value used in the code. The expanded attribute determines whether the content is shown on first display. For the demo, I've put several Collapsible Panels in a JSF <h:panelGrid />, which is placed in a Tab, which is placed in a Tab Panel.

Wrap it up

RichFaces provides a large number of JSF components for building RIAs and Ajax-enabled applications. This article has demonstrated only a few, but you should have gotten a feel for how things work under RichFaces, and seen several components that could be useful in many applications. With the introduction of version 4, Richfaces is now compatible with JSF 2 and includes simplifications and efficiencies you'll appreciate. An online demo of all of the components available in the suite, documentation, and other resources are available from the RichFaces project page (see Related topics).

If you choose to use RichFaces, I encourage you to dig deeply into the a4j: components and processing discussed in the documentation to understand how to apply the concepts to the other RichFaces components. The research time you invest will pay multiple dividends in your development process and run-time performance.

Downloadable resources

Related topics

Zone=Java development, Open source
ArticleTitle=Using RichFaces with JSF 2