JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Skin Customization in JBoss RichFaces 3.3

November 11, 2009 by Krishna Srinivasan Leave a Comment

JBoss RichFaces 3.3JBoss RichFaces is a rich component library for JavaServer Faces and an AJAX framework that allows easy integration of Ajax capabilities into complex business applications. Do you wish to eliminate the time involved in writing JavaScript code and managing JavaScript-compatibility between browsers to build an Ajax web application quickly?

also read:

  • Introduction to JSF
  • JSF Interview Questions
  • Request Processing Lifecycle phases in JSF

This book goes beyond the documentation to teach you how to do that. It will show you how to get the most out of JBoss RichFaces by explaining the key components and how you can use them to enhance your applications. Most importantly, you will learn how to integrate Ajax into your applications without using JavaScript, but only standard JSF components. You will learn how to create and customize your own components and add them to your new or existing applications.

First, the book introduces you to JBoss RichFaces and its components. It uses many examples of Ajax components which, among others, include: Calendar, Data Table, ToolTip, ToolBar, Menu, RichEditor, and Drag ‘n’ Drop. All these components will help you create the web site you always imagined. Key aspects of the RichFaces framework such as the Ajax framework, skinnability, and Component Development Kit (CDK) will help you customize the look of your web application. As you progress through the book, you will see a sample application that shows you how to build an advanced contact manager. You’re also going to be amazed to know about the advanced topics you will learn such as developing new components, new skins, optimizing a web application, inserting components dynamically using Java instead of XHTML, and using JavaScript to manage components. This book is more than a reference with component example code: it’s a manual that will guide you, step by step, through the development of a real Ajax JSF web application.

What This Book Covers

Chapter 1: What is RichFaces covers the aims of the RichFaces framework, its components, and what you can do by using it in a web application.

Chapter 2: Getting Ready explains how to configure your environment by creating a simple project using the seam-gen tool, adding support to Seam and Facelets, and the manual configuration for the RichFaces libraries. We will understand the IDE that we can
use while developing with the framework.

In Chapter 3: First Steps, you will learn to build Ajax applications by developing a simple example, the basics of RichFaces step by step, from creating the project to editing the code, using very important components and their Ajax properties.

Chapter 4: The Application covers how to create the basics of our project by having a look at the side technologies we might know, in order to build good applications. It will cover templating with Facelets, JBoss Seam authentication, and customization of the entities.

Chapter 5: Making the Application Structure explains us how to create the login and registration system of the website. We’ll look at all the features that a real application might have.

In Chapter 6: Making the Contacts List and Detail, we will develop the core feature of our application—contact management. We’ll learn about Ajax interaction and containers, and about new Ajax components that RichFaces offers.

Chapter 7: Finishing the Application explains how to finish building the application using the RichFaces components, and about customizing them.

In Chapter 8: Skin Customization, we’ll see all the powerful customization capabilities that the RichFaces framework offers.

Chapter 9: Creating a New plug ‘n’ skin covers how to create, customize, and package and deploy a new pluggable skin.

Chapter 10: Advanced Techniques explains you how to use and implement pushing, partial updates, and session expiration handling in order to develop advanced applications.

In Chapter 11: Component Development Kit, we’ll see how to start a project in order to develop a simple JSF Ajax component in a simple and effective way using the features the CDK offers.

Appendix: RichFaces Components Overview covers a list of all the components of RichFaces with their functionalities.

Skin Customization

We have finished our application and now we would like to customize its look to follow the style we like. In this chapter, we will see how to change the style of existing skins (using CSS and XCSS) and how to create a new personalized skin starting from the built-in skins that the RichFaces framework offers.

Skinnability

In the Chapter 1, First Steps, we read an introduction of what RichFaces skinnability is about, and during the development of our application, we’ve learned how to set the default skin for a project and even how to change it dynamically .

Summarizing, every RichFaces component gives the support for skinnability and it means that just by changing the skin, we change the look for all of the components. That’s very good for giving our application a consistent look and not repeating the same CSS values for each component every time.

RichFaces still uses CSS, but it also enhances it in order to make it simpler to manage and maintain.

Customize skin parameters

A skin file contains the basic settings (such as font, colors, and so on) that we’ll use for all the components—just by changing those settings, we can customize the basic look and feel for the RichFaces framework.

As you might know, RichFaces comes with some built-in skins (and other external plug ‘n’ skin ones)—you can start with those skins in order to create your own custom skin.

The built-in skins are:

  • Plain
  • emeraldTown
  • blueSky
  • wine
  • japanCherry
  • ruby
  • classic
  • deepMarine

The plug ‘n’ skin ones are:

  • laguna
  • darkX
  • glassX

The plug ‘n’ skin skins are packaged in external jar files (that you can download from the same location as that of the RichFaces framework) that must be added into the project in order to be able to use them. We will see how to create our custom plug ‘n’
skin in the next chapter. Remember that the skin used by the application can be set as context-param in the

web.xml file:

[code lang=”xml”] <context-param>
<param-name>org.richfaces.SKIN</param-name>
<param-value>emeraldTown</param-value>
</context-param>
[/code]

This is an example with the emeralTown skin set:

richfaces-1If we change the skin to japanCherry, we have the following screenshot:

richfaces-2That’s without changing a single line of CSS or XHTML!

Edit a basic skin

Now let’s start creating our own basic skin. In order to do that, we are going to reuse one of the built-in skin files and change it. You can find the skin files in the richfaces-impl-3.x.x.jar file inside the META-INF/skins directory.

Let’s open the file and then open, for example, the emeraldTown.skin.properties file that looks like this (yes, the skin file is a .properties file!):

[code] #Colors
headerBackgroundColor=#005000
headerGradientColor=#70BA70
headerTextColor=#FFFFFF
headerWeightFont=bold

generalBackgroundColor=#f1f1f1
generalTextColor=#000000
generalSizeFont=18px
generalFamilyFont=Arial, Verdana, sans-serif

controlTextColor=#000000
controlBackgroundColor=#ffffff
additionalBackgroundColor=#E2F6E2

shadowBackgroundColor=#000000
shadowOpacity=1

panelBorderColor=#C0C0C0
subBorderColor=#ffffff

tabBackgroundColor=#ADCDAD
tabDisabledTextColor=#67AA67

trimColor=#BBECBB

tipBackgroundColor=#FAE6B0
tipBorderColor=#E5973E

selectControlColor=#FF9409

