Using Spring Faces

Exclusive offer: get 50% off this eBook here
Spring Web Flow 2 Web Development

Spring Web Flow 2 Web Development — Save 50%

Master Spring's well-designed web frameworks to develop powerful web applications

$23.99    $12.00
by Markus Stäuble | March 2009 | Java Open Source Web Development

In the previous article we saw how to Enable Spring Faces support. In this article by Markus Stäuble, we will learn how to use Spring Faces and its integration with JSF component libraries.

Using Spring Faces Module

The following section shows you how to use the Spring Faces module.

Overview of all tags of the Spring Faces tag library

The Spring Faces module comes with a set of components, which are provided through a tag library. If you want more detailed information about the tag library, look at the following files inside the Spring Faces source distribution:

  • spring-faces/src/main/resources/META-INF/spring-faces.tld
  • spring-faces/src/main/resources/META-INF/springfaces.taglib.xml
  • spring-faces/src/main/resources/META-INF/faces-config.xml

If you want to see the source code of a specific tag, refer to faces-config.xml and springfaces.taglib.xml to get the name of the class of the component. The spring-faces.tld file can be used for documentation issues.

The following table should give you a short description about the available tags from the Spring Faces component library:

Name of the tag

Description

includeStyles

The includeStyles tag renders the necessary CSS stylesheets which are essential for the components from Spring Faces. The usage of this tag in the head section is recommended for performance optimization. If the tag isn't included, the necessary stylesheets are rendered on the first usage of the tag. If you are using a template for your pages, it's a good pattern to include the tag in the header of that template.

For more information about performance optimization, refer to the Yahoo performance guidelines, which are available at the following URL: http://developer.yahoo.com/performance. Some tags (includeStyles, resource, and resourceGroup) of the Spring Faces tag library are implementing patterns to optimize the performance on client side.

resource

The resource tag loads and renders a resource with ResourceServlet. You should prefer this tag instead of directly including a CSS stylesheet or a JavaScript file because ResourceServlet sets the proper response headers for caching the resource file.

resourceGroup

With the resourceGroup tag, it is possible to combine all resources which are inside the tag. It is important that all resources are the same type. The tag uses ResourceServlet with the appended parameter to create one resource file which is sent to the client.

clientTextValidator

With the clientTextValidator tag, you can validate a child inputText element. For the validation, you have an attribute called regExp where you can provide a regular expression. The validation is done on client side.

clientNumberValidator

With the clientNumberValidator tag, you can validate a child inputText element. With the provided validation methods, you can check whether the text is a number and check some properties for the number, e.g. range. The validation is done on client side.

clientCurrencyValidator

With the clientCurrencyValidator tag, you can validate a child inputText element. This tag should be used if you want to validate a currency. The validation is done on client side.

clientDateValidator

With the clientDateValidator tag, you can validate a child inputText element. The tag should be used to validate a date. The field displays a pop-up calendar. The validation is done on client side.

validateAllOnClick

With the validateAllOnClick tag, you can execute all client-side validation on the click of a specific element. That can be useful for a submit button.

commandButton

With the commandButton tag, it is possible to execute an arbitrary method on an instance. The method itself has to be a public method with no parameters and a java.lang.Object instance as the return value.

commandLink

The commandLink tag renders an AJAX link. With the processIds attribute, you can provide the ids of components which should be processed through the process.

ajaxEvent

The ajaxEvent tag creates a JavaScript event listener. This tag should only be used if you can ensure that the client has JavaScript enabled.

A complete example

After we have shown the main configuration elements and described the Spring Faces components, the following section shows a complete example in order to get a good understanding about how to work with the Spring Faces module in your own web application.

The following diagram shows the screen of the sample application. With the shown screen, it is possible to create a new issue and save it to the bug database.

It is not part of this example to describe the bug database or to describe how to work with databases in general. The sample uses the model classes.

Using Spring Faces

The diagram has three required fields. These fields are:

  • Name: The name of the issue
  • Description: A short description for the issue
  • Fix until: The fixing date for the issue

Additionally, there are the following two buttons:

  • store: With a click on the store button, the system tries to create a new issue that includes the provided information
  • cancel: With a click on the cancel button, the system ignores the data which is entered and navigates to the overview page.

