Comparison of AJAX JSF Libraries Functionality and Interoperability

newjerseyshakySoftware and s/w Development

Oct 30, 2013 (3 years and 5 months ago)

718 views

MASARYK UNIVERSITY
FACULTY OF INFORMATICS

Comparison of AJAX JSF Libraries
Functionality and Interoperability
DIPLOMA THESIS
Bc.Pavol Pitoˇnák
Brno,June 2011
Declaration
Hereby I declare,that this paper is my original authorial work,which I have worked out by
my own.All sources,references and literature used or excerpted during elaboration of this
work are properly cited and listed in complete reference to the due source.
Bc.Pavol Pitoˇnák
Advisor:Mgr.Marek Grác
ii
Acknowledgement
I would like to thank my supervisor,Mgr.Marek Grác,my consultant,Ing.Jiˇrí Pechanec,
and RichFaces team,especially Lukáš Fryˇc,for their guidance and support throughout my
work on this thesis.
Many thanks also go to my family,girlfriend,and close friends who supported me while
working on this thesis.
iii
Abstract
This thesis compares functionality of four popular JavaServer Faces component libraries—
RichFaces,ICEfaces,OpenFaces,and PrimeFaces.This thesis demonstrates differences be-
tween them,highlights their unique features,and research their interoperability.A demo
application that would demonstrate interoperability of these libraries is created as a part of
the thesis.
iv
Keywords
Java Server Faces,JSF,RichFaces,ICEfaces,PrimeFaces,interoperability,web framework,
Rich Internet Applications
v
Contents
1 Introduction.........................................1
2 The JavaServer Faces Framework............................4
2.1 History of JavaServer Faces.............................4
2.2 Key Terms.......................................5
2.3 JSF Application....................................6
2.4 The Request Processing Lifecycle..........................8
2.5 The Navigation Model................................10
2.6 Managed Beans and Scopes.............................12
2.7 The Facelets ViewDeclaration Language.....................12
2.8 Composite Components...............................14
2.9 Resource Handling..................................15
2.10 Component Libraries.................................15
3 Ajax and Core Components................................18
3.1 Ajax in JSF 2 and in Component Libraries.....................18
3.2 Region.........................................20
3.3 Command Button and Command Link.......................21
3.4 JavaScript Function..................................21
3.5 Queue.........................................22
3.6 Status..........................................23
3.7 Poll...........................................25
3.8 Push..........................................25
4 Input Components.....................................29
4.1 Calendar........................................29
4.2 Inplace Inputs.....................................31
4.3 Autocomplete.....................................31
4.4 Slider..........................................34
4.5 Spinner.........................................35
4.6 File Upload.......................................37
5 Output Components....................................40
5.1 Progress Bar......................................40
5.2 Tree...........................................41
6 Panels.............................................46
6.1 Panels in RichFaces..................................46
6.2 Panels in PrimeFaces.................................48
6.3 Panels in OpenFaces.................................51
6.4 Panels in ICEfaces...................................52
7 Iteration Components...................................56
7.1 RichFaces Repeat,List and Data Grid........................57
7.2 RichFaces Data Table.................................58
vi
7.3 RichFaces Extended Data Table...........................60
7.4 RichFaces Data Scroller................................61
7.5 OpenFaces ForEach..................................63
7.6 OpenFaces Data Table................................63
7.7 PrimeFaces Data Grid................................69
7.8 PrimeFaces Data List.................................70
7.9 PrimeFaces Data Table................................71
7.10 ICEfaces Data Table..................................72
8 Charts.............................................75
8.1 Charts in PrimeFaces.................................75
8.2 Charts in OpenFaces.................................77
8.3 Charts in ICEfaces...................................79
9 Validation..........................................82
9.1 Faces Validation....................................82
9.2 Bean Validation....................................82
9.3 Client Side Validation.................................83
9.4 Cross-field Validation.................................84
9.5 Messages........................................85
9.6 Captcha.........................................86
10 Conclusion..........................................88
Bibliography..........................................91
A Sample Use of RichFaces Sub Table...........................93
B Sample Use of Sorting in RichFaces Table.......................94
C Metamer Screenshot....................................95
D Contents of Attached CD.................................96
vii
1 Introduction
Rich Internet Applications (RIA) became extremely popular in last couple of years.A Rich
Internet Application is a web application that has many of the characteristics of a desktop
application,typically delivered either by way of a site-specific browser,via a browser plu-
gin,independent sandboxes,or virtual machines.[1] The three most common platforms are
Adobe Flash,Microsoft Silverlight and Java.Although all these platforms are mature,stable
and widespread,their biggest disadvantage is that they all depend on plugins installed in
user’s web browser.
On the other hand,newweb standards such as HTML 5 are being developed in order to pro-
vide advanced features need by RIAs out-of-the-box.HTML 5 will contain newelements for
handling multimedia (video and audio),a canvas element and improved integration of SVG
content.Next,there are planned new semantic elements for page header,articles and sec-
tions.Several newAPIs are about to be introduced for offline storage database (also known
as Web Storage),drag-and-drop,geolocation,indexed database,an API for handling file
uploads and file manipulation,and many more.Although latest versions of most popu-
lar browsers,namely Google Chrome,Mozilla Firefox,Apple Safari and Microsoft Internet
Explorer support many HTML 5 features,it is expected to become a standard in 2014.[2]
Therefore,most of modern web frameworks uses a mixture of HTML 4 and some propri-
etary technologies such as Adobe Flash or Microsoft Silverlight.
In the Java world,there are several web frameworks and standards for creating rich internet
applications.In March 1998,the Java Servlet API was introduced.Prior to servlets,Java was
not widely used as a server-side technology for web applications.Unlike other proprietary
web server APIs,the Java Servlet API provided an object-oriented design approach and was
able to run on any platformwhere Java was supported.Since the Java Servlet API provided
a low-level handling of HTTP requests,it was tedious and error-prone to generate HTML,
e.g.:
1 out.println("<img id=\"cat\"src=\"cat.png\"/>");
Notice howthe quote symbols (”) have to be escaped.
Because of above-mentioned problems of the Java Servlet API,a new technology called
JavaServer Pages (JSP) was introduced.JSP was built on top of servlets and provided a sim-
pler solution to generating large amounts of dynamic HTML.JSP were using a mix of two
basic content forms,scriptlets and markup.Markup is typically HTML with some special
JSP tags,while scriptlets are blocks of Java code.When a page is requested,it is translated
into servlet code that is then compiled and immediately executed.Subsequent requests to
the same page simply invoke generated servlet for the page.Simple page might look like
this:
1 <%@ page errorPage="myerror.jsp"%>
1
1.INTRODUCTION
2 <%@ page import="com.foo.bar"%>
3 <html>
4 <body>
5 <%!int serverInstanceVariable = 1;%>
6 <% int localStackBasedVariable = 1;%>
7 <table>
8 <tr>
9 <td>
10 <%= toStringOrBlank("expanded inline data"+ 1 ) %>
11 </td>
12 </tr>
13 </table>
14...
The Java Platform,Enterprise Edition (J2EE,later renamed to JEE) contained both Servlet
API and JavaServer Pages right fromthe first version.
Although JSP was an improvement,it was not a complete solution.Developers used to use
a lot of Java code in JSPs making themhard to maintain.Thus,some separation of applica-
tion logic and viewwas needed.What was needed was an implementation of model-view-
controller design pattern.The model-view-controller (MVC) was first described in 1979 by
Trygve Reenskaug.[3] The MVC pattern separates the modeling of the domain,the presen-
tation,and the actions based on user input into three separate classes:[4]
 model—manages the behavior and data of the application domain,responds to re-
quests for information about its state (usually fromthe view),and responds to instruc-
tions to change state (usually fromthe controller);
 view—manages the display of information;and
 controller—interprets the mouse and keyboard inputs from the user,informing the