generalLinkColor=#43BD43
hoverLinkColor=#FF9409
visitedLinkColor=#43BD43

# Fonts
headerSizeFont=18px
headerFamilyFont=Arial, Verdana, sans-serif

tabSizeFont=11
tabFamilyFont=Arial, Verdana, sans-serif

buttonSizeFont=18
buttonFamilyFont=Arial, Verdana, sans-serif

tableBackgroundColor=#FFFFFF
tableFooterBackgroundColor=#cccccc
tableSubfooterBackgroundColor=#f1f1f1
tableBorderColor=#C0C0C0
tableBorderWidth=2px

#Calendar colors
calendarWeekBackgroundColor=#f5f5f5

calendarHolidaysBackgroundColor=#FFEBDA
calendarHolidaysTextColor=#FF7800

calendarCurrentBackgroundColor=#FF7800
c alendarCurrentTextColor=#FFEBDA

calendarSpecBackgroundColor=#E2F6E2
calendarSpecTextColor=#000000

warningColor=#FFE6E6
warningBackgroundColor=#FF0000

editorBackgroundColor=#F1F1F1
editBackgroundColor=#FEFFDA

#Gradients
gradientType=plain
[/code]

In order to test it, let’s open our application project, create a file called mySkin.skin. properties inside the directory /resources/WEB-INF/, and add the above text. Then, let’s open the build.xml file and edit it, and add the following code into the war target:

[code lang=”html”] <copy
tofile="${war.dir}/WEB-INF/classes/mySkin.skin.properties"
file="${basedir}/resources/WEB-INF/mySkin.skin.properties"
overwrite="true"/>
[/code]

Also, as our application supports multiple skins, let’s open the components.xml file and add support to it:

[code lang=”xml”] <property name="defaultSkin">mySkin</property>
<property name="availableSkins">
<b><value>mySkin</value></b>
<value>laguna</value>
<value>darkX</value>
<value>glassX</value>
<value>blueSky</value>
<value>classic</value>
<value>ruby</value>
<value>wine</value>
<value>deepMarine</value>
<value>emeraldTown</value>
<value>japanCherry</value>
</property>
[/code]
If you just want to select the new skin as the fixed skin, you would just edit the web.xml file and select the new skin by inserting the name into the context parameter (as explained before).

Just to make an (bad looking, but understandable) example, let’s change some parameters in the skin file:

[code] # Colors
headerBackgroundColor=#005000
headerGradientColor=#70BA70
headerTextColor=#FFFFFF
headerWeightFont=bold

generalBackgroundColor=#f1f1f1
generalTextColor=#000000
<b>generalSizeFont=18px</b>
generalFamilyFont=Arial, Verdana, sans-serif

controlTextColor=#000000
controlBackgroundColor=#ffffff
additionalBackgroundColor=#E2F6E2

shadowBackgroundColor=#000000
shadowOpacity=1

panelBorderColor=#C0C0C0
subBorderColor=#ffffff

tabBackgroundColor=#ADCDAD
tabDisabledTextColor=#67AA67

trimColor=#BBECBB

tipBackgroundColor=#FAE6B0
tipBorderColor=#E5973E

selectControlColor=#FF9409
generalLinkColor=#43BD43
hoverLinkColor=#FF9409
visitedLinkColor=#43BD43

# Fonts
<b>headerSizeFont=18px</b>
headerFamilyFont=Arial, Verdana, sans-serif

tabSizeFont=11
tabFamilyFont=Arial, Verdana, sans-serif

<b>buttonSizeFont=18</b>
buttonFamilyFont=Arial, Verdana, sans-serif

tableBackgroundColor=#FFFFFF
tableFooterBackgroundColor=#cccccc
tableSubfooterBackgroundColor=#f1f1f1
tableBorderColor=#C0C0C0
<b>tableBorderWidth=2px</b>

#Calendar colors
calendarWeekBackgroundColor=#f5f5f5

calendarHolidaysBackgroundColor=#FFEBDA
calendarHolidaysTextColor=#FF7800

calendarCurrentBackgroundColor=#FF7800
calendarCurrentTextColor=#FFEBDA

calendarSpecBackgroundColor=#E2F6E2
calendarSpecTextColor=#000000

warningColor=#FFE6E6
warningBackgroundColor=#FF0000

editorBackgroundColor=#F1F1F1
editBackgroundColor=#FEFFDA

#Gradients
gradientType=plain
[/code]

Here is the screenshot of what happened with the new skin:

richfaces-3How do I know which parameters to change? The official RichFaces Developer Guide contains, for every component, a table with the correspondences between the skin parameters and the CSS properties they are connected to.

Using CSS

What about when we need to change just a specific component’s look? And what if we need to change it just for a specific page?. In these cases, we can use the CSS framework to accomplish the tasks. For the first case, we can redefine the skin-inserted CSS classes, and for the second, we can specify our specific CSS classes for every component.

Redefine the skin-inserted CSS classes

Let’s come back to our example, we want to change the background for all of the panel headers. In the official RichFaces Developer Guide, we can see that we have to redefine the CSS class rich-panel-header. Let’s open the /view/stylesheet/theme.css and add the following code:

[code] .rich-panel-header {
color: #FF0000;
background: #9999ff repeat scroll 0 0;
}
[/code]

The result is as follows:

richfaces-4By now, all of the rich:panel components have a new header redefined by the CSS class.

Specify our specific CSS classes

If we want to change the style for a specific component, we can just pass our custom CSS classes using the *Class attributes. In order to give an example, we are going to customize just the rich:toolBar component of the All contacts table—let’s open the /view/stylesheet/theme.css file and add our custom CSS class as follows:

[code] .my -custom-toolbar {
background: #cccc00 repeat scroll 0 0;
}
[/code]

Now, let’s open the /view/main/contactsList.xhtml file and set the styleClass attribute with our newly created CSS class:

[code lang=”html”] …
<rich:toolBar styleClass="my-custom-toolbar">
…
[/code]

The result of this customization is as shown in the following screenshot:

richfaces-5You can see that only the All contacts table toolbar is customized.

You can also insert inline CSS code using the style attribute of the component:

[code lang=”html”]
…
<rich:toolBar styleClass="my-custom-toolbar"
<b>style="border: 2px solid #FF0000;"></b>
…
[/code]

You can see the following result:

richfaces-6Even if we change the skin, our custom CSS settings will still be valid:

richfaces-7

Using skins with non-skinnable components