Now, the first step is to create the implementation of that input page. That implementation and its description are shown in the section below.

Creating the input page

As we described above, we use Facelets as a view handler technology. Therefore, the pages have to be defined with XHTML, with .xhtml as the file extension. The name for the input page will be add.xhtml.

For the description, we separate the page into the following five parts:

  • Header
  • Name
  • Description
  • Fix until
  • The Buttons

This separation is shown in the diagram below:

Using Spring Faces

The Header part

The first step in the header is to define that we have an XHTML page. This is done through the definition of the correct doctype.

<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

An XHTML page is described as an XML page. If you want to use special tags inside the XML page, you have to define a namespace for that. For a page with Facelets and Spring Faces, we have to define more than one namespace. The following table describes those namespaces:

Namespace

Description

http://www.w3.org/1999/xhtml

The namespace for XHTML itself.

http://java.sun.com/jsf/facelets

The Facelet defines some components (tags). These components are available under this namespace.

http://java.sun.com/jsf/html

The user interface components of JSF are available under this namespace.

http://java.sun.com/jsf/core

The core tags of JSF, for example converter, can be accessed under this namespace.

http://www.springframework.org/tags/faces

The namespace for the Spring Faces

component library.

For the header definition, we use the composition component of the Facelets components. With that component, it is possible to define a template for the layout. This is very similar to the previously mentioned Tiles framework. The following code snippet shows you the second part (after the doctype) of the header definition:

A description and overview of the JSF tags is available at: http://developers.sun.com/jscreator/archive/learning/bookshelf/pearson/corejsf/standard_jsf_tags.pdf.

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:sf="http://www.springframework.org/tags/faces"
template="/WEB-INF/layouts/standard.xhtml">

With the help of the template attribute, we refer to the used layout template. In our example, we refer to /WEB-INF/layouts/standard.xhtml.

The following code shows the complete layout file standard.xhtml. This layout file is also described with the Facelets technology. Therefore, it is possible to use Facelets components inside that page, too. Additionally, we use Spring Faces components inside that layout page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:sf="http://www.springframework.org/tags/faces">
<f:view contentType="text/html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
/>
<title>flow.tracR</title>
<sf:includeStyles/>
<sf:resourceGroup>
<sf:resource path="/css-framework/css/tools.css"/>
<sf:resource path="/css-framework/css/typo.css"/>
<sf:resource path="/css-framework/css/forms.css"/>
<sf:resource path="/css-framework/css/layout-navtop-localleft.
css"/>
<sf:resource path="/css-framework/css/layout.css"/>
</sf:resourceGroup>
<sf:resource path="/css/issue.css"/>
<ui:insert name="headIncludes"/>
</head>
<body class="tundra spring">
<div id="page">
<div id="content">
<div id="main">
<ui:insert name="content"/>
</div>
</div>
</div>
</body>
</f:view>
</html>

The Name part

The first element in the input page is the section for the input of the name. For the description of that section, we use elements from the JSF component library. We access this library with h as the prefix, which we have defined in the header section. For the general layout, we use standard HTML elements, such as the div element. The definition is shown below.

<div class="field">
<div class="label">
<h:outputLabel for="name">Name:</h:outputLabel>
</div>
<div class="input">
<h:inputText id="name" value="#{issue.name}" />
</div>
</div>

The Description part

The next element in the page is the Description element. The definition is very similar to the Name part. Instead of the definition of the Name part, we use the element description inside the h:inputText element—the required attribute with true as its value. This attribute tells the JSF system that the issue.description value is mandatory. If the user does not enter a value, the validation fails.

<div class="field">
<div class="label">
<h:outputLabel for="description">Description:</h:outputLabel>
</div>
<div class="input">
<h:inputText id="description" value="#{issue.description}"
required="true"/>
</div>
</div>

The Fix until part