model and/or the viewto change as appropriate.
Because of above mentioned issues with JSP and the need of MVC,several web frame-
works were created.They could be divided into two major groups by a paradigmthey use–
request based (e.g.Struts or Stripes) and component based (e.g.Wicket,Tapestry,Google
Web Toolkit and JavaServer Faces).Arequest based framework basically gets user’s request,
then determines what the application should do and gives the response back to the user.On
the other hand,in a component based framework there is no clear sense of the flow from
front to back.The developer has to think not in actions but in components.JavaServer Faces
(JSF) is based on components but is somehowsimilar to request based frameworks.
Struts became one of the most dominant Java web frameworks and was donated to the
Apache Foundation in May 2000.Formerly located under the Apache Jakarta Project and
known as Jakarta Struts,it became a top level Apache project in 2005.According to Edward
Burns,[5] the Java Community Process (JCP) sawthe benefits that Struts offeredby explicitly
following the MVC approach.However,Struts lacked a robust way to handle the viewtier.
2
1.INTRODUCTION
To address this need,several leading software vendors,including Sun,Oracle,IBM,and
BEA,met through the JCP in 2001 and voted to proceed with a comprehensive and detailed
specification for building Java web applications.
JavaServer Faces became part of the Java EE in version 5 (May 2006).Since it contained only
few basic components,soon several component libraries with advanced features were cre-
ated.These libraries brought Ajax
1
support andvarious visual components such as calendar,
spinner,slider or advanced tables.Despite the fact that they all were built on top of a stan-
dard,they did not work together well,if at all.JEE 6 (December 2009) introduced JSF 2.0
which added many missing features.Since many developers wanted to use components
from several JSF libraries,JSF 2.0 were designed with interoperability in mind.However,
the JSF specification does not prescribe implementation details.The main goal of this thesis
is to compare functionality of three JSF open source component libraries (ICEfaces,Prime-
Faces,and OpenFaces) with RichFaces and find out how they inter-operate.Author of this
thesis works at Red Hat in RichFaces team.This work will help RichFaces team to under-
stand strengths and weaknesses of RichFaces components.
The work is divided into several chapters.The second chapter describes the history of
JavaServer Faces and new features of JSF 2.There are also above-mentioned component
libraries introduced.The following chapters describe functionality and interoperability of
various groups of components—Ajax,input,output,panels,charts and other components.
The last chapter describes validation of forms on the pages.It describes three different mech-
anisms for validation.
1.AJAX is an acronym for Asynchronous JavaScript and XML.In this work it will be referred to as “Ajax”
because this name is usual in JSF community.
3
2 The JavaServer Faces Framework
2.1 History of JavaServer Faces
JavaServer Faces is a standard component-oriented user interface (UI) framework for the
Java EE platform.JSF offers an ecosystem of portable UI component libraries and exten-
sions.JSF was created through the Java Community Process (JCP) by a group of technology
leaders.
The first version of JSF (1.0) was introduced in the first half of March 2004 as Java Specifi-
cation Request (JSR) 127
1
along with J2EE 1.4.After that,a revised version (1.1) was release
in late May 2004.JSF 1.1 was only a bug-fixing release,it did not contain any specification
changes nor HTML renderkit changes.The specification was led by Edward Burns (Oracle)
and Craig R.McClanahan (Sun Microsystems).The objective of the specification was to es-
tablish a standard API for creating Java web application GUIs which would eliminate the
burden of creating and maintaining GUI infrastructure for developers.The specification did
not have any dependency on specific operating systemnor CPUs.The API was created with
internationalization and localization in mind.
Two years later,JSF 1.2 was introduced as JSR-252
2
.The specification was released in May
2006 and after that,three reviewed versions were released (last in July 2008),all targeted the
J2EE 5.0 Platform.The specification was led by Edward Burns and Roger Kitain (both from
Oracle).JSF 1.2 was not a JSR for newfeatures.According to specification page,the primary
goal of the JSR was handling the Faces side of the JSP/Faces alignment issues addressed
in the parallel JSR-245 (JavaServer Pages 2.1).The specification contained also several sec-
ondary goals:
 enhancements to provide an interimsolution to the content-interweaving problemde-
scribed in article Improving JSF by Dumping JSP
3
;
 provide XML Schema for the config files,instead of using DTD;
 enhancements to allowfaces applications to handle multi-frame,or multi-windowUI
designs;
 enhancements to the f tag library for improved TCK coverage,<f:view> lifetime
events,and other small features;enhancements to the decorator support for API ob-
jects;
 security enhancements for client side state saving;
1.JSR-127,http://jcp.org/en/jsr/detail?id=127
2.JSR-252,http://jcp.org/en/jsr/detail?id=252
3.Improving JSF by Dumping JSP,http://www.onjava.com/pub/a/onjava/2004/06/09/jsf.html
4
2.THE JAVASERVER FACES FRAMEWORK
 solve the"duplicate button press"problem;
 re-organize the spec into normative,and non-normative sections,to make implemen-
tation easier;
 portlet related bug-fixes;and
 bug fixes that require minimal spec changes.
In July 2009 JavaServer Faces 2.0 specification was released.
4
The specification was led,
as JSF 1.2,by Edward Burns and Roger Kitain.Similarly to previous specifications,expert
group consisted of several individuals and companies,such as Oracle,Sun Microsystems,
Red Hat,Exadel,IBM,Apache Software Foundation and many other.Unlike JSF 1.2,2.0 was
a feature specification targeting the Java EE 6 Platform.According to specification page,
the JSR was about to bring the best ideas in web application development to the Java EE
platform.Specification should maximize the productivity of web application development
and minimize the complexity of maintenance of the web application during its production
lifetime.Another goal of the specification was to bring an easy to use API for Ajax.The tech-
nical details will be explained in following sections.This work will focus mainly on JSF 2.0
and upcoming versions.
JSF applications need a JSF implementation to run.There are two major implementations
of JSF:a reference implementation (also known as Mojarra) and Apache’s implementation
called MyFaces.All JEE 6 compliant application servers contain a JSF implementation,e.g.
GlassFish V3 contains Mojarra and JBoss AS 6 contains both Mojarra and MyFaces.
2.2 Key Terms
This section contains a list of key terms used in JSF as explained by Kito Mann in his book
JavaServer Faces in Action [6,p.39-40].
UI component is a stateful object,maintained on the server,that provides specific functional-
ity for interacting with an end user.UI components are JavaBeans with properties,methods,
and events.They are organized into a view,which is a tree of components usually displayed
as a page.
Renderer is responsible for displaying a UI component andtranslating a user’s input into the
component’s value.Renderers can be designed to work with one or more UI components,
and a UI component can be associated with many different renderers.
Validator is responsible for ensuring that the value entered by a user is acceptable.One or
more validators can be associated with a single UI component.
4.JSR-314,http://jcp.org/en/jsr/detail?id=314
5
2.THE JAVASERVER FACES FRAMEWORK
Backing beans (managed beans) are specialized JavaBeans that collect values fromUI com-
ponents and implement event listener methods.They can also hold references to UI compo-
nents.
Converter converts a component’s value to and froma string for display.A UI component
can be associated with a single converter.
JSF uses the JavaBeans event/listener model (also used by Swing).UI components (and
other objects) generate events,and listeners can be registered to handle those events.
Message is some information that is displayed back to the user.Just about any part of the
application (backing beans,validators,converters,and so on) can generate information or
error messages that can be displayed back to the user.
Navigation is the ability to move fromone page to the next.JSF has a powerful navigation
systemthat is integrated with specialized event listeners.
2.3 JSF Application
AJavaServer Faces application is like any other Java web application.Atypical JSF applica-
tion includes the following parts:[7,section 4]
 a set of web pages in which components are laid out;
 a set of tags to add components to the web page;
 a set of backing beans,which are JavaBeans
5
component that define properties and
functions for components on a page;
 a web deployment descriptor (web.xml file);
 optionally,one or more application configuration files,such as a faces–config.xml file,
which can be used to define page navigation rules and configure beans and other cus-
tomobjects,such as customcomponents;
 optionally,a set of customobjects,which can include customcomponents,validators,
converters,or listeners,created by the application developer;and
 a set of customtags for representing customobjects on the page.