The skinnability feature works only for RichFaces components, so, the same problems for which this feature was created would be found using other framework components (also using the standard JSF ones!). In order to be able to use the skin parameters also for non-RichFaces components, the framework declares an object called richSkin that permits access to the skin values.

Let’s see this code as an example:

[code] #{richSkin.tabBackgroundColor}[/code]

Therefore, if we have a seam div component (s:div) and we still want to use the border color defined by the skin, we can use this code:

[code lang=”html”] <s:div
style="border: 10px solid #{richSkin.panelBorderColor}">
<h:outputText value="Example text" />
</s:div>
[/code]

And the color will be the one selected by our skin, so, for our new custom skin it will be as follows:

richfaces-8Instead, for the japanCherry skin, it will be:

richfaces-9

Standard controls skinning

For the s tandard XHTML controls, we have the options of customizing the style the RichFaces way.

RichFaces, in fact, unifies the application’s appearance by skinning the standard HTML elements the same way it does with the other components of the library.

There are two levels of skinning:

  • Standard: For customizing only the basic properties (applies to IE 6, IE 7 in BackCompat mode and Safari)
  • Extended: For customizing more properties with more styles (it applies to Mozilla Firefox and IE 7 in standards-compliant mode)

In order to activate the Standard controls skinning, it is sufficient to add a new context-param inside the web.xml file, like this:

[code lang=”html”] <context-param>
<param-name>org.richfaces.CONTROL_SKINNING</param-name>
<param-value>enable</param-value>
</context-param>
[/code]

This will enable the feature for our application.

Enabling the parameter in our application will skin the standard controls from this:

richfaces-10So it appe ars like this:

richfaces-11If you want to customize the standard controls using the CSS framework, you can also enable the org.richfaces.CONTROL_SKINNING_CLASSES context parameter (inside the web.xml file)—by doing so, you will be able to edit a set of CSS classes for skinning the XHTML components (some examples of CSS classes you can redefine are rich-select, rich-input-text, and so on that follow the rich-[-] pattern).

Extended s kinning in Opera and Safari
In order to resolve some problem with extended skinning in Opera and Safari, you can activate a JavaScript script that detects the browser and enables extended skinning only where supported. For doing that, just add the following code to the XHTML page (in our case, we would add it to the /view/layout/template.xhtml file):
[code lang=”html”]
<script type="text/javascript">
window.RICH_FACES_EXTENDED_SKINNING_ON = true;
</script>
[/code]

XCSS

Another way to use skin properties values for CSS classes is the XCSS. It is an XML version of the CSS used to extend the CSS feature and add extra functionalities. It is widely used inside the RichFaces framework, because of its fl exibility. In short, it is an XML version of the CSS file that contains skin parameters and dynamic resource generator classes. It is automatically converted in a standard CSS file suitable for all browsers.

In our application, you can open the /view/stylesheet/theme.xcss file and look at the definition created by Seam-gen for the project. As you can see, you have to use the and XML tags to create a CSS selector. Let’s see the following code for example:

This will read the values from the current skin and produce the following CSS code (if mySkin is selected):

[code].rich-panel-header {
background-color: #005000;
color: #FFFFFF;
}
[/code]

As you can see, the name attribute of the u:selector tag defines the CSS selector name, and the name attribute of the u:style tag defines the name of the CSS property. You can also use comma-separated CSS selector names into the u:selector name attribute to specify more selector at a time:

[code lang=”html”]
<u:selector name=".rich-panel-header, .rich-panel-body">
…
[/code]

Another feature is the possibility to use Java resources inside the CSS to dynamically generate images; in theme.xcss, you can find some examples to generate gradients:

[code lang=”html”]
<u:selector name=".rich-table-subheadercell">
<u:style name="background-image">
<f:resource f:key="org.richfaces.renderkit.images.TabGradientB"/>
</u:style>
</u:selector>
[/code]

XCSS is very powerful and extends the CSS framework for skinning every component we need to skin!

[code lang=”html”][/code]Summary

In this chapter, we’ve seen all the powerful customization capabilities that the RichFaces framework offers. In the next chapter, we will create a new skin using the plug ‘n’ skin technology.

Filed Under: JSF Tagged With: Richfaces

Creating simple toolbar using RichFaces tag library

July 19, 2008 by Krishna Srinivasan Leave a Comment

rich:toolBar, rich:dropDownMenu and rich:menuItem

This example demonstrates how to create simple toolbar using RichFaces tag library. RichFaces provides predefined tags like rich:toolBar which will be easily plugged into our webpages to display the toolbar component. Apart from rich:toolBar, to create menus we have to use other tags rich:dropDownMenu and rich:menuItem.

also read:

  • Introduction to JSF
  • JSF Interview Questions
  • Request Processing Lifecycle phases in JSF

rich:dropDownMenu is used for creating the group of menus and inside that use rich:menuItem to add a single menu. You can view the image in this article bottom to know how it looks like.

richfaces.jsp

[code lang=”html”]
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@ taglib prefix="rich" uri="http://richfaces.org/rich" %>
<%@ taglib prefix="a4j" uri="http://richfaces.org/a4j"%>
<html>
<body>
<f:view>
<h:form>
<rich:toolBar>
<rich:dropDownMenu>
<f:facet name="label">
<h:outputText value="File"/>
</f:facet>
<rich:menuItem value="New"/>
<rich:menuItem value="Open"/>
<rich:menuItem value="Exit"/>
</rich:dropDownMenu>
<rich:dropDownMenu>
<f:facet name="label">
<h:outputText value="Edit"/>
</f:facet>
<rich:menuItem value="Find"/>
<rich:menuItem value="Replace"/>
</rich:dropDownMenu>
</rich:toolBar>
</h:form>
</f:view>
</body>
</html>
[/code]

view in browser

rich-1

Filed Under: JSF Tagged With: Richfaces

Use rich:datascroller for rich:dataTable pagination

July 18, 2008 by Krishna Srinivasan Leave a Comment

rich:datascroller and rich:dataTable

rich:dataTable tag is the RichFaces version for datatable component which has few extra features on look and feel.One of the difficulty JSF developers is creating good pagination for the data dsiplayed using rich:datatable. To resole this problem, RichFaces tags library provides rich:datascroller component which can display the automatic paginations based on data populated using rich:dataTable.

also read:

  • Introduction to JSF
  • JSF Interview Questions
  • Request Processing Lifecycle phases in JSF