The last input section is the Fix until part. This field is a very common field in web applications, because there is often the need to input a date. Internally, a date is often represented through an instance of the java.util.Date class. The text which is entered by the user has to be validated and converted in order to get a valid instance. To help the user with the input, a calendar for the input is often used. The Spring Faces library offers a component which shows a calendar and adds client-side validation. The complete definition of the Fix until part is shown below. The name of the component is clientDateValidator. The clientDateValidator component is used with sf as the prefix. This prefix is defined in the namespace definition in the shown header of the add.xhtml page.

<div class="field">
<div class="label">
<h:outputLabel for="checkinDate">Fix until:</h:outputLabel>
</div>
<div class="input">
<sf:clientDateValidator required="true" invalidMessage="please
insert a correct fixing date. format: dd.MM.yyyy"
promptMessage="Format: dd.MM.yyyy, example: 01.01.2020">
<h:inputText id="checkinDate" value="#{issue.fixingDate}"
required="true">
<f:convertDateTime pattern="dd.MM.yyyy" timeZone="GMT"/>
</h:inputText>
</sf:clientDateValidator>
</div>
</div>

In the example above, we use the promptMessage attribute to help the user with the format. The message is shown when the user sets the cursor on the input element.

Using Spring Faces

If the validation fails, the message of the invalidMessage attribute is used to show the user that a wrong formatted input has been entered.

The Buttons part

The last element in the page are the buttons. For these buttons, the commandButton component from Spring Faces is used. The definition is shown below:

<div class="buttonGroup">
<sf:commandButton id="store" action="store" processIds="*"
value="store"/>
<sf:commandButton id="cancel" action="cancel" processIds="*"
value="cancel"/>
</div>

It is worth mentioning that JavaServer Faces binds an action to the action method of a backing bean. Spring Web Flow binds the action to events.

Handling of errors

It's possible to have validation on the client side or on the server side. For the Fix until element, we use the previously mentioned clientDateValidator component of the Spring Faces library. The following figure shows how this component shows the error message to the user:

Using Spring Faces

Reflecting the actions of the buttons into the flow definition file

Clicking the buttons executes an action that has a transition as the result. The name of the action is expressed in the action attribute of the button component which is implemented as commandButton from the Spring Faces component library. If you click on the store button, the validation is executed first. If you want to prevent that validation, you have to use the bind attribute and set it to false. This feature is used for the cancel button, because in this state it is necessary to ignore the inputs.

<view-state id="add" model="issue">
<transition on="store" to="issueStore" >
<evaluate expression="persistenceContext.persist(issue)"/>
</transition>
<transition on="cancel" to="cancelInput" bind="false">
</transition>
</view-state>

Showing the results

To test the implemented feature, we implement an overview page. We have the choice to implement the page as a flow with one view state or implement it as a simple JSF view. Independent from that choice, we will use Facelets to implement that overview page, because Facelets does not depend on the Spring Web Flow Framework as it is a feature of JSF.

The example uses a table to show the entered issues. If no issue is entered, a message is shown to the user. The figure below shows this table with one row of data. The Id is a URL. If you click on this link, the input page is shown with the data of that issue. With data, we execute an update. The indicator for that is the valid ID of the issue.

Using Spring Faces

If your data is available, the No issues in database message is shown to the user. This is done with a condition on the outputText component. See the code snippet below:

<h:outputText id="noIssuesText" value="No Issues in the database"
rendered="#{empty issueList}"/>

For the table, we use the dataTable component.

<h:dataTable id="issues" value="#{issueList}" var="issue"
rendered="#{not empty issueList}" border="1">
<h:column>
<f:facet name="header">Id</f:facet>
<a href="add?id=#{issue.id}">#{issue.id}</a>
</h:column>
<h:column>
<f:facet name="header">Name</f:facet>
#{issue.name}
</h:column>
<h:column>
<f:facet name="header">fix until</f:facet>
#{issue.fixingDate}
</h:column>
<h:column>
<f:facet name="header">creation date</f:facet>
#{issue.creationDate}
</h:column>
<h:column>
<f:facet name="header">last modified</f:facet>
#{issue.lastModified}
</h:column>
</h:dataTable>
Spring Web Flow 2 Web Development Master Spring's well-designed web frameworks to develop powerful web applications
Published: March 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Integration with other JavaServer Faces component libraries