Asimple web.xml descriptor might look like in the following code snippet where two URL
patterns are mapped to Faces servlet.When running JSF 2.0 on a Servlet 3.0 container,the
web.xml is optional.If no web.xml is found,the Faces Controller servlet is automatically
mapped to the most popular URL patterns:/faces/*,*.jsf,and *.faces.[5,p.9]
5.JavaBeans,http://download.oracle.com/javase/tutorial/javabeans/index.html
6
2.THE JAVASERVER FACES FRAMEWORK
1 <?xml version="1.0"encoding="UTF-8"?>
2 <web-app version="2.5"xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/
xml/ns/javaee/web-app_2_5.xsd">
5 <display-name>Foo Application</display-name>
6 <context-param>
7 <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
8 <param-value>.xhtml</param-value>
9 </context-param>
10 <servlet>
11 <servlet-name>Faces Servlet</servlet-name>
12 <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
13 <load-on-startup>1</load-on-startup>
14 </servlet>
15 <servlet-mapping>
16 <servlet-name>Faces Servlet</servlet-name>
17 <url-pattern>/faces/
*
</url-pattern>
18 </servlet-mapping>
19 <servlet-mapping>
20 <servlet-name>Faces Servlet</servlet-name>
21 <url-pattern>
*
.jsf</url-pattern>
22 </servlet-mapping>
23 <welcome-file-list>
24 <welcome-file>faces/index.xhtml</welcome-file>
25 </welcome-file-list>
26 </web-app>
Example of faces-config.xml:
1 <?xml version="1.0"encoding="UTF-8"?>
2 <faces-config version="2.0"xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:xi="http://www.w3.org/2001/XInclude"xmlns:xsi="http://www.w3.org
/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/
xml/ns/javaee/web-facesconfig_2_0.xsd">
5 <application>
6 <locale-config>
7 <default-locale>en</default-locale>
8 <supported-locale>en</supported-locale>
9 </locale-config>
10 <message-bundle>com.pitonak.foo.messages</message-bundle>
11 </application>
12 </faces-config>F
Both web.xml and faces-config.xml are located in WEB-INF directory.Once a JSF application
is properly configured,XHTML pages can be constructed (notice the mixture of HTML and
JSF tags).Here is example index.xhtml:
1 <html xmlns="http://www.w3.org/1999/xhtml"
2 xmlns:h="http://java.sun.com/jsf/html">
3 <h:head/>
4 <h:body>
7
2.THE JAVASERVER FACES FRAMEWORK
5 <h:form>
6 name:<h:inputText value="#{fooBean.name}"/> <br/>
7 Hello <h:outputText value="#{fooBean.name}"/>!<br/>
8 <h:commandButton value="Greet"/>
9 </h:form>
10 </h:body>
11 </h:head>
Avery minimalist managed bean might look as follows:
1 package com.pitonak.foo;
2 import javax.faces.bean.ManagedBean;
3 import javax.faces.bean.SessionScoped;
4
5 @ManagedBean
6 @SessionScoped
7 public class FooBean {
8 private String name;
9
10 public String getName() {
11 return name;
12 }
13
14 public void setName(String name) {
15 this.name = name;
16 }
17 }
2.4 The Request Processing Lifecycle
In the example presented in last section,a managed bean FooBean is named fooBean.Its
getter and setter methods are called using the Unified Expression Language.[7,section 6].
JSF creates and manages a server-side component tree in memory that directly corresponds
to the components included in a page.[5,p.10]
Figure 2.1:JSF component tree
8
2.THE JAVASERVER FACES FRAMEWORK
Common tasks,such as handling incoming requests,decoding parameters,modifying and
saving state,and rendering web pages to the browser are all performed during a web ap-
plication lifecycle.By default,JavaServer Faces automatically handles most of the lifecycle
actions for a developer.However,it also exposes the various stages of the request lifecycle,
so that developer can modify or perform different actions if his application requirements
warrant it.[7,section 4]
The lifecycle of a JavaServer Faces application starts and ends with the following activity:
the client makes a request for the web page,and the server responds with the page.The
whole request processing lifecycle is more complicated.JavaServer Faces goes through sev-
eral phases when it processes a single incoming request:[6,p.59]
 Restore View—finds or creates a tree of components for the selected view;some com-
ponents,like HtmlCommandButton,will generate action events (or other types of
events) in this phase;
 Apply Request Values—updates the value of the components to equal ones sent in the
request,optionally using converters;adds conversion errors if there is an error and
also generates events fromrequest parameters;
 Process Validations—asks each component to validate itself (which may include using
external validators);validation error messages may be reported;
 Update Model Values—updates all the values of backing beans or model objects asso-
ciated with components;conversion error messages may be reported;
 Invoke Application—calls any registered action listeners;the default action listener
will also execute action methods referenced by command components and choose the
next viewto be displayed;and
 Render Response—displays the selected view using the current display technology
(like JSP).
For the initial request,only the view is built which means that only phases Restore View,
Invoke Application and Render Response are invoked.For subsequent (postback) requests,
some or all other phases are invoked.In chapter 3 some advanced techniques for limiting
the request processing lifecycle will be explained.
When the application fromprevious section is built and deployed to an application server,
the application is in an uninitiated state.When a client makes an initial request for in-
dex.xhtml web page,the Facelets application is compiled (see section The Facelets View
Declaration Language).The compiled Facelets application is executed and a new compo-
nent tree is constructed for the application and is placed in a FacesContext.The compo-
nent tree is populated with the component and the backing bean property associated with it.
Then a newviewis built and rendered to the requesting client as a response.The component
tree is destroyed automatically.On subsequent requests,the component tree is rebuilt and
9
2.THE JAVASERVER FACES FRAMEWORK
Figure 2.2:Initial request vs.usual postback request
the saved state is applied to it.
2.5 The Navigation Model
Navigation happens in a web application when a user tries to switch from one page to
another page.There are several ways howto navigate on the web application:
1.submitting a formand invoking an action method;
2.clicking a hyperlink;or
3.directly entering the target URL of a page into a browser.
Whatever be the case,the next page to be displayed or the response for the current page
has to be handled by the web application.The navigation outcome is result of an action
method.
In JSF 1.x all navigation cases had to be configured in faces-config.xml.For example,when
navigating frompage1 to page2 in response to a “success” outcome on a command compo-
10
2.THE JAVASERVER FACES FRAMEWORK
nent in page1 required the following XML boilerplate code:[8]
1 <navigation-rule>
2 <from-view-id>/page1.xhtml</from-view-id>
3 <navigation-case>
4 <from-outcome>success</from-outcome>
5 <to-view-id>/page2.xhtml</to-view-id>
6 </navigation-case>
7 </navigation-rule>
The URL of the resulting page will be concatenation of context root,context path,Faces
servlet mapping,and view ID,e.g.for the sample above the URL of the page might be
http://localhost:8080/myapp/faces/page2.xhtml.
JSF 2.0 introduced a simplification called implicit navigation that reduces the size of faces-
config.xml.If no matching navigation case is found,the navigation handler checks to see
whether the outcome of action corresponds to a viewID.It is possible to use absolute path
to the page (/page2.xhtml),relative path to the page (page2.xhtml) or even the ID of the
view(page2).The sample action method called frompage1 resulting in navigation to page2
might look like this:
1 public String fooAction() {
2//some business logic
3 return"page2";
4 }
Another enhancement to the navigation subsystem is conditional navigation.It is possible
to use expression language in pre-conditions that must be met in order for the navigation
case to be accepted:
1 <navigation-rule>
2 <from-view-id>/page1.xhtml</from-view-id>
3 <navigation-case>
4 <from-outcome>success</from-outcome>
5 <to-view-id>/page2.xhtml</to-view-id>
6 <if>#{bean.fooCondition}</if>
7 </navigation-case>
8 </navigation-rule>
One of drawbacks of JSF navigation is that it uses strings for outcomes.Apache MyFaces Ex-
tensions project (CODI),inspired by Tapestry,brings type-safe navigation to the JSF 2 (using
Contexts and Dependency Injection,JSR-299).Another implementation is SeamFaces.It is
probable that type-safe navigation will be addressed in future version of JSF specification.
There has to be a new class defined for each view and the action method returns a Class
object instead of string:
1 public Class fooAction() {
2//some business logic
3 return Page2.class;
4 }
11
2.THE JAVASERVER FACES FRAMEWORK
2.6 Managed Beans and Scopes
Model objects in JSF are called managed beans.Section 2.3 showed how to define and use
a simple managed bean.Managed beans are accessed from XHTML pages using Unified
Expression Language (EL).
6
Any time user references a bean,Managed Bean Creation facil-
ity creates the bean,initializes it,and stores it in the proper application scope if it does not
already exist.If the bean already exists,it is returned.[6,p.110]
In JSF 1.x,it was necessary to configure managed beans in the faces-config.xml:
1 <managed-bean>
2 <managed-bean-name>fooBean</managed-bean-name>
3 <managed-bean-class>com.pitonak.foo.FooBean</managed-bean-class>
4 <managed-bean-scope>session</managed-bean-scope>
5 </managed-bean>
In JSF 2 it is possible to configure managed beans directly in code using annotations,for
example see section 2.3.
In JSF 2 it is possible to use the following scopes:
 request—variables are available only during the current request;
 flash—variables survive a single viewtransition,including surviving redirects;
 view—variables are preserved until the user finishes interaction with the current view;
 session—variables are available for during of user’s HTTP session;
 application—variables are available for the entire life of the application;and
 custom—a scope defined by the user using EL expression instead of a keyword.
Even though newscopes were added to JSF 2 (flash and view),it is still missing some com-
monly used scopes such as conversation known fromJBoss SeamFramework.In Java EE 6 a
newstandard was created - Contexts and Dependency Injection (CDI,JSR-299).CDI defines
four built-in scopes:request,session,application,and conversation.
7
It is recommended to
use CDI for creating JSF 2 applications.
2.7 The Facelets ViewDeclaration Language
When JSF was created,JSP was about to be reused as it was already a standard in the web
community.The idea was to simplify the adoption of JSF by using a familiar tag language.
6.Expression Language,http://java.sun.com/products/jsp/reference/techart/unifiedEL.
html
7.CDI scopes,http://docs.jboss.org/weld/reference/1.1.0.Final/en-US/html/
scopescontexts.html
12
2.THE JAVASERVER FACES FRAMEWORK
Unfortunately,JSP and JSF do not naturally complement each other.JSP is not suitable for
creating component trees.Its elements are processed in a page from top to bottom with
the basic objective of creating a response to a request.On the other hand,JSF has a more
complex life cycle,and thus mixing JSP and JSF tags in pages causes problems.Consider the
following example:
1 <h:panelGroup>
2 <h:outputText value="first"/>
3 second
4 </h:panelGroup>
In the example above,JSF tags (h:panelGroups and h:outputText) are mixed with JSP
fragments (free text).This causes that the output of the example will be reversed:[9,p.67-
68]
1 second
2 first
This is one of reasons why several view definition languages,such as Apache Shale’s Clay,
JSFTemplating or Facelets,were created.Bruno Aranda and Zubin Wadia describe Facelets
as a templating language developed from the ground up with JavaServer Faces in mind.
[10,foreword] Facelets is founded on the idea of compositions.This means that a compo-
nent tree can be defined in multiple Facelet pages.A simple template can look like this
(template.xhtml):
1 <html xmlns="http://www.w3.org/1999/xhtml"...>
2 <head>
3 <title><ui:insert name="title">Default title</ui:insert></title>
4 <ui:insert name="head"/>
5 </head>
6 <body>
7 <ui:insert name="body">
8 <p>Body of the page.</p>
9 </ui:insert>
10 </body>
11 </html>
Page using the defined template will then look like this (index.xhtml):
1 <html xmlns="http://www.w3.org/1999/xhtml"...>
2 <body>
3 <ui:composition template="/template.xhtml">
4 <ui:define name="title">Main page</ui:define>
5 <ui:define name="body">
6 some content
7 </ui:define>
8 </ui:composition>
9 </body>
10 </html>
13
2.THE JAVASERVER FACES FRAMEWORK
JSF 2.0 recognizes the need for a standard alternative to JSP.JSF 2 introduced a generic
foundation for integrating view declaration languages into the JSF runtime environment—
the view declaration language API.This API allows framework authors to define their
own viewdeclaration languages and integrate these with JSF in a standard way.Moreover,
Facelets became part of JSF 2.0 as default declaration language implementation.This 2.0 ver-
sion of Facelets ought be very familiar to anyone who has been using Facelets 1.x.Most of
the 1.x APIs are present,though there has been some tweaking/repackaging as part of the
standardization process.[8]
2.8 Composite Components
Creating a customcomponent in JSF is quite complicated process.In the worst case,a com-
ponent class has to be created,with a lot of attributes with special getters and setters that
interacts with StateHelper,renderer-specific class that contains similar attributes for pa-
rameters related to HTML and defines JSF behavior events for them.A renderer class that
generates HTMLcode using spaghetti of startElement/writeAttribute/writeText
/endElement calls has to be created as well.Everything has to be described in the faces-
config.xml and Facelets taglib.xml has to be created.[11] RichFaces uses special Component
Development Kit (CDK) that simplifies development of customcomponents and lets devel-
opers to concentrate on component functionality only.
Even though RichFaces CDKis a powerful tool,it is too complicated for simple components.
JSF 2 greatly simplifies customcomponent development with the introduction of the “com-
posite component” feature.[8].A simple “Hello world” component could be implemented
with a single file with no Java code required (hello.xhtml):
1 <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
2"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml"
4 xmlns:h="http://java.sun.com/jsf/html"
5 xmlns:composite="http://java.sun.com/jsf/composite">
6 <h:body>
7
8 <composite:interface>
9 <composite:attribute name="who"/>
10 </composite:interface>
11
12 <composite:implementation>
13 <h:outputText value="Hello,#{cc.attrs.who}!"/>
14 </composite:implementation>
15
16 </h:body>
17 </html>
This is howthe component would be used on a page:
14
2.THE JAVASERVER FACES FRAMEWORK
1 <html xmlns="http://www.w3.org/1999/xhtml"
2 xmlns:h="http://java.sun.com/jsf/html"
3 xmlns:greet="http://java.sun.com/jsf/composite/greet">
4 <h:head/>
5 <h:body>
6 <greet:hello who="World"/>
7 </h:body>
8 </html>
2.9 Resource Handling
Before JSF 2 each component library loaded resources (images,JavaScript files,style sheets,
etc.) in its own way.JSF 2 provides a standard solution to resource loading with the intro-
duction of the resource handler API.The ResourceHandler is responsible for serving up
resources fromwell-knownlocations onthe class path.Resource requests are routedthrough
the FacesServlet,which passes these request onto the ResourceHandler for process-
ing.This solution allows components and their resource dependencies to be bundled in the
same jar file with no need for a bonus servlet,servlet filter or phase listener to serve up these
artifacts.In order to support resource relocation,JSF 2 introduces two newtags:<h:head>
and <h:body>.These components render the HTML head/body markup and also provide
a target for relocatable resources.[8]
2.10 Component Libraries
JSF provides a basic set of components for creating web pages such as inputs,outputs,ta-
bles,etc.However,modern web applications require more advanced components,such as
inplace inputs,tables with sortable columns,pagination in tables,various menus and pan-
els,progress bars,charts and more.This is a reason why many components libraries were
created.This thesis will describe four open source libraries—RichFaces,PrimeFaces,Open-
Faces,and ICEfaces.
RichFaces
RichFaces is a JSF component framework containing tens of advanced visual and non-visual
components.JSF 2’s <f:ajax> tag was inspired by RichFaces <a4j:support> tag which
will be describedin detail in section 3.1.RichFaces is a project createdby Alexander Smirnov.
In 2005,Smirnov was hired by Exadel and continued to develop the framework (then called
Ajax4jsf).In 2007 Red Hat and Exadel signed a partnership agreement.RichFaces were open
sourced under the GNU Lesser General Public License,version 2.1 and became a JBoss.org
project.
15
2.THE JAVASERVER FACES FRAMEWORK
The main features of RichFaces include advanced Ajax components,many visual compo-
nent,strong skinning support,client side validation and a component development kit
(CDK).In the sample application developed for this thesis (will be described later),version
4.1.0-SNAPSHOT of RichFaces is used.Unlike RichFaces 3,client-side code in RichFaces 4
is implemented in jQuery only.RichFaces 4 support this environments:
 Java Development Kit (JDK) 1.5 or higher;
 an application server compliant with JEE6,such as JBoss Application Server 6 or Glass-
fish 3;
 servlet containers Tomcat 6 or 7;
 Google App Engine;
 JSF 2 implementation such as Mojarra 2.0.4 or Apache MyFaces 2.0.4;and
 web browser such as Google Chrome 11,Firefox 3.6,or Internet Explorer 8.
PrimeFaces
PrimeFaces is a lightweight open source (Apache License v2) component suite for JSF 2 fea-
turing more than 100 of JSF components.Additional PrimeFaces Mobile module features a
UI kit for developing mobile web applications.However,development of mobile web ap-
plications is out of the scope of this work and therefore this part of PrimeFaces will not
be described.PrimeFaces is maintained by Prime Technology,a Turkish software develop-
ment company specialized in agile consulting,JSF,Java EE and outsourcing.Project is led
by Ça˘gatay Çivici.The sample application uses PrimeFaces 2.2.1 which support similar en-
vironments as RichFaces.
OpenFaces
OpenFaces is an open-source library of Ajax-powered JSF components,an Ajax framework
and a client-side validation framework.OpenFaces is based on the set of JSF components
formerly known as QuipuKit.It contains fully revised codebase of QuipuKit and intro-
duces many new components and features.OpenFaces is distributed under a dual license
model.Users can choose between using the library under GNU Lesser General Public Li-
cense v2.1 or purchasing a commercial license.OpenFaces is contributed and administered
by TeamDev Ltd,and Ukrainian company providing Java development services.The sam-
ple application uses OpenFaces 3.0 which supports very similar environments as Rich-
Faces.
16
2.THE JAVASERVER FACES FRAMEWORK
ICEfaces
ICEfaces 2 is an open source (Mozilla Public License) rich Internet application development
framework based on the JavaServer Faces 2 standard.Like its predecessor,ICEfaces 1.8,
ICEfaces 2 extends JSF to simplify development and enhance the standard JSF feature set—
simultaneously improving developer efficiency and expanding the spectrumof RIAcapabil-
ities that can be included in any JSF-based web application.Adhering closely to the standard
JSF 2 extension points allows ICEfaces to work transparently with the stock JSF framework,
simplifying integration and fostering 3rd party compatibility with other JSF 2-compliant
libraries.
The two most significant features of ICEfaces 2 are automatic Ajax with Direct-to-DOMren-
dering and Ajax Push (see chapter 3).ICEfaces 2 contains three sets of components:
1.ICEfaces Components—original components from ICEfaces 1.8 using a compatibility
layer that enables themto work with JSF 2;
2.ICEfaces Advanced Components—using all the features of the JSF 2 standard and are
based on a newAdvanced Component Environment;and
3.ICEfaces Enterprise Components—derived from ICEfaces 1.8 composite components
but ported to Facelets,these components are available only in ICEfaces 2 Enterprise
Edition.
Since this thesis deals only with freely available open source components,the ICEfaces
Enterprise Components will not be compared.The sample application uses ICEfaces 2.0.2
which runs on JBoss AS 6,Glassfish 3.1 and all modern web browsers.Moreover,it runs in
Liferay Portal 5.2.3.[12]
There are many other open source JSF component libraries.In 2006 Oracle donated its Ora-
cle ADF Faces to the Apache Software Foundation which became MyFaces Trinidad.Other
examples are MyFaces Tobago (donated by Atanion GmbH) and MyFaces Tomahawk.There
are also many proprietary technologies built on JSF,such as IBM’s XPages.Though,all these
technologies are out of the scope of this work.
17
3 Ajax and Core Components
3.1 Ajax in JSF 2 and in Component Libraries
One of major additions to the JSF 2 is standard Ajax support.In JSF 1.2 every compo-
nent framework implemented Ajax in it own style.On the client side,JSF 2 exposes a new
JavaScript API that issues an Ajax request back to the current view.Once the request enters
the Faces lifecycle,the state of the Ajax request is captured via the PartialViewContext.
This object provides access to information such as which components are targeted for pro-
cessing/rendering.The PartialViewContext’s processPartial() method uses this
information to performpartial subtree processing/rendering.When the rendered response
is sent back to the client,the callback previously provided by jsf.ajax.request() is
invoked.This callback automatically updates the client-side DOMto reflect the newly ren-
dered markup.[8]
The jsf.ajax.request() JavaScript API is targeted for use by frameworks as well as
by the JSF implementation itself.JSF 2 also includes a declarative approach using the new
<f:ajax> tag.The tag was inspired by tag <a4j:support> tag fromRichFaces 3:
1 <h:form>
2 <h:inputText id="input"value="#{bean.text}">
3 <a4j:support event="keyup"process="input"reRender="output"/>
4 </h:inputText>
5 <h:outputText id="output"value="#{bean.text}"/>
6 </h:form>
1 <h:form>
2 <h:inputText id="input"value="#{bean.text}">
3 <f:ajax event="keyup"execute="input"render="output"/>
4 </h:inputText>
5 <h:outputText id="output"value="#{bean.text}"/>
6 </h:form>
The first sample demonstrates the use of RichFaces 3 <a4j:support> tag.When a user
starts typing into input,pressed keys are sent by Ajax to the server,bean is updated and
then output is rerendered.Attribute execute says the server which data should be process
and attribute reRender says the client which parts of the page should be rerendered.The
second sample does exactly the same but it uses JSF 2 to send Ajax request.Since it was
inspired by RichFaces 3,the usage is almost the same.
RichFaces 4 comes with its own tag,<a4j:ajax>,which is based on f:ajax but upgrades
the tag with more features and advanced functionality.It originates in <a4j:support> but
was greatly refactored in order to be similar to <f:ajax>.The previous example written
using RichFaces 4 would look very similarly:
1 <h:form>
18
3.AJAX AND CORE COMPONENTS
2 <h:inputText id="input"value="#{bean.text}">
3 <a4j:ajax event="keyup"execute="input"render="output"/>
4 </h:inputText>
5 <h:outputText id="output"value="#{bean.text}"/>
6 </h:form>
Max Katz describes non-standard features of <a4j:ajax>.[13] First of all,EL expressions
in render and execute attributes are evaluated differently and <a4j:ajax> accepts a
special keyword @region which instructs the application to execute/render only <a4j:
region>.Secondly,it adds newevent handlers:
 onbegin—JavaScript to execute before Ajax request;
 onbeforedomupdate—JavaScript to execute after response comes back but before any
DOMupdate;and
 oncomplete—JavaScript to execute after response comes back but before any DOM
update.
Last but not least important attribute is bypassUpdate which,if set to true,skips Update
Model and Invoke Application phases which is useful for formvalidation.
PrimeFaces contain <p:ajax> tag that is very similar to RichFaces’ <a4j:ajax>.How-
ever,there are some little differences.First,<p:ajax> has attribute process instead of
standard execute and attribute update instead of standard render.PrimeFaces’ Ajax tag
has additional event handlers similar to those in <a4j:ajax>—onstart,oncomplete,
and onsuccess.
OpenFaces contain their own tag for Ajax,too.Similarly to RichFaces andPrimeFaces,it con-
tains additional event handlers onajaxstart and onajaxend.Moreover,it has attribute
delay that reduces the number of Ajax requests by skipping the frequently-happening
events.This attribute specifies the delay in milliseconds that should elapse after an event
that activates this component to start an actual request for reloading components (and in-
voking an appropriate action if specified).If there will be another event during this delay,
this event will postpone the request according to the specified delay instead of performing
an additional request.As a result there will be only one request for all events that come more
frequently than specified in this attribute.Exactly the same behavior can be implemented in
RichFaces by using queues (see section 3.5).Another interesting feature of <o:ajax> is its
attribute for which allows attaching Ajax component to an arbitrary component or HTML
tag instead of attaching to the parent component.The sample above might look in Open-
Faces as follows:
1 <h:form>
2 <h:inputText id="input"value="#{bean.text}"/>
3 <o:ajax for=":input"event="keyup"execute="input"render="output"/>
4 <h:outputText id="output"value="#{bean.text}"/>
5 </h:form>
19
3.AJAX AND CORE COMPONENTS
ICEfaces use a very different approach to Ajax called automatic Ajax.ICEfaces Automatic
Ajax feature guarantees minimal page updates under any condition,and does not require
the page developer to consider how,when or why page updates occur.The key to Automatic
Ajax is the use of Direct-to-DOM(D2D) rendering in the ICEfaces framework.D2Ddoes just
what it says,and writes the output of the JSF rendering phase into a server-side DOMthat
represents exactly what the client DOMneeds be.Using a cached version of the DOM,the
framework calculates precisely the set of DOMupdates required to affect the changes in the
page at the completion of any JSF lifecycle.[14,section Automatic Ajax]
Although the D2Dhandles the page updating aspect,it is still necessary to initiate the whole
process through some UI event.ICEfaces provides the Single Submit features,which causes
a component to submit itself automatically when the user interacts with it.
1 <h:form>
2 <icecore:singleSubmit/>
3 <h:inputText id="myinput"value="#{bean.input}"/>
4 output:<h:outputText id="output"value="#{bean.input}"/>
5 </h:form>
On one hand,the automatic Ajax feature optimizes the development time but on the other
hand,there is some overhead as it is necessary to render the entire page to produce the DOM
for comparison.This can be optimized by using <f:ajax> tag with redefined attribute
render.
1 <h:form>
2 <icecore:singleSubmit/>
3 <h:inputText id="myinput"value="#{bean.input}">
4 <f:ajax execute="@this"render="output"/>
5 </h:inputText>
6 output:<h:outputText id="output"value="#{bean.input}"/>
7 </h:form>
More information about both automatic Ajax and Direct-to-DOMrendering can be found in
ICEfaces documentation.[14,section Direct-to-DOM]
3.2 Region
RichFaces contain an <a4j:region> component which specifies a part of the JSF compo-
nent tree to be processed on the server.The region causes all the a4j and rich Ajax controls
to execute:decoding,validating,and updating the model.The region causes these compo-
nents to execute even if not explicitly declared.As such,processing areas can more eas-
ily be marked using a declarative approach.Regions can be nested,in which case only
the parent region of the component initiating the request will be processed.[15,section
a4j:region]
20
3.AJAX AND CORE COMPONENTS
There is no region component in other component libraries.However,because of ICEfaces’
automatic Ajax and Direct-to-DOMrendering,it is not needed when using ICEfaces.
3.3 Command Button and Command Link
RichFaces <a4j:commandButton> and <a4j:commandLink> components are similar to
the JavaServer Faces <h:commandButton> and <h:commandLink> components,but ad-
ditionally include Ajax support.All extra attributes from <a4j:ajax>,e.g.onbegin or
bypassUpdates,are also available in command button and command link.
Similarly to RichFaces,PrimeFaces command button and command link are very similar
to standard JSF button and link but add advanced features that are available also in the
component <p:ajax>.What is unique comparing to RichFaces,<p:commandButton>and
<p:commandLink> have attribute ajax which specifies submit mode—when set to true
(default),submit would be made with Ajax.
OpenFaces link extends standard JSF link,too,and add some features from <o:ajax>.
OpenFaces’ button is more advanced because it supports child elements inside and so it
is possible to create graphical images with text:
1 <o:commandButton action="#{fooBean.bar}"...>
2 <h:graphicImage url="..."/>
3 <h:outputText value="..."/>
4 </o:commandButton>
ICEfaces contain command button and command link component that are very similar to
those in RichFaces.
Figure 3.1:Command button in RichFaces,PrimeFaces,OpenFaces,and ICEfaces
3.4 JavaScript Function
If a user need to fire an Ajax request from his JavaScript function,it is possible to directly
call jsf.ajax.request(),RichFaces.ajax() or similar functions from PrimeFaces
and OpenFaces.However,this approach is error prone and therefore RichFaces contains the
component <a4j:jsFunction> which performs Ajax requests directly from JavaScript
code and retrieves server-side data.The server-side data is returned in JavaScript Object
21
3.AJAX AND CORE COMPONENTS
Notation (JSON) format prior to the execution of any JavaScript code defined using the
oncomplete attribute.
1 <a4j:jsFunction name="updateName"render="showname">
2 <a4j:param name="name"assignTo="#{functionBean.text}"/>
3 </a4j:jsFunction>
4
5 <span onmouseover="updateName(’Kate’)"onmouseout="updateName(’’)">
6 Kate
7 </span>
8 <h:outputText id="showname"value="#{functionBean.text}"/>
OpenFaces’ component <o:ajax> has attribute standalone which behaves similarly to
<a4j:jsFunction>.In is used in this way:
1 <h:form id="form">
2 <h:inputText id="textField"
3 onkeypress="O$(’form:updateImage’).run()".../>
4 <o:ajax id="updateImage"standalone="true"render="dynamicImage"
5 execute="textField colorField fontSizeField"requestDelay="500"/>
6 <o:dynamicImage id="dynamicImage".../>
7 </h:form>
There is not any similar component in PrimeFaces nor ICEfaces.
3.5 Queue
JSF 2 has very basic queue functionality—requests are queued and fired one at a time.This
means that only one request is processed on the server at a time.Since it is a very simple
queue,RichFaces implemented a much more sophisticated queue.The component <a4j
:queue> provides additional options for a finer control of request processing.It works
in the same basic way as the standard JSF queue.It can be enabled and disabled through
the enabled attribute.Attribute requestDelay adds a delay between each request in the
queue.Delaying requests avoids unnecessary processing for actions that would otherwise
cause multiple requests,such as typing.Similar requests in the queue are combined while
waiting for the request delay.The user ought be aware of the fact that the component does
not handle standard JSF requests or requests from component libraries other than Rich-
Faces.[15,section a4j:queue]
RichFaces contains behavior <a4j:attachQueue> which is usedtogether with component
<a4j:queue> to further customize queuing for particular components and behaviors.The
<a4j:attachQueue> behavior can override the scope-wide queue settings for an individ-
ual component,or attach specific requests to a queue.
1 <a4j:queue requestDelay="2000"/>
2
3 <h:form>
22
3.AJAX AND CORE COMPONENTS
4 <h:inputText>
5 <a4j:ajax event="keyup"/>
6 </h:inputText>
7 <a4j:commandButton value="submit">
8 <a4j:attachQueue requestDelay="0"/>
9 </a4j:commandButton>
10 </h:form>
PrimeFaces do not have any queue component.In OpenFaces,it is possible to set attribute
delay of <o:ajax> which has similar functionality.
3.6 Status
Users of a web page usually want to know the status of latest action they triggered.This is
the place where status component is useful.RichFaces contain a highly customizable com-
ponent <a4j:status> which can be in three states:
 progress—during the execution of an Ajax request;
 complete—after an Ajax request completed successfully;or
 error—after and Ajax request completed with an error.
It is possible to define start text,stop text and error text.User can choose whether compo-
nent’s attributes or facets will be used.
1 <a4j:status id="status1"startText="Work in progress..."
2 stopText="Complete"errorText="Error">
3
4 <a4j:status id="status2">
5 <f:facet name="start">
6 <h:graphicImage value="/images/ai.gif"alt="ai"/>
7 </f:facet>
8 <f:facet name="stop">...</f:facet>
9 <f:facet name="error">...</f:facet>
10 </a4j:status>
The <a4j:status> component monitors the status of the region relevant to where it is
placed.If it is unnamed and placed outside any forms,it monitors the status at the view
level.If unnamed and placed inside a form,it monitors the status at the form level.[15,
section a4j:status]
PrimeFaces contains a similar component called <p:ajaxStatus>.Unlike RichFaces’ sta-
tus,it is not possible to define start text,stop text,etc.using attributes.On the other hand,
it has more facets so it is possible to customize the component a bit better.Its list of facets
include prestart,start,complete,error,and success.Similarly to <a4j:status>,
it is possible to define whichever markup the user needs in facets.
23
3.AJAX AND CORE COMPONENTS
In OpenFaces,the status of current request is handled in different way.When any Ajax
request is in progress,the “Loading...” message with and animated image appear in the
upper-right corner of the screen.This message is displayed by default.It is possible to con-
figure this message for the whole application or for the particular page.The user can change
the Ajax progress message for the whole application by specifying the org.openfaces.
ajaxMessageHTML parameter in web.xml.This parameter should be specified as portion
of HTML that will be shown in the upper-right corner on an Ajax request.[16,section Ajax
Settings Component]
1 <context-param>
2 <param-name>org.openfaces.ajaxMessageHTML</param-name>
3 <param-value><![CDATA[
4 <div style="background:white;font:Tahoma 15pt normal;border:1px solid
black;">
5 <img src="/resources/images/progress.gif"/>
6 Ajax request is currently in progress!
7 </div>
8 ]]></param-value>
9 </context-param>
When the user needs to change the status only for a particular page,the progressMessage
facet of the <o:ajaxSettings> tag which accepts tag <o:defaultProgressMessage>
should be used.It provides many options for customization,such as text,image URL,align-
ment,transparency and many more.It is also possible to define mode which tells OpenFaces
whether to display message for all Ajax requests or only for those fired by OpenFaces com-
ponents.Sample configuration would look like this:
1 <o:ajaxSettings>
2 <f:facet name="progressMessage">
3 <o:defaultProgressMessage text="..."imageUrl="..."
4 mode="..."transparency="...">
5 </f:facet>
6 </o:ajaxSettings>
RichFaces and OpenFaces interoperate in this field very nice.When an OpenFaces compo-
nent fires an Ajax request,RichFaces’ status component shows the progress and vice versa.
PrimeFaces status,unlike RichFaces and OpenFaces,can handle only requests fromPrime-
Faces components.RichFaces and OpenFaces cannot handle PrimeFaces requests,too.
The <a4j:status> components cannot be present on the page when using ICEfaces.Oth-
erwise,the Ajax request is fired and the page is updated but the <a4j:status> never
shows the end of request.This causes that all subsequent requests are blocked.
There is the <ice:outputConnectionStatus> component that shows the progress of
an Ajax request.However,it does not work for standard JSF requests,only those made by
ICEfaces automatic Ajax.If no attributes are set,an image is displayed in each state.
1 <link rel="stylesheet"type="text/css"
2 href="./xmlhttp/css/xp/xp.css"/>
24
3.AJAX AND CORE COMPONENTS
3 <ice:outputConnectionStatus/>
Figure 3.2:ICEfaces status in all states in two themes
3.7 Poll
Poll is a component that has the ability to send periodical Ajax requests and execute action
listener on a JSF managed bean.RichFaces poll has all standard Ajax attributes,such as
onbegin,render,execute,etc.,but the most important attribute is interval which is
poll-specific.It specifies the time in milliseconds between requests.
There is a very similar component in PrimeFaces.It also defines attributes usual for Prime-
Faces components firing Ajax requests.The most noticeable difference fromRichFaces poll
is that attribute interval accepts an integer expressing the number of seconds,not millisec-
onds.
There is no component with similar functionality in OpenFaces.ICEfaces contain poll com-
ponent only in Enterprise Edition.
3.8 Push
The push component performs real-time updates on the client side from events raised at
the server side,e.g.displaying new messages in a chat application.Push behavior can be
simulatedusing poll technique but it in most cases produces too much network traffic.
Comet is a web application model in which a long-held HTTP request allows a web server
to push data to a browser,without the browser explicitly requesting it.[17,p.1].There
are several techniques how to achieve this,including long polling and HTTP streaming.
When using long polling,browser’s requests are suspended and only resumed when server
decides to push data.After the response is retrieved,browser connects and begins to waiting
for data again.An application using streaming Comet opens a single persistent connection
from the client browser to the server for all Comet events.These events are incrementally
handled and interpreted on the client side every time the server sends a new event,with
neither side closing the connection.[18]
25
3.AJAX AND CORE COMPONENTS
More modern approach to dealing with push in web applications is using WebSockets.Web-
Sockets is a technology providing bi-directional,full-duplex communication channels,over
a single Transmission Control Protocol (TCP) socket.It is designed to be implemented in
web browsers and web servers,but it can be used by any client or server application.The
WebSocket specification—developed as part of the HTML5 initiative—introduced the Web-
Socket JavaScript interface.The WebSocket API is being standardized by the W3C,and the
WebSocket protocol is being standardized by the IETF.Because ordinary TCP connections to
ports other than 80 are frequently blocked by administrators outside of home environments,
it can be used as a way to overcome these restrictions and provide similar functionality with
some additional protocol overhead while multiplexing several WebSocket services over a
single TCP port.The WebSocket standard simplifies much of the complexity around bi-
directional web communication and reduces network traffic significantly.
Both RichFaces and PrimeFaces use the Atmosphere framework which implements both
Comet and WebSockets and runs on any Java based web server including Tomcat,JBoss
AS,Glassfish and many more.For the client side,WebSocket was to be implemented in
Firefox 4,Google Chrome 4,Opera 11,and Safari 5,as well as the mobile version of Safari in
iOS 4.2.However,although present,support was disabled by default in Firefox 4 [19] and
Opera 11 [20] because of concerns over security vulnerabilities.[21] Although the problem
in WebSockets was already solved,it is expected that web browsers will implement the new
version of protocol in next major releases.This would mean that all major browsers should
have WebSockets enabled again in summer 2011.
RichFaces push component performs real-time updates on the client side fromevents raised
at the server side.The events are pushed out to the client through the Java Message Service
(JMS).Instead of implementing its own messaging mechanism,RichFaces reuses the well
defined and tested standard solution.This results in very easy integration of <a4j:push>
with existing enterprise applications.On the other hand,for smaller applications not us-
ing Java EE compliant application server,it brings some overhead.When the <a4j:push>
component is triggered by a server event,it can in turn cause Ajax updates and changes.
The <a4j:push> component uses the Comet model for pushing data to the client.
On the server side,RichFaces push first needs to initialize topics context,get and instance
of TopicsContext and then send the message (the sample assumes that the JMS topic is
configured in application server):
1 public void initializePush() {
2 TopicsContext topicsContext = TopicsContext.lookup();
3 Topic topic = topicsContext.getOrCreateTopic(
4 new TopicKey("fooTopic","fooSubtopic"));
5 topic.setMessageDataSerializer(
6 DefaultMessageDataSerializer.instance());
7 }
8
9 public void send() {
10 try {
26
3.AJAX AND CORE COMPONENTS
11 TopicsContext.lookup().publish(
12 new TopicKey("fooTopic","fooSubtopic"),message);
13 } catch (MessageException messageException) {
14...
15 }
16 }
On client,<a4j:push> tag would be used like this:
1 <a4j:push address="fooSubtopic@fooTopic"
2 onerror="alert(’Error:’ + event.rf.data)"
3 ondataavailable="handlePush(event.rf.data)"/>
Ajax Push in ICEfaces 2.0 leverages an asynchronous notification mechanism called ICE-
push.ICEpush unleashes the power of Ajax Push in a wide range of Java and JavaScript
technologies,including JSP,JSF,Spring MVC,GWT,Wicket,jQuery,and Prototype.ICE-
push uses long polling to provide asynchronous notification over standard HTTP,using
only standard browser capabilities.
The sequence of events involved in ICEfaces Ajax Push is following:[14,section Ajax Push
Overview]
1.some state change in the application triggers an Ajax Push event;
2.ICEpush notification is delivered to the browser client over a dedicated ICEpush con-
nection;
3.notification at client browser causes a JSF Ajax request with an empty execute phase;
and
4.render phase captures new state of client,and Direct-to-DOMRendering delivers in-
cremental page updates to client.
ICEpush relies on Servlet 3.0 standard Asynchronous Request Processing APIs.If they are
not present in the deployment environment,normal thread blocking connections are used.
For clustered and high-availability deployments of Ajax Push-enabled applications the En-
terprise Push Server (EPS) is required.It manages asynchronous blocking connections across
the cluster and performs seamless fail over for mission-critical,high-availability deploy-
ments.EPS is available in ICEfaces Enterprise Edition.
To use the ICEfaces push in application,client session has to be addedto a push group:
1 PushRenderer.addCurrentSession("fooGroup");
Then,an Ajax Push notification ought be sent to any other client sessions in the push group
“fooGroup”.To do so,method PushRenderer.render() has to be called.
1 public String myAction() {
2//some business logic
3 PushRenderer.render("fooGroup");
27
3.AJAX AND CORE COMPONENTS
4 return null;
5 }
ICEfaces push in version 2.0.2 does not work properly because of an issue with asynchro-
nous request processing (see ICEfaces Jira PUSH-128
1
).The issue is scheduled to be fixed in
ICEfaces 2.1.
PrimeFaces Push is powered by Atmosphere,however it is only compatible with version
0.5.x,not the newer one which is used by RichFaces push.To use <p:push>,the Comet
Servlet and its mapping has to be defined in web.xml:
1 <servlet>
2 <servlet-name>Comet Servlet</servlet-name>
3 <servlet-class>org.primefaces.comet.PrimeFacesCometServlet</servlet-class>
4 <async-supported>true</async-supported>
5 </servlet>
6 <servlet-mapping>
7 <servlet-name>Comet Servlet</servlet-name>
8 <url-pattern>/primefaces_comet/
*
</url-pattern>
9 </servlet-mapping>
On the server side,the following method is the main element of PrimeFaces Push.
1 CometContext.push(String channel,Object data)
On the client side,the component <p:push> is used.This component has two main para-
meters—channel and onpublish.The channel attribute represents an unique name of
communication channel and onpublish attribute points to a JavaScript handler method.
Published object is serialized as JSON,passed to publish handler,and is accessible using
response.data.
1 <h:head>
2 <script type="text/javascript">
3 function handlePublish(response) {
4 alert(response.data);
5 }
6 </script>
7 </h:head>
8
9 <h:body>
10 <h:form>
11 <h:inputText value="..."/>
12 <p:commandButton value="Send"actionListener="..."/>
13 </h:form>
14 <p:push channel="chat"onpublish="handlePublish"/>
15 </h:body>
There is no push component in OpenFaces.
1.PUSH-128:Servlet 3.0’s ARP support is broken on Tomcat 7,http://jira.icefaces.org/browse/
PUSH-128
28
4 Input Components
4.1 Calendar
Applications frequently require users to insert a date such as date of birth or the start date of
employment.The <rich:calendar> component allows the user to enter a date and time
through an inline or popup calendar.The popup calendar can navigate through months and
years,and its look and feel can be highly customized.
Figure 4.1:RichFaces calendar in popup mode expanded,in inline mode,and with hidden
input
Simple usage of <rich:calendar> migh look like in the following sample.RichFaces cal-
endar works fine with all <f:ajax>,<a4j:ajax>,<p:ajax> and <o:ajax>.
1 <rich:calendar value="#{bean.dateTest}">
2 <a4j:ajax event="change".../>
3 </rich:calendar>
In ICEfaces,there is the <ice:selectInputDate> component which renders either inline
or popupcalendar depending on attribute renderAsPopup.Users may enter a date directly
into the text input or click the popup button beside the input to display the popup calendar
view(when in popup mode).When the attached <f:convertDateTime> is configured to
showtime,the calendar will include a time editing UI.
1 <ice:selectInputDate id="calendar"value="#{bean.date}">
2 <f:convertDateTime pattern="MM/dd/yyyy hh:mm a"
3 timeZone="#{bean.timeZone}"/>
4 </ice:selectInputDate>
OpenFaces contain two components for inputting dates—calendar and date chooser.Open-
Faces calendar component is an inline component and date chooser has an input and popup
29
4.INPUT COMPONENTS
which contains <o:calendar>.
Figure 4.2:Expanded OpenFaces date chooser and calendar
In PrimeFaces,there is a <p:calendar> component.Like RichFaces calendar,it supports
both inline and popup mode with or without icon.
Figure 4.3:PrimeFaces calendar in inline mode,default popup mode and popup mode acti-
vated by clicking on button
It has very similar features to RichFaces calendar.However,there is one unique feature—
paging.Using attribute pages it is possible to display multiple months at once.
Figure 4.4:PrimeFaces calendar with pages attributes set to 3
All above mentioned calendar components can be easily localized so that users can input
dates in the format to which they are used,names of months are in the language of theirs
choice and week begins on Sunday or Monday according to set locale.All calendar compo-
nents support only Gregorian calendar.It would not be easy to use e.g.Hebrew or Islamic
30
4.INPUT COMPONENTS
calendar in JSF components.
4.2 Inplace Inputs
An inplace input component allows information to be entered inline in blocks of text,im-
proving readability of the text.RichFaces inplace input has three functional states:the view
state,where the component displays its initial setting,such as “click to edit”;the edit state,
where the user can input text;and the “changed” state,where the newvalue for the compo-
nent has been confirmed but can be edited again if required.It is possible to set the compo-
nent to save its state on blur event and to display controls for confirming or canceling user’s
input.The second similar component provided by RichFaces is <rich:inplaceSelect>.
It looks the same in initial state but it renders a select menu instead of text input when in
edit state.Basic inplace input and inplace select are very easy to use:
1 <rich:inplaceInput value="#{bean.value}"
2 defaultLabel="click here to edit"/>
3
4 <rich:inplaceSelect value="#{bean.value2}"
5 defaultLabel="click here to edit">
6 <f:selectItems value="#{bean.selectItems}"/>
7 <f:selectItem itemValue="1"itemLabel="Item 1"/>
8 <f:selectItem itemValue="2"itemLabel="Item 2"/>
9 <f:selectItem itemValue="3"itemLabel="Item 3"/>
10 <f:selectItem itemValue="4"itemLabel="Item 4"/>
11 </rich:inplaceSelect>
PrimeFaces contains a more universal component called <p:inplace>.It wraps not only
text input but it is possible to create an inplace select,inplace checkbox or even inplace im-
age.Inplace with inner <h:textInput> produces a component very similar to component
<rich:inplaceInput>.However,with default settings,it does not behave the same—the
component does not save its state on blur event.On the other hand,it can be in editor mode
when it shows buttons for confirming or canceling the input and then it is possible to fire
Ajax requests.This advanced inplace would be used like this:
1 <p:inplace editor="true"onEditUpdate="msgs">
2 <p:inputText value="#{inplaceBean.text}"
3 required="true"label="text"/>
4 </p:inplace>
Neither OpenFaces nor ICEfaces have inplace components.
4.3 Autocomplete
Users of modern web applications expect inputs to show suggestions as they type into in-
put.The <rich:autocomplete> component is an auto-completing input box with built-in
31
4.INPUT COMPONENTS
Figure 4.5:RichFaces and PrimeFaces inplace input in initial state,in edit state and in edit
state with controls enabled
Ajax capabilities.It supports client-side suggestions,browser-like selection,and customiza-
tion of the look and feel.To use the component,it is necessary to implement a method that
will return list of suggestions,e.g.:
1 public List<String> autocomplete(String prefix) {
2 ArrayList<String> result = new ArrayList<String>();
3 if (prefix!= null && prefix.length() > 0) {
4 Iterator<Capital> iterator = capitals.iterator();
5 while (iterator.hasNext()) {
6 Capital elem = ((Capital) iterator.next());
7 if ((elem.getState()!= null && elem.getState().toLowerCase().indexOf(
prefix.toLowerCase()) == 0) ||"".equals(prefix)) {
8 result.add(elem.getState());
9 }
10 }
11 } else {
12 for (Capital capital:capitals) {
13 result.add(capital.getState());
14 }
15 }
16 return result;
17 }
This method will be set in autocompletMethod attribute of the <rich:autocomplet>
component.
1 <rich:autocomplete autocompleteMethod="#{bean.autocomplete}"
2 value="#{bean.value}">
The <rich:autocomplete> can work in several modes which influence if the data should
be pre-loaded or if they will be fetched with an Ajax request on every user’s input.By de-
fault,the first suggestion itemis selected as the user types.This behavior can be deactivated
by setting selectFirst to false.Setting autoFill to true causes the combo-box to fill the
text field box with a matching suggestion as the user types.The attribute tokens can be used
for user to be able to input multiple values.For example,if the tokens attribute is set to “,”,
32
4.INPUT COMPONENTS
user can use both comma and space for separating inputs.For each input,a newsuggestion
is process begins.
PrimeFaces autocomplete component is very similar to RichFaces’ one.It can be used in
almost the same way.There is attribute completeMethod instead of RichFaces’ method
autocompleteMethod.This attribute canbe boundto the methodfromRichFaces example
without any changes.
1 <p:autoComplete completeMethod="#{bean.complete}"
2 value="#{bean.value}">
It is possible to limit the maximumnumber of suggestions,set minimumquery length and
even set query delay in order to ensure that the server will not be flooded with Ajax re-
quests.
Instead of waiting for user to send the input manually with some action button or link,it is
possible to send value of <p:autoComplete> instantly with Ajax.However,PrimeFaces
do not support standard JSF way,i.e.to attach an Ajax behavior (<f:ajax>,<p:ajax>,
or <a4j:ajax>).To do Ajax request,one has to set attribute selectListener.Option-
ally,some parts of the page can be rerendered after selection using onSelectUpdate op-
tion.
In OpenFaces,an autocomplete input component is called <o:suggestionField>.It can
contain static options (similarly to <h:selectOneMenu>) or dynamic options.To use the
later,the autocomplete method fromabove example has to be modified slightly:
1 public List<String> getCapitals() {
2 String prefix = Faces.var("searchField",String.class);
3 ArrayList<String> result = new ArrayList<String>();
4 if (prefix!= null && prefix.length() > 0) {
5 Iterator<Capital> iterator = capitals.iterator();
6 while (iterator.hasNext()) {
7 Capital elem = ((Capital) iterator.next());
8 if ((elem.getState()!= null && elem.getState().toLowerCase().indexOf(
prefix.toLowerCase()) == 0) ||"".equals(prefix)) {
9 result.add(elem.getState());
10 }
11 }
12 } else {
13 for (Capital capital:capitals) {
14 result.add(capital.getState());
15 }
16 }
17 return result;
18 }
Component will then be used in the following way:
1 <o:suggestionField id="suggestionField"value="#{oSuggestionFieldBean.value}"
2 suggestionMode="custom">
33
4.INPUT COMPONENTS
3 <o:dropDownItems value="#{oSuggestionFieldBean.capitals}"/>
4 <o:ajax event="change"render="output"/>
5 </o:suggestionField>
Autocomplete in ICEfaces is represented by the <ice:selectInputText> component.
The usage is very similar to previous components.The filtering method can be reused with
very small change.
1 <ice:selectInputText rows="15"width="300"valueChangeListener="#{bean.
updateList}"
2 value="#{bean.selected}">
3 <f:selectItems value="#{bean.list}"/>
4 </ice:selectInputText>
1 public void updateList(ValueChangeEvent event) {
2 matchesList = new ArrayList<String>();
3 String prefix = (String) event.getNewValue();
4 if (prefix!= null && prefix.length() > 0) {
5 Iterator<Capital> iterator = capitals.iterator();
6 while (iterator.hasNext()) {
7 Capital elem = ((Capital) iterator.next());
8 if ((elem.getState()!= null && elem.getState().toLowerCase().indexOf(
prefix.toLowerCase()) == 0) ||"".equals(prefix)) {
9 matchesList.add(elem.getState());
10 }
11 }
12 } else {
13 for (Capital capital:capitals) {
14 matchesList.add(capital.getState());
15 }
16 }
17 }
4.4 Slider
The <rich:inputNumberSlider> component is an input component for numerical val-
ues that can optionally include control arrows to step through the values,a tooltip to display
the value while sliding,and a text field for typing the numerical value which can then be
validated against the slider’s range.Basic use of the component with no attributes specified
will render a slider with a minimumvalue of 0,a maximumof 100,and a gradient step of 1,
together with a text field for typing the desired numerical value.
The <rich:inputNumberSlider> component is highly customizable,e.g.input can be
hidden,boundary values do not have to be displayed,step,minimal and maximal value can
be customized,and slider can be displayed horizontally or vertically.
PrimeFaces contains a slider component but it is much simpler though.The <p:slider>
itself does not contain input but it has to be associated with some text input using attribute
34
4.INPUT COMPONENTS
Figure 4.6:Default RichFaces slider with value set to 81
for.
1 <h:inputText id="number"value="#{bean.value}"/>
2 <p:slider for="number"style="width:150px;"/>
Figure 4.7:PrimeFaces slider with default values
Similarly to <p:autoComplete> component,no Ajax behavior can be attached to compo-
nent <p:slider>.Instead,the slideEndListener attribute has to be used which is not
standard JSF approach.
There is no slider component in OpenFaces nor ICEfaces standard component suite.How-
ever,there is a slider component in ICEfaces Enterprise Edition.
4.5 Spinner
Spinner is a single-line input field with buttons to increase and decrease a numerical value.
In RichFaces,this component is called <rich:inputNumberSpinner>.It has practically
the same API as <rich:inputNumberSlider>.As in RichFaces slider,for basic use only
attribute value has to be set (either to an EL expression or a literal).
Figure 4.8:RichFaces spinner component
Spinner is a very simple component.However,there are som features that can be cus-
tomized.When changing the value using the buttons,raising the value above the maximum
will cause the spinner to restart at the minimumvalue.Likewise,when lowering belowthe
minimum value the spinner will reset to the maximum value.This behavior can be deac-
tivated by setting cycled to false,which will cause the buttons to stop responding when
35
4.INPUT COMPONENTS
the reach the maximumor minimumvalue.The second customizable feature is set with at-
tribute enableManualInput.When it is set to false,it is not possible to type into spinner’s
input field.
In PrimeFaces,there is <p:spinner> component.Unlike PrimeFaces slider,this compo-
nents behaves like a JSF component.Similarly to RichFaces slider,it is really easy to start
using the component:
1 <p:spinner value="#{bean.value}"/>
Many aspects of the component are customizable.Spinner’s step can be set using attribute
stepFactor,it is possible to set boundaries (i.e.min a max value),and using the at-
tributes prefix and suffix it is possible e.g.to display spinners containing currency sym-
bol.
1 <p:spinner value="#{bean.value}"prefix="$">
2 <f:convertNumber currencySymbol="$"type="currency"/>
3 </p:spinner>
OpenFaces contain a spinner component,too.It has features very similar to PrimeFaces and
RichFaces spinner and practically identical API.It is possible to disabled manual input by
setting attribute typingAllowed to false.Buttons can be placed either on the left or on the
right of spinner’s input.This can be achieved by using attribute buttonAlignment.
1 <o:spinner id="input"value="#{bean.value}"promptText="click here to edit"
2 minValue="0"maxValue="10"step="0.1">
3 <o:ajax render="output"/>
4 </o:spinner>
However the example above is very simple,it does not work because of an exception re-
turned in response for Ajax request:
1 <partial-response>
2 <error>
3 <error-name>class java.lang.IllegalStateException</error-name>
4 <error-message>
5 <![CDATA[org.openfaces.component.ajax.AjaxHelper]]>
6 </error-message>
7 </error>
8 <extension ln="openfaces"ajaxResult="null"type="ajaxResult">
9 </extension>
10 </partial-response>
This bug is caused by JSF itself.It was reported as JSF issue 1427.
1
It is marked as critical and
should be resolved in Mojarra 2.2.There is a workaround for this issue,though.The follow-
ing context parameter has to be set in web.xml pointing to the problematic page(s).
1.JSF Jira,http://java.net/jira/browse/JAVASERVERFACES-1427
36
4.INPUT COMPONENTS
1 <context-param>
2 <param-name>javax.faces.FULL_STATE_SAVING_VIEW_IDS</param-name>
3 <param-value>/page.xhtml</param-value>
4 </context-param>
Then,<o:ajax> has to be replaced with <f:ajax>.After that,Ajax requests should be
fired and output should be updated as expected.
There is no spinner component is standard ICEfaces component suite.However,there are
number spinner,date spinner,and text spinner components in ICEfaces Enterprise Edi-
tion.
4.6 File Upload
Many web applications require or allow their users to upload files.In RichFaces,there is
component <rich:fileUpload> that features multiple uploads,progress bars,restric-
tions on file types,and restrictions on sizes of the files to be uploaded.
Basic usage requires the fileUploadListener attribute.Use the attribute to reference a
listener function on the server side after each file is uploaded.The listener should process
files as required,such as storing them in the session,database,or filesystem directory.The
component itself does not store uploaded files,so if the listener is not implemented they are
not stored anywhere.[15,section rich:fileUpload]
1 <rich:fileUpload fileUploadListener="#{bean.listener}"/>
Depending on org.richfaces.fileUpload.createTempFiles context parameter of
the web.xml,files will be uploaded to either a temporary directory (depending on operating
system) or to RAM.If the value is true,they will be uploaded to a temporary directory.
To limit the maximumsize of the uploaded files,it is necessary to define the context parame-
ter org.richfaces.fileUpload.maxRequestSize in the web.xml.Its value is defined
in bytes.
Figure 4.9:RichFaces file upload with selected files and during the uploading
37
4.INPUT COMPONENTS
PrimeFaces file upload is based on Flash.If the user agent does not support JavaScript or
Flash,it fallback to the standard input with type set to file.
First of all,PrimeFaces file upload requires two additional dependencies,namely commons-
fileupload version 1.2.1 and commons-io version 1.4 or newer.Then,file upload filter has to
be defined in application’s web.xml.Moreover,this filter has to be listed first.
1 <filter>
2 <filter-name>PrimeFaces FileUpload Filter</filter-name>