This tips shows very basic working example using rich:datascroller.for attribute in the rich:datascroller is used for mapping to corresponding rich:dataTable. rows attribute in the dataTable used for displaying the number of rows in each page. There is many attributes in rich:datascroller to manipulate the look and the way it is diplaying data.

richfaces.jsp

[code lang=”html”]
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@ taglib prefix="rich" uri="http://richfaces.org/rich" %>
<%@ taglib prefix="a4j" uri="http://richfaces.org/a4j"%>
<html>
<body>
<f:view>
<h:form>
<rich:datascroller for="sampleData" maxPages="10"/>
<rich:dataTable id="sampleData" value="#{richBean.employees}" var="loc" rows="10">
<rich:column>
<h:outputText value="#{loc.empId}"/>
</rich:column>
<rich:column>
<h:outputText value="#{loc.empName}"/>
</rich:column>
<rich:column>
<h:outputText value="#{loc.dept}"/>
</rich:column>
</rich:dataTable>
</h:form>
</f:view>
</body>
</html>[/code]

JavaBeatRichfacesBean.java

[code lang=”java”]
package javabeat.net.richfaces;

import java.util.ArrayList;
import java.util.List;

/**
* source : www.javabeat.net
*/
public class JavaBeatRichfacesBean {
private List<employee> employees;

public List<employee> getEmployees() {
this.employees = new ArrayList<employee>();
Employee employee = null;
for (int i = 0;i<50;i++)
{
employee = new Employee();
employee.setEmpId(String.valueOf(i));
employee.setEmpName("Name : " + i);
employee.setDept("JSF");
employees.add(employee);
}
return employees;
}

public void setEmployees(List<employee> employees) {
this.employees = employees;
}

}
[/code]

faces-config.xml

[code lang=”xml”]
<?xml version=’1.0′ encoding=’UTF-8′?>
<faces-config version="1.2"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
<managed-bean>
<managed-bean-name>richBean</managed-bean-name>
<managed-bean-class>javabeat.net.richfaces.JavaBeatRichfacesBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
[/code]

Filed Under: JSF Tagged With: Richfaces

How to set selected tab in rich:tabPanel tag?

April 12, 2008 by Krishna Srinivasan Leave a Comment

  • Topic : Java Server Faces (JSF), RichFaces, Ajax4Jsf
  • Environment : J2EE 5.0, MyFaces 1.1.5, RichFaces 3.1.0

rich:tabPanel

also read:

  • Introduction to JSF
  • JSF Interview Questions
  • Request Processing Lifecycle phases in JSF

This example illustrates how to set the selected tab in rich:tabPanel. This tag is used for creating the multiple tabs
with in same page and allowing user to populate the each tab with different data. RichFaces provides three types of mechanism to fetch the data from server. They are: client,server and ajax. These values are used in the attribute called switchType. Our example uses switchType as client.

switchType=”client”

If the switchType is “client”, then all the data will be reterived from the server and stored in the client. When you select different tabs, javascript is used for dsiplaying the data. This is the fastest solution compare to other approaches.

switchType=”server”

If the switchType is “server”, then the data will be reterived from the server for every request. The page will be refreeshed for
the each request.

switchType=”ajax”

If the switchType is “ajax”, then the data will be reterived from the server for ever request. The page will not be refreeshed for the
each request because we are using ajax call to the server.

selectedTab attribute

selectedTab attribute is used for setting the default selected tab in the rich:tabPanel. If you are not providing the
correct tab name to this attribute, it will throw java.lang.IllegalStateException: No active tabs!.

specifies the default tab as “Tabname1”. The “TabName1” is
the name of the tabs used in rich:tab.

selectedTab.jsp

[code lang=”html”]

<!–
Source : www.javabeat.net
–>

<html>
<body>
<f:view>
<h:form id="select">
<rich:tabPanel selectedTab="TabName1" switchType="client">
<rich:tab name="TabName1" label="Java">
<!– Tab content here –>
<h:outputText value="Sample Text 1"/>
</rich:tab>
<rich:tab name="TabName2" label="J2EE">
<!– Tab content here –>
<h:outputText value="Sample Text 2"/>
</rich:tab>
<rich:tab name="TabName3" label="Java Server Faces">
<!– Tab content here –>
<h:outputText value="Sample Text 3"/>
</rich:tab>
</rich:tabPanel>
</h:form>
</f:view>
</body>
</html>

[/code]

Filed Under: JSF Tagged With: Richfaces

Introduction to Ajax4Jsf

June 27, 2007 by Krishna Srinivasan Leave a Comment

Java Server Faces provided a Component Based Architecture for building User Interface Components for the Web Application. Ajax aims in providing Faster Response to the Client Applications by reloading only the needed Data. Wouldn’t be nice to take the advantages of both Jsf and Ajax for developing Robust Web Applications. Ajax4Jsf provides solution for this. It is the integration of Java Server Faces with Ajax (which stands for Asynchronous JavaScript and Xml), thereby providing Ajax Support to the Jsf UI Components. This article attempts to provide an overview of the Ajax4Jsf Framework which is now an open Source Project in the JBoss Community.

also read:

  • Introduction to Java Server Faces
  • Request Processing Lifecycle phases in JSF
  • Accessing Web Services from JSF applications
  • Navigation model in JSF

2) What is Ajax4Jsf?

Before trying into Ajax4Jsf, it is wise to know about the various pieces of technologies upon which Ajax4Jsf is built. From the name of the Framework itself, one should identity that Ajax (Asynchronous JavaScript and Xml) and Jsf (Java Server Faces), the most two popular technologies, are embedded within it. Let us look into these two technologies first, before delving deep into Ajax4Jsf.
Java Server Faces provides a Component Based Framework for managing and developing User Interface Components in a Web Application. It also provides rich set of Functionalities that includes Event Handling, Configuring the Page Navigation Mechanism, Validation of Client Data, Data Conversion etc. It also provides a Pluggable Architecture wherein Developers can develop their own Custom User Interface Components and plug with ease into the Framework. One of the major features of the Jsf Framework is that it is not targeted to one type of Clients. It means that apart from Html Browser Clients for the Desktop, it is even possible to have Wml Browser Clients for the mobile phones.
Ajax which stands for Asynchronous JavaScript and Xml is not new. A smarter way of using the existing standards/technologies like JavaScript, Xml and Html gave birth to Ajax. Using Ajax, it is possible for the JavaScript Code to directly communicate with the Server End. The request and the response data between Client and Server is exchanged in Xml Format. One of the major advantages of using Ajax is that it is speed up the performance of the Web Application by loading only the portion of the Web Page in consideration, thereby establishing better results.
Now it’s time to have a look on Ajax4Jsf. As one would have guessed, Ajax4Jsf is a Framework, which, when included in a Web Application will add Ajax support for the Jsf Components. Since Jsf is a Component Based Framework, it is easy to Construct Additional Components which provided Ajax Support to the Jsf Pages. So, all the Components in the Ajax4Jsf Library are nothing but extension to Jsf Components. The transparent use of Java Script Code along with Xml Http Request Objects will be taken care by the Framework itself which means that Developer don’t have to mix Java Script Code into their Application. Let us look into the Internals of the Ajax4Jsf Framework in detail in the next section.