One of the basic concepts of JavaServer Faces is the components. The idea is to have one implementation of the JavaServer Faces infrastructure and use the components which are appropriate for your web application. It should be possible to use any third-party JSF component library with Spring Faces.

It is important to say that the configuration in the web deployment descriptor web.xml is different if you are using Spring Faces, because the requests are not routed through the standard FacesServlet. FacesServlet is used only to establish the infrastructure for the JavaServer Faces subsystem.

Many JSF component libraries are available in the market. Some libraries are open-source, other libraries are commercial. In this section, we will have a look at the following two open-source JSF component libraries:

Integration with JBoss RichFaces

One open-source JavaServer Faces component library is JBoss RichFaces. The web site of that framework is available at the following URL: http://www.jboss.org/jbossrichfaces. This component library offers many components which are based on AJAX (Asynchronous JavaScript and XML). If you want to use that component library in conjunction with Spring Faces, you first have to download the latest release from the download section of the web page of JBoss RichFaces at the http://www.jboss.org/jbossrichfaces/downloads/ URL. We have used Version 3.2.2 in our example. After the download of the richfaces-ui-3.2.2.GA-bin.zip archive (the size is about 25 MB), extract the archive into an arbitrary folder. Other formats (tar.gz) and the source files are also available from the mentioned download page. The directory layout of the extracted archive looks like the figure which is shown below:

Using Spring Faces

The binary libraries are located inside the lib folder. The apidocs, docs, and tlddoc folders contain the documentation for the component library. If you need more information, it is highly recommended to read the documentation inside the docs folder. To use the RichFaces component library inside your web application, copy the richfaces-api-3.2.2.GA.jar, richfaces-impl-3.2.2.GA.jar, and richfacesui-3.2.2.GA.jar files into the WEB-INF/lib folder of your web application.

The next step is the configuration inside the web deployment descriptor file web.xml. RichFaces comes with a servlet filter which has to be configured as shown in the example below:

<filter>
<display-name>RichFaces Filter</display-name>
<filter-name>richfaces</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>

After the configuration of the filter, the mapping of the filter has to be done. The important parameter for the integration with Spring Faces is the servlet-name parameter. Here, you have to mention the name of your used dispatch servlet.

<filter-mapping>
<filter-name>richfaces</filter-name>
<servlet-name>flowtrac</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>

After this configuration, you can use the components inside your views. The namespace for the components is available at http://richfaces.org/rich. The example page header below shows the usage of the namespace:

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:rich="http://richfaces.org/rich"
xmlns:sf="http://www.springframework.org/tags/faces"
template="/WEB-INF/layouts/standard.xhtml">

After the configuration in the page header, you can use the components with the configured prefix rich. The following example uses the component for uploading a file:

<rich:fileUpload maxFilesQuantity="3" />

The figure below shows the sample component in action:

Using Spring Faces

The number of components inside the RichFaces library is quite comprehensive. We recommend reading the documentation of RichFaces to learn more about the possibilities which are offered through these components

Integration with Apache MyFaces Trinidad

Apache MyFaces Trinidad is an open-source JSF framework which offers many components that you can use in conjunction with your own web application. The web page of the framework is at http://myfaces.apache.org/trinidad. The first step is to download the distribution of Apache MyFaces Trinidad from the download section from the following URL: http://myfaces.apache.org/trinidad/download.html. For our example, we have used version 1.0.10 of Apache MyFaces Trinidad. After the download of the trinidad-1.0.10-dist.zip file (the size of the compressed archive is about 11.9 MB), extract it into an arbitrary folder. The layout of the folder is shown in the figure below:

Using Spring Faces

The lib folder contains the binary libraries. The library as the source archive is included in the src folder. The javadoc folder comprehends the API documentation of the library. After the download, you have to copy two libraries, trinidad-api-1.0.10.jar and trindad-impl-1.0.10.jar, into the WEB-INF/lib folder of your web application. The libraries themselves are located inside the lib folder. Apache MyFaces Trindad comes with two component libraries which can be used inside your web application. The namespace of these libraries is shown in the table below:

Recommended Shortcut

for the library

Namespace

Tr

http://myfaces.apache.org/trinidad

Trh

http://myfaces.apache.org/trinidad/html