3) Ajax4Jsf Internals

Before looking into the Ajax4Jsf internals, let us look briefly into the Architecture of Jsf. It is worth to look into the Architecture of Jsf first before getting into the details.
In Java Server Faces, whenever a Client makes a Request comes for a Resource, it is intercepted by the Faces Servlet (as represented by the javax.faces.webapp.FacesServlet). This Servlet will make the Client Request that will go through the six different Life cycle Phases like View Restoration Phase, Applying the Request Values, Validation of User Inputs, Updating the Model Objects, Execution of Application and finally Response Rendering. Ajax4Jsf is a framework that adds support to existing Jsf Application. In fact, Ajax4Jsf Framework is implemented as a Filter thereby adding JavaScript function and XmlHttpObject dependencies to the existing Jsf Components. But when the Request is a Ajax4Jsf Request, the whole things changes. Specially, whenever a Request is made by the User, a Java Script Event is fired which is processed by the Ajax Engine that usually sits in the Client Side. Now it’s the Job of the Ajax Engine to submit to original Request to the Ajax4Jsf, which means that the Request will be intercepted by the Ajax4Jsf Filter. Then the Conversion of the Data to the Xml Format will take place here through the various Xml Filters after which the Request is forwarded to the original Faces Servlet thereby making the Request to go through Several Phases.
In the Ajax4Jsf Framework, there are so-called Ajax Containers which represents a Tree of Components along with Request Values that is encoded and decoded during Ajax Request and Response. It is because of the availability of Ajax Engine in the Client updates to portion of Areas in the Web Page is possible.

4) Exploring the Ajax4Jsf Library

This section is dedicated in looking over the Ajax4Jsf Tags for the various Functionalities. Most of the Tags in this Library provide an alternate means for representing the same functionality as achieved by Jsf Tags. Either of the two Tags can be used in such a situation. It is hard to classify the set of tags based on the functionalities and the following sections attempt to provide a brief description about the most commonly used Tags along with some sample snippets.

4.1) Region Tag

Not all the Client Data in a Page is needed by the Server for processing. In most of the cases, only Data from a Portion of a Page is sufficient to process that particular request. This is where the Ajax Region Tag comes into picture. It is a kind of Container Tag meaning that it can hold other Type of Component tags. When components are defined in this Tag, only the values for these components are processed in the Server Side when an Ajax Request is made.
By default, if there is no definition for a Region Tag in a JSP page, then the whole of the JSP Page will be taken as the Ajax Region. Multiple Region Tags within the same Page is also possible.
Following code snippet shows the usage of this Tag,

[code lang=”html”]<a4j:region id = "employeeRegion" actionListener = "#{manager.processEmpData}">
<!– Other Set of Components –>
</a4:region>

<a4j:region id = "stockRegion" actionListener = "#{manager.processStockData}">
<!– Other Set of Components –>
</a4:region>[/code]

In the above code, we have defined two regions, one is the 'employeeRegion' and the other one is the 'stockRegion'. Whenever an Ajax Request is made for the 'employeeRegion' (or 'stockRegion'), then the portion of Data available only with the 'employeeRegion' will be sent to the server (Manager. processEmpData() method) for processing.

4.2) Command Button Tag

This represents a Button Component and can be used to fire Action Events on the Server. This is very similar to the Jsf Command Button Tag, but instead of generating Jsf Request, an Ajax Request will be generated upon Button Click which will be intercepted by the Ajax Engine. There is a useful attribute called 'oncomplete' which can contain JavaScript Code or a JavaScript Function that will get executed once the response comes from the Server.
All the Events like Change Events, Key Events, and Mouse Events etc are applicable to this Tag through the usage of various attributes. The property called 'reRender' will take a comma separated list of Component Identifier that will get re-rendered as soon as control comes from the Server back to the Client.
Following is the code snippet demonstrating the usage of Command Button Tag,

[code lang=”html”]<a4j:commandButton id = "clickButton" value = "Click Me"
action = "#{Listener.processClickRequest}" oncomplete = "jsFunction()">
reRender = "CompId1, CompId2, CompId3"
</a4j:commandButton>[/code]

In the above code, whenever the Button with value 'Click Me' is activated, the method processClickRequest() within the Listener class gets invoked. After that the Components as represented by the Component Ids (CompId1, CompId2 and CompId3) will get the updated value from the Server. Then finally, the Java Script function jsFunction() as mentioned in the 'oncomplete' attribute will be invoked.

4.3) Command Link Tag

There is no great difference between the Command Button and the Command Link apart from their representation, as both manifests a form of Action Components. All the properties that are applicable to Command Button are applicable to Command Link also.
The following code snippet shows the usage of this Component,

[code lang=”html”]<a4:commandLink id = "myLink" value = "This is my Link"
action = "Listener.processMyLink">
</a4:commandLink>[/code]

4.4) Media Output Tag

While the output Text Tag is used to pour normal Character contents, this Tag is used to render Rich Contents back to the Client in the form of Image, Audio or Video. To achieve this, the attribute 'createContent' must provide a method which takes two arguments of type java.io.OuputStream and java.lang.Object. Following is the usage for the same,

[code lang=”html”]<a4j:mediaOutput id = "telephone" element = "img" mimeTye = "image/png"
createContent = "#{ImagePainter.drawImage}">
</a4j:mediaOutput>[/code]

In the above code snippet, the attribute 'element' can take these possible set of values (‘anchor’, ‘image’, ‘object’, ‘applet’) which represents the name of the Html Element that should be used to render this image. Note that 'mimeType' being pointed to image/png file, since we are going to create an array of bytes from an image file that is of type png. Considering the 'createContent' attribute, it takes a Jsf EL Expression whose method takes OutputStream and Object as arguments. Following is the code for the same,
ImagePainter.java

[code lang=”java”]package net.javabeat.articles.ajax4jsf.introduction;

import java.io.*;

public class ImagePainter {

private String fileName = "telephone.png";

public void drawImage (OutputStream output, Object object) throws IOException{

File file = new File(fileName);
byte byteArray[] = new byte[1000];

FileInputStream inputStream = new FileInputStream(file);
while(true){
try{
int bytesRead = inputStream.read(byteArray);
output.write(byteArray, 0, bytesRead);
}finally{
if (inputStream != null){
inputStream.close();
}
}
}
}
}
[/code]

Note that the OutputStream object which is passed as an argument to the drawImage() method should be populated with the byte array pointing to the Image Resource.

4.5) Keep Alive Tag

Assume that a Managed Bean Component has been declared with 'Request' scope in the Configuration File with the help of <managed-bean-scope> tag. Then the Life-time of this Bean Object is valid only for the Current Request. Any attempt to make a reference to the Bean Object after the Request ends will throw in Illegal Argument Exception by the Server because the Bean Object is now invalid.
To avoid these kinds of Exceptions being happening, we can depend on the Keep Alive Tag which is used to maintain the state of the Whole Bean object among subsequent Request. Following is the code snippet for the same,

[code lang=”html”]<a4j:keepAlive beanName = "#{manager.empBean}">
</a4j:keepAlive>[/code]

Note that the attribute must point to a legal Jsf EL Expression which resolves to a Managed Bean instance. For example for the above code the Class definition may look like this,
Manager.java

[code lang=”java”]class Manager{

private EmployeeBean empBean;
// Getters and Setters for empBean.

}[/code]

4.6) Repeat Tag

The Tag implements the Basic Iteration Operation and it is generally preferred to Display a Set of Objects found in a Collection. It is very similar to the functionality available in <h:dataTable> Component. Following is usage scenario for this Tag.

[code lang=”html”]<a4j:repeat id = "repeater" value = "#{manager.empList}" var = "employee">
<h:outputText id = "name" value = "#{employee.name}"/>
<h:outputText id = "age" value = "#{employee.age}"/>
</a4:repeat>[/code]

Assume that we have a Class called Manager which represents a Collection of Employee objects holding two properties namely name and age. Following is the structure of the Manager Class.
Manager.java

[code lang=”java”]public class Manager{

private List<Employee> employees;
// Getters and setters for employees;

}[/code]

Employee.java

[code lang=”java”]public class Employee{

private String name;
private int age;

// Getters and Setters for name and age

}[/code]

If suppose, we want to display the list of Employees in a Page then we can use the Repeat Tag. The 'value' attribute in the Tag usually represents a Collection and the 'var' attribute can be assumed to hold an element from the Collection object. This tag is identically equivalent to a 'for' loop.

[code lang=”java”]for (Employee employee : manager.getEmployees() ){
display(employee.getName());
display(employee.getAge());
}[/code]

4.7) Poll Tag

The Poll Tag is used to Auto Refresh the Current Page by sending Periodic Request to the Server at Regular Intervals by submitting the Form. This can be used in Pages where the View should provide Up-to-Date Information like the Stock Value, Cricket Scores etc. Following is the code snippet demonstrating this Tag.

[code lang=”html”]<a4j:poll id = "refreshId" reRender = "CompId1, CompId2" timeout = "50000"
interval = "1000">
</a4j:poll>[/code]

In the above one, the Page will be refreshed automatically after every 1 second (as mentioned in the 'interval' attribute). Note the 'timeout' attribute set to 50 seconds, which means that after 50 seconds the page would stop to Auto Refresh. The List of Components that are to be re-rendered is specified in the 'reRender' attribute.

4.8) Status Tag

The Status Tag can be used as a kind of Indication to the Client about the current Status of the Request, like whether the Request is still being processed by the Server or the Request has been served. Following is the sample code illustrating the same,

[code lang=”html”]<a4j:status startText = "Request sent to the Server" stopText = "Request is completed">
</a4j:status>
[/code]

In the above case, whenever the Client initiates a Request then the message ‘Request sent to the Server’ (as represented by 'startText' attribute) is displayed until the Request is completely processed in which case the message ‘Request is Completed’ (as represented by 'stopText' attribute) is displayed.

4.9) Support Tag

The mostly commonly used Tag in the Ajax4Jsf Library is the Support which provides Ajax Support to the Jsf Components. It always appears as a Child Tag for the various Jsf Components. Following listing provides the usage of this Tag,

[code lang=”html”]<a4j:inputText id = "userInput">
<a4j:support event = ‘onblur’ action = "#{bean.process}"
binding = "bean.userInput" reRender = "CompId1, CompId2"/>
</a4j:inputText>[/code]

In the above sample, whenever the focus is lost for the user input text Field Component, and then the corresponding process method in the Bean class will be invoked. The 'reRender' attribute defines a list of components whose values are to be updates once the request is over. Note the usage of the 'binding' attribute. This attribute resolves to an EL Expressing which maps to the UIInput Control of the Component represented by userInput. Following is the structure in which the Bean class may look like,
Bean.java

[code lang=”java”]public class Bean{

private UIInput userInput;
//Getters and Setters

}[/code]

5) Sample Application

5.1) Introduction

In this section, let us walk through a Sample Application that makes use of the Ajax4Jsf Libraries. Let the keep the functionalities of this Sample Application to a simpler extent. This is a kind of Auto Complete Application in which whenever the User gives the Bank Account Number, the corresponding details like the name of the Bank, its Branch Name, Customer Name, Balance Details, Contact Details etc will be fetched from the Server. The more important thing to note that is the Request that is sent to the Server is not a normal Jsf Request but instead it is a Ajax Request.

5.2) Web Application Descriptor File

As seen previously, the Ajax4Jsf provides a Filter Servlet for adding Ajax capability for the Jsf Components. So, the web.xml should include a 'filter' tag about the various information about the Filter Servlet.
web.xml

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

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

<filter-mapping>
<filter-name>ajax4jsf</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>

<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>30</session-timeout>
</session-config>

<!– Welcome files –>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>[/code]

As we can see from the above Xml File, apart from the normal Faces Servlet information, a Filter Servlet has been embedded to add Ajax capabilities for the Client Requests.

5.3) Faces Configuration File