The first step in the configuration process is the configuration inside the web deployment descriptor (web.xml) of your web application. You have to configure some context parameters, the Trinidad filter, and the Trinidad Resource Servlet. If you use Facelets to describe your views, do not forget to set the org.apache.myfaces.trinidad.ALTERNATE_VIEW_HANDLER parameter.

<context-param>
<param-name>org.apache.myfaces.trinidad.ALTERNATE_VIEW_
HANDLER</param-name>
<param-value>com.sun.facelets.FaceletViewHandler</param-value>
</context-param>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>
org.apache.myfaces.trinidad.CHANGE_PERSISTENCE
</param-name>
<param-value>session</param-value>
</context-param>
<context-param>
<param-name>
org.apache.myfaces.trinidad.ENABLE_QUIRKS_MODE
</param-name>
<param-value>false</param-value>
</context-param>
<filter>
<filter-name>Trinidad Filter</filter-name>
<filter-class>
org.apache.myfaces.trinidad.webapp.TrinidadFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>Trinidad Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>Trinidad Resource Servlet</servlet-name>
<servlet-class>
org.apache.myfaces.trinidad.webapp.ResourceServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Trinidad Resource Servlet</servlet-name>
<url-pattern>/adf/*</url-pattern>
</servlet-mapping>

The next step is the configuration of faces-config.xml.

<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
"http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config>
<application>
<default-render-kit-id>org.apache.myfaces.trinidad.core</
default-render-kit-id>
<property-resolver>org.springframework.faces.webflow.
FlowPropertyResolver</property-resolver>
<variable-resolver>org.springframework.faces.webflow.
FlowVariableResolver</variable-resolver>
<variable-resolver>org.springframework.web.jsf.
DelegatingVariableResolver</variable-resolver>
</application>
</faces-config>

After the configuration inside faces-config.xml, we can use the mentioned namespaces inside the header of our views.

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:tr="http://myfaces.apache.org/trinidad"
xmlns:sf="http://www.springframework.org/tags/faces"
template="/WEB-INF/layouts/standard.xhtml">

For our example, we use a color chooser for selecting a color.

<div class="section">
<h1>Choose color</h1>
<h:messages errorClass="errors" />
<h:form id="issueForm">
<tr:inputColor id="sic1" chooseId="cc2"/>
<tr:chooseColor id="cc2" width="18" />
</h:form>
</div>

The component in action is shown in the figure below.

Using Spring Faces

As you have seen in the two examples, the integration of component libraries needs some additional work. Therefore, it is not recommended to use more than one or two component libraries. Our recommendation is to select one rich component library and take care that the integration is working in a maintainable way.

Summary

This article shows a complete example of using Spring Faces in your own project. The last section in this article shows the integration with JSF component libraries. You have seen explicitly the integration with RichFaces and Apache MyFaces Trinidad. If you want to integrate with other component libraries, just remember not to configure it with FacesServlet.

If you have read this article you may be interested to view :

 

Spring Web Flow 2 Web Development Master Spring's well-designed web frameworks to develop powerful web applications
Published: March 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Markus Stäuble

Markus Stäuble is currently working as CTO at namics (deutschland) gmbh. He has a Master degree in Computer Science. He started programming with Java in the year 1999. After that he has earned much experience in building enterprise java systems, especially web applications. He has a deep knowledge of the java platform and the tools and frameworks around Java.

Books From Packt

Spring 2.5 Aspect Oriented Programming
Spring 2.5 Aspect Oriented Programming

Learning jQuery 1.3
Learning jQuery 1.3

Drupal 6 Site Builder Solutions
Drupal 6 Site Builder Solutions

JBoss Portal Server Development
JBoss Portal Server Development

Drupal 6 Social Networking
Drupal 6 Social Networking

WordPress Plugin Development: Beginner's Guide
WordPress Plugin Development: Beginner's Guide

Java EE 5 Development with NetBeans 6
Java EE 5 Development with NetBeans 6

jQuery UI 1.6: The User Interface Library for jQuery
jQuery UI 1.6: The User Interface Library for jQuery

 

 

 

 

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
C
d
6
x
7
E
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software