The Faces Configuration file (faces-config.xml) contains only one entry that represents a Managed Bean object. As we will see in the later sections, this Managed Bean will contain the logic for creating some Dummy Account Information as well as contains the logic for fetching the appropriate Account Information. Following is the code for faces-config.xml file.
faces-config.xml

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>

<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

<managed-bean>
<managed-bean-name>accountSearcher</managed-bean-name>
<managed-bean-class>
net.javabeat.articles.ajax4jsf.introduction.AccountSearcher
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>[/code]

5.4) Jsp File containing Jsf and Ajax4Jsf Tags

The following Jsp page presents an Interface to the user, when the User is given a Text-Field prompting to enter the Account Information. If the Account Number entered in valid, which is done by comparing the list of Account Objects, then the corresponding related Information of the Account will be populated in the View.
index.jsp

[code lang=”html”]<html>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="https://ajax4jsf.dev.java.net/ajax" prefix="a4j" %>

<f:view locale="en">
<head>
<title>Account Details</title>
</head>

<body>

<h:form id="form">

<h2>Enter the Account number and tab out for getting further information</h2>

<h:panelGrid columns="2">

<h:outputLabel for = "AccountNo" value = "Account Number:"/>
<h:inputText id = "AccountNo"
binding = "#{accountSearcher.accountTextField}"
size = "6" required="true">
<f:validateLength minimum="6" maximum="6"/>
<f:convertNumber type = "number" />
<a4j:support event = "onblur" immediate="true"
actionListener = "#{accountSearcher.search}"
reRender = "BankName, CustName, BranchName, OpenDate,
ClosingBalance, Address, EmailId, PhoneNumber"/>
</h:inputText>

</h:panelGrid>

<hr>
<p>Bank Details:

<h:panelGrid columns="2">

<h:outputLabel for = "BankName" value = "Bank Name:"/>
<h:inputText id = "BankName" size="25"
binding = "#{accountSearcher.bankNameTextField}"
value = "#{accountSearcher.account.bankName}"/>

<h:outputLabel for = "CustName" value = "Customer Name"/>
<h:inputText id = "CustName" size="15"
binding = "#{accountSearcher.customerNameTextField}"
value = "#{accountSearcher.account.customerName}"/>

<h:outputLabel for = "BranchName" value = "Branch Name"/>
<h:inputText id = "BranchName" size="15"
binding = "#{accountSearcher.branchNameTextField}"
value = "#{accountSearcher.account.branchName}"/>

<h:outputLabel for = "OpenDate" value = "Open Date"/>
<h:inputText id = "OpenDate" size="15"
binding = "#{accountSearcher.openDateTextField}"
value = "#{accountSearcher.account.openDate}"/>

<h:outputLabel for = "ClosingBalance" value = "Closing Balance"/>
<h:inputText id = "ClosingBalance" size="15"
binding = "#{accountSearcher.closingBalanceTextField}"
value = "#{accountSearcher.account.closingBalance}"/>

</h:panelGrid>

<hr>
<p>Contact Details:

<h:panelGrid columns="2">

<h:outputLabel for = "Address" value = "Address"/>
<h:inputTextarea id = "Address"
binding = "#{accountSearcher.addressTextArea}"
value = "#{accountSearcher.account.address}"/>

<h:outputLabel for = "EmailId" value = "EMail Id"/>
<h:inputText id = "EmailId" size="15"
binding = "#{accountSearcher.emailIdTextField}"
value = "#{accountSearcher.account.emailId}"/>

<h:outputLabel for = "PhoneNumber" value = "Phone Number"/>
<h:inputText id = "PhoneNumber" size="15"
binding = "#{accountSearcher.phoneNumberTextField}"
value = "#{accountSearcher.account.phoneNumber}"/>

</h:panelGrid>

</h:form>
</body>

</f:view>

</html>[/code]

The main thing to observe in the Jsp Page is for the <a4j:support> tag which is embedded within the <h:inputText> tag representing the Account Number. Since we want support for the Account Number Text-Field we have done like this. That’s all, just by adding this support Tag within the Jsf UI Components, automatically Ajax Support will be applicable to the JSF UI Components. The attribute 'event' is set to 'onblur' which means that the corresponding listener method as represented by the 'actionListener' attribute (search() defined inside the AccountSearcher class) will be called when the focus is lost from the Text Field control (which means after tabbing out from the Control). The most significant attribute is the support tag is the 'reRender' attribute which takes a comma separated list of Component Identifiers that want to be re-rendered once the control returns back from the Server.
The 'binding' attribute evaluates to a Jsf EL Expression, if specified will map to the corresponding UI Component in the Backing Bean Class. For example, consider the following code snippet,

[code lang=”html”]<h:inputText id = "AccountNo" binding = "#{accountSearcher.accountTextField}">
</h:inputText>[/code]

The binding expression is given as "#{accountSearcher.accountTextField}, which means that the Input Control directly maps to a property by name accountTextField in the AccountSearcher class which is of type javax.faces.component.UIInput. Following is the Java Code for the same,
AccountSearcher.java

[code lang=”java”]public class AccountSearcher {

private UIInput accountTextField;
// Getters and Setters for the same.

}
[/code]

5.5) Account.java

Following is the class that encapsulates pieces of information like Account Number, Bank Name, Customer Name, Branch Name, Account Opening Date, Contact Information inside the Account class. Following is the complete Listing for the Account.java class.
Account.java

[code lang=”java”]package net.javabeat.articles.ajax4jsf.introduction;

import java.util.Date;

public class Account {

private long accountNo;
private String bankName;
private String customerName;
private String branchName;
private String openDate;
private double closingBalance;
private String address;
private String emailId;
private String phoneNumber;

public Account() {
}

public long getAccountNo() {
return accountNo;
}

public void setAccountNo(long accountNo) {
this.accountNo = accountNo;
}

public String getBankName() {
return bankName;
}

public void setBankName(String bankName) {
this.bankName = bankName;
}

public String getCustomerName() {
return customerName;
}

public void setCustomerName(String customerName) {
this.customerName = customerName;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getEmailId() {
return emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

public String getBranchName() {
return branchName;
}

public void setBranchName(String branchName) {
this.branchName = branchName;
}

public String getOpenDate() {
return openDate;
}

public void setOpenDate(String openDate) {
this.openDate = openDate;
}

public double getClosingBalance() {
return closingBalance;
}

public void setClosingBalance(double closingBalance) {
this.closingBalance = closingBalance;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}[/code]

5.6) AccountCreator.java

This Utility Class is used to create Dummy Account Information Objects and acts as Storage for those Account Objects. When looked-up for an Account object by giving the Account Number as a Key, the appropriate Object is returned. The Managed Bean references this Class heavily for creating and retrieving Account Objects. Following listing is the complete code for AccountCreator.java
AccountCreator.java

[code lang=”java”]package net.javabeat.articles.ajax4jsf.introduction;

import java.util.HashMap;
import java.util.Map;

public class AccountCreator {

private static Map<Long, Account> accounts;

public static void createTestAccounts(){
if (accounts == null || accounts.isEmpty()){
accounts = new HashMap<Long, Account>();
}

Account account = null;
account = createAccountInfo(123456, "Hdfc Bank",
"Jenny", "Shastri Nagar, Chennai",
"10/05/2003", 100033.53, "Address1",
"jenny@gmail.com", "99123456789");
accounts.put(account.getAccountNo(), account);

account = createAccountInfo(234567, "Icici Bank",
"Joseph", "Besant Nagar, Chennai",
"121/09/2001", 3200033.53, "Address2",
"joseph@gmail.com", "99987654321");
accounts.put(account.getAccountNo(), account);
}

private static Account createAccountInfo(long accountNo, String bankName,
String customerName, String branchName, String openDate,
double closingBalance, String address, String emailId, String phoneNumber){

Account account = new Account();
account.setAccountNo(accountNo);
account.setBankName(bankName);
account.setCustomerName(customerName);
account.setBranchName(branchName);
account.setOpenDate(openDate);
account.setClosingBalance(closingBalance);
account.setAddress(address);
account.setEmailId(emailId);
account.setPhoneNumber(phoneNumber);
return account;
}

public static Account getAccountInfo(Long accountNo){
return accounts.get(accountNo);
}
}[/code]

5.7) Account Searcher.java

This Managed Bean takes care of creating Dummy Account Objects and it returns the appropriate Account Information back to the Client upon Request. Most of the code in this class represents the getters and the setters for the various UI Components in the Jsp Page. The search logic is implemented in the search() method which takes ActionEvent as its only parameter. Following is the code for the same.
AccountSearcher.java

[code lang=”java”]package net.javabeat.articles.ajax4jsf.introduction;

import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

public class AccountSearcher {

private Account account;

private UIInput accountTextField;
private UIInput bankNameTextField;
private UIInput customerNameTextField;
private UIInput branchNameTextField;
private UIInput openDateTextField;
private UIInput closingBalanceTextField;
private UIInput addressTextArea;
private UIInput emailIdTextField;
private UIInput phoneNumberTextField;

public AccountSearcher() {
AccountCreator.createTestAccounts();
}

public void search(ActionEvent actionEvent){

String strAccountNo = (String)getAccountTextField().getSubmittedValue();
long accountNo = 0L;
try{
accountNo = Long.parseLong(strAccountNo);
account = AccountCreator.getAccountInfo(accountNo);
if (account != null){
setComponentsValueToNull();
}else{
// Error Message.
}
}catch(Exception exception){
exception.printStackTrace();
}
}

private void setComponentsValueToNull(){
bankNameTextField.setSubmittedValue(null);
customerNameTextField.setSubmittedValue(null);
branchNameTextField.setSubmittedValue(null);
openDateTextField.setSubmittedValue(null);
closingBalanceTextField.setSubmittedValue(null);
addressTextArea.setSubmittedValue(null);
emailIdTextField.setSubmittedValue(null);
phoneNumberTextField.setSubmittedValue(null);
}

public Account getAccount() {
return account;
}

public void setAccount(Account account) {
this.account = account;
}

public UIInput getAccountTextField() {
return accountTextField;
}

public void setAccountTextField(UIInput accountTextField) {
this.accountTextField = accountTextField;
}

public UIInput getBankNameTextField() {
return bankNameTextField;
}

public void setBankNameTextField(UIInput bankNameTextField) {
this.bankNameTextField = bankNameTextField;
}

public UIInput getCustomerNameTextField() {
return customerNameTextField;
}

public void setCustomerNameTextField(UIInput customerNameTextField) {
this.customerNameTextField = customerNameTextField;
}

public UIInput getBranchNameTextField() {
return branchNameTextField;
}

public void setBranchNameTextField(UIInput branchNameTextField) {
this.branchNameTextField = branchNameTextField;
}

public UIInput getOpenDateTextField() {
return openDateTextField;
}

public void setOpenDateTextField(UIInput openDateTextField) {
this.openDateTextField = openDateTextField;
}

public UIInput getClosingBalanceTextField() {
return closingBalanceTextField;
}

public void setClosingBalanceTextField(UIInput closingBalanceTextField) {
this.closingBalanceTextField = closingBalanceTextField;
}

public UIInput getAddressTextArea() {
return addressTextArea;
}

public void setAddressTextArea(UIInput addressTextArea) {
this.addressTextArea = addressTextArea;
}

public UIInput getEmailIdTextField() {
return emailIdTextField;
}

public void setEmailIdTextField(UIInput emailIdTextField) {
this.emailIdTextField = emailIdTextField;
}

public UIInput getPhoneNumberTextField() {
return phoneNumberTextField;
}

public void setPhoneNumberTextField(UIInput phoneNumberTextField) {
this.phoneNumberTextField = phoneNumberTextField;
}
}
[/code]

Take a careful look at the implementation of the Search Logic. After getting the submitted value of the Account Text Field by calling UIInput. getSubmittedValue(), the code tries to perform a lookup operation in the Account Storage. If an Account object is obtained, then the code explicitly sets all the submitted information of the UI Components to Null. This is necessary because by setting all the Submitted Value of the Input Components to null, we are ensuring that the Component’s Value will be taken from the appropriate Model Objects.

6) Conclusion

Many of the Vendors have started using Ajax4Jsf Framework in their Web Applications due to its simplicity. No need to depend on JavaScript code to make use of Ajax Functionality. This article initially focused on explaining the need to have another Framework for the Web Tier. Then it provided a Brief Information about the Workflow that happens in an Ajax4Jsf enabled Web Application. Then the most commonly used Ajax4Jsf Tags are explained in detail. Finally the article concluded by giving a Sample AutoComplete Application for populating the User Account Information when given the Account Number.

Filed Under: JSF Tagged With: Ajax4jsf, JBoss, JSF, Richfaces

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved