Java Server Faces (JSF) Tools

Exclusive offer: get 50% off this eBook here
JBoss Tools 3 Developers Guide

JBoss Tools 3 Developers Guide — Save 50%

Develop JSF, Struts, Seam, Hibernate, jBPM, ESB, web services, and portal applications faster than ever using JBoss Tools for Eclipse and the JBoss Application Server

$23.99    $12.00
by Anghel Leonard | May 2009 | Java Open Source Web Development

Java Server Faces (JSF) Tools is a set of tools designed for improving the development process of JSF projects. In this article by Anghel Leonard, we will see that these tools offer amazing skills for creating different kinds of JSF projects and JSF components, such as converters, validators, managed beans, referenced beans, and so on.

Throughout this article, we will follow the "learning by example" technique, and we will develop a completely functional JSF application that will represent a JSF registration form as you can see in the following screenshot. These kinds of forms can be seen on many sites, so it will be very useful to know how to develop them with JSF Tools.

JBoss Tools 3 Developers Guide

The example consists of a simple JSP page, named register.jsp, containing a JSF form with four fields (these fields will be mapped into a managed bean), as follows:

  • personName – this is a text field for the user's name
  • personAge – this is a text field for the user's age
  • personPhone – this is a text field for the user's phone number
  • personBirthDate – this is a text field for the user's birth date

The information provided by the user will be properly converted and validated using JSF capabilities. Afterwards, the information will be displayed on a second JSP page, named success.jsp.

Overview of JSF

Java Server Faces (JSF) is a popular framework used to develop User Interfaces (UI) for server-based applications (it is also known as JSR 127 and is a part of J2EE 1.5). It contains a set of UI components totally managed through JSF support, like handling events, validation, navigation rules, internationalization, accessibility, customizability, and so on. In addition, it contains a tag library for expressing UI components within a JSP page. Among JSF features, we mention the ones that JSF provides:

  • A set of base UI components
  • Extension of the base UI components to create additional UI component libraries
  • Custom UI components
  • Reusable UI components
  • Read/write application date to and from UI components
  • Managing UI state across server requests
  • Wiring client-generated events to server-side application code
  • Multiple rendering capabilities that enable JSF UI components to render themselves differently depending on the client type
  • JSF is tool friendly
  • JSF is implementation agnostic
  • Abstract away from HTTP, HTML, and JSP

Speaking of JSF life cycle, you should know that every JSF request that renders a JSP involves a JSF component tree, also called a view. Each request is made up of phases. By standard, we have the following phases (shown in the following figure):

  • The restore view is built
  • Request values are applied
  • Validations are processed
  • Model values are updated
  • The applications is invoked
  • A response is rendered
  • During the above phases, the events are notified to event listeners

JBoss Tools 3 Developers Guide

We end this overview with a few bullets regarding JSF UI components:

  • A UI component can be anything from a simple to a complex user interface (for example, from a simple text field to an entire page)
  • A UI component can be associated to model data objects through value binding
  • A UI component can use helper objects, like converters and validators
  • A UI component can be rendered in different ways, based on invocation
  • A UI component can be invoked directly or from JSP pages using JSF tag libraries

Creating a JSF project stub

In this section you will see how to create a JSF project stub with JSF Tools. This is a straightforward task that is based on the following steps:

  1. From the File menu, select New | Project option. In the New Project window, expand the JBoss Tools Web node and select the JSF Project option (as shown in the following screenshot). After that, click the Next button.

    JBoss Tools 3 Developers Guide

  2. In the next window, it is mandatory to specify a name for the new project (Project Name field), a location (Location field—only if you don't use the default path), a JSF implementation (JSF Environment field), and a template (Template field). As you can see, JSF Tools offers a set of predefined templates as follows:
    • JSFBlankWithLibs—this is a blank JSF project with complete JSF support.
    • JSFKickStartWithLibs—this is a demo JSF project with complete JSF support.
    • JSFKickStartWithoutLibs—this is a demo JSF project without JSF support. In this case, the JSF libraries are missing for avoiding the potential conflicts with the servers that already offer JSF support.
    • JSFBlankWithoutLibs—this is a blank JSF project without JSF support. In this case, the JSF libraries are missing for avoiding the potential conflicts with the servers that already offer JSF support (for example, JBoss AS includes JSF support).

    The next screenshot is an example of how to configure our JSF project at this step. At the end, just click the Next button:

    JBoss Tools 3 Developers Guide

    This step allows you to set the servlet version (Servlet Version field), the runtime (Runtime field) used for building and compiling the application, and the server where the application will be deployed (Target Server field). Note that this server is in direct relationship with the selected runtime. The following screenshot shows an example of how to complete this step (click on the Finish button):

    JBoss Tools 3 Developers Guide

After a few seconds, the new JSF project stub is created and ready to take shape! You can see the new project in the Package Explorer view.

JBoss Tools 3 Developers Guide Develop JSF, Struts, Seam, Hibernate, jBPM, ESB, web services, and portal applications faster than ever using JBoss Tools for Eclipse and the JBoss Application Server
Published: April 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

JSF Project Verification

Before starting to develop a JSF application, you can take advantage of an important facility of JSF Tools that is, ability to verify and report any dysfunction that may affect the application flow. This facility, known as the JSF Project Verification, will verify the application when it is saved and help you to easily identify errors. For this, you can follow these steps:

  1. From the Window main menu, select the Preferences option.
  2. In the Preferences window, expand the JBoss Tools | Web | Verification node from the left panel.
  3. Select the desired checkboxes and click on Apply and OK (it is recommended to select all of them).

JSF application configuration file

A very useful facility of JSF Tools consists of an editor especially designed for managing everything that is related to the JSF main configuration file (faces-config.xml). You can start this editor like this:

  1. Place the cursor in the Package Explorer view on your project node.
  2. Expand your JSF project node: registerJSF | WebContent| WEB-INF.

    JBoss Tools 3 Developers Guide

  3. Double-click on the faces-config.xml file.

When the editor is available, it will appear as in the screenshot shown below:

The Diagram view

From this view, you can easily manage pages and transitions between the application's pages (navigation rules). You can create, modify, or delete a page/transition in just a few seconds, and you will always have a clear image of the application flow, thanks to the graphical representation mode.

Creating pages

As an example, let's create two pages named register.jsp and success.jsp. Usually, you would have had to edit these files by hand to describe the pages flow, but using Diagram view features, we can do it visually. For this, you have to apply the following steps:

  1. Right-click inside the Diagram view and select the New View... option from the contextual menu:

    JBoss Tools 3 Developers Guide

    Another way to create a new page is selecting the View Template icon (fourth from the top) from the toolbar placed in the top-left corner of the Diagram view and, following that, clicking inside the Diagram view surface.

  2. The above step will open the New View window (as shown in the following screenshot). In the From-View-ID field, enter the relative path and name of the new page. For example, you can type pages/register (without the .jsp extension). Leave everything else unchanged and click on the Finish button.

    JBoss Tools 3 Developers Guide

  3. Repeat step 2, but this time type pages/success in the From-View-ID field. Note that both pages are represented on the Diagram view surface as you can see in the following screenshot. Also, they are present under the registerJSF/WebContent/pages directory in the Package Explorer view.

    JBoss Tools 3 Developers Guide

Adding navigation rules

Now, it is time to connect the two pages by creating a transition (navigation rule) from register.jsp to success.jsp. To do this, follow these steps:

  1. Select the Create New Connection icon (third from the top) from the toolbar placed in the top-left corner of the Diagram view. This will change the cursor into an arrow cursor with a two-pronged plug at the arrow's bottom.
  2. Click on register.jsp and after that click on success.jsp. You should see something resembling that shown in the following screenshot:

    JBoss Tools 3 Developers Guide

  3. Save the changes by selecting Save option from the main File menu.

The Tree view

Maybe the most important view of this editor is the Tree view, which is made of a set of nodes that put the configuration file in a graphical and easy-to-use manner. Just with a few clicks, we can create and modify the properties of the JSF components by skipping the annoying process of manually editing the configuration file. In this section you will see how to exploit this view for managing the most important components of a JSF application, such as managed beans, converters, and validators. The Tree view can be seen as shown in the following screenshot:

JBoss Tools 3 Developers Guide

Working with Managed Beans

A very powerful facility of the Tree view is the support for managed beans. Now, we can create, modify, and delete managed beans without touching the source code. Next, you will see how to create beans properties, how to create getter and setter methods, and how to obtain the generated source code in just a few steps.

As you have seen in the introduction of this article, we want to develop a registration form (register.jsp) with four fields representing name (java.lang.String), age (int), birth date (java.util.Date), and phone number (register.PhoneNumber) of the user. Each of these fields can be encapsulated as a property of a managed bean that can be developed by following these steps:

  1. Select the Managed Beans node from the left panel inside the Tree view.
  2. From the right panel (which is displaying the current managed beans status), click on the Add button. This will open the New Managed Bean window (as shown in the following screenshot):

    JBoss Tools 3 Developers Guide

  3. In this window you have to specify the scope where the managed bean is active (in our case, the request scope), the class that represents the managed bean (for example, type register.PersonBean), and a bean's alias name used as a shortcut name (for example, type personBean). Because we want to allow JSF Tools to generate the managed bean source code, we mark as selected the Generate Source Code checkbox. Note that if you click on the Class link, you can configure internal aspects of the bean class (in our example, we will use the default settings).
  4. Clicking the Finish button of the New Managed Bean window will generate the managed bean, and it will display as shown in the following screenshot:

    JBoss Tools 3 Developers Guide

Now that we have created the managed bean stub, it is time to create the bean's properties. For doing this, you can follow these steps:

  1. Click on the Add button in Properties panel. This will open the Add Property window (as shown in the following screenshot):

    JBoss Tools 3 Developers Guide

  2. In this window, you have to specify the new property name (for example, for mapping the username—Your Name field of our registration form—type in the Property-Name field, personName), the property type (in our example, the username is a string), the value kind, and default value (fill up the Value field only if you want to use a different default value). Note that we have marked as selected the three checkboxes for adding the new property to our bean and to generate the corresponding getter/setter methods. At the end, click on the Finish button for generating the new property. The following screenshot will appear:

    JBoss Tools 3 Developers Guide

    For primitive types (including strings), the value kind is recommended to be set as value. For objects, it is recommended to set it as null-value. List-entries and map-entries values are also supported.

  3. Now, if you repeat the above two steps you can map the user age (Your Age field), user birth date (Your Birth Date field), and user phone number (Your Phone Number field) in the same way. The following three screenshots represent the settings that should be made in the Add Property window for mapping these fields to bean properties:

    JBoss Tools 3 Developers Guide

    JBoss Tools 3 Developers Guide

    JBoss Tools 3 Developers Guide

An interesting aspect is represented by the Your Phone Number field, because this field is mapped to another managed bean named register.PhoneNumber. This managed bean has three properties used for extracting from the inserted phone number, the country code (countryCode property), area code (areaCode property), prefix number (prefixNumber property), and a property for keeping the entire phone number (allNumber property). These four properties are all strings (java.lang.String). Now, use what you have learnt so far to create this managed bean with JSF Tools (for alias name, use the phoneNumber text).

In the end, you should have the two managed beans as shown in the following three screenshots:

JBoss Tools 3 Developers Guide

JBoss Tools 3 Developers Guide

JBoss Tools 3 Developers Guide

Finally, save the project state by selecting the Save option from the File main menu.

If you want to see the generated code source for our beans, you can double-click the Managed-Bean-Class link that appears in the right panel of the Tree view when you select a bean from the left panel of the same view (as shown in the following screenshot).

JBoss Tools 3 Developers Guide

You can also open a bean from the Package Explorer view by expanding the project node and double-clicking on the bean's name.

In addition, JSF Tools allows us to add existing Java Beans to the configuration file. This is a very useful facility because it allows us to import existing Java Beans so that we don't have to recreate them from the start. For this, we select the Managed Beans node (in Tree view) and click the Add button in the right panel. In the New Managed Bean wizard, we browse to the existing Java Bean, click the Next button (adding an exiting bean will deactivate the Generate Source Code checkbox and activate the Next button), select the properties to be imported (from the Managed Properties wizard), and click on the Finish button.

JBoss Tools 3 Developers Guide Develop JSF, Struts, Seam, Hibernate, jBPM, ESB, web services, and portal applications faster than ever using JBoss Tools for Eclipse and the JBoss Application Server
Published: April 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Working with custom converters

Creating and registering a custom converter is a very elegant method for accomplishing conversion issues that can't be resolved by JSF default converters. For example, in our registration form, we need the following conversions:

  • The username (personName bean property) doesn't need a conversion as the name is a String.
  • The user age (personAge bean property) needs to be converted from a String to an Integer. We will use a default JSF converter.
  • The user birth date (personBirthDate bean property) needs to be converted from a String to a java.util.Date instance. This conversion can be accomplished by the JSF f:convertDateTime default converter.
  • The user phone number (personPhone bean property) needs to be converted from a String to a register.PhoneNumber instance. This task can be accomplished only by a custom converter because no default converter can help us obtain this conversion.

Now, creating a custom converter can be done like this:

  1. Click on the Converters node inside the left panel of Tree view.
  2. From the right panel of Tree view, click on the Add button for opening the Add Converter window (as shown in the following screenshot).

    JBoss Tools 3 Developers Guide

  3. Fill in the Converter-ID field with the converter name and the Converter-Class field with the converter class name. If you want to customize the converter class, click on the Converter-Class link (in our example, we will use the default settings).
  4. In the Add Converter window, click on the Finish button for generating the new converter.

Edit the converter-generated source code by clicking on the Converter-Class link that appears

JBoss Tools 3 Developers Guide

in the right panel of the Tree view (as shown in the following screenshot):

Note that you have to manually insert the behavior of the getAsObject and getAsString methods. For example, we convert the inserted phone number into a register.PhoneNumber object by adding the following code to these methods:

import java.util.StringTokenizer;
...
public Object getAsObject(FacesContext arg0, UIComponent arg1,
String arg2) {
// TODO Auto-generated method stub
System.out.println("//getAsObject method//");
StringTokenizer st = new StringTokenizer(arg2,"-");
PhoneNumber pn = new PhoneNumber();
try{
pn.setAllNumber(arg2);
pn.setCountryCode(st.nextToken());
pn.setAreaCode(st.nextToken());
pn.setPrefixNumber(st.nextToken());
}catch (Exception e){ return pn; }
return pn;
}
public String getAsString(FacesContext arg0, UIComponent arg1,
Object arg2) {
// TODO Auto-generated method stub
System.out.println("//getAsString method//");
if(arg2 != null)
{
String value = ((PhoneNumber)arg2).getAllNumber();
return value;
}
return "";
}

Finally, save the project state by selecting the Save option from the File main menu.

Working with custom validators

When JSF default validators don't satisfy your application's needs, it is time to implement a custom validator. For example, for our registration form, we have the following situation:

  • The username (personName bean property)—doesn't need validation.
  • The user age (personAge bean property)—needs to be a valid age. This can be accomplished with the JSF f:validateLongRange default validator.
  • The user birth date (personBirthDate bean property)—doesn't need validation.
  • The user phone number (personPhone bean property)—needs to be validated as a string that respects the next pattern: x[x]-xxx-xxx-xxxx. This task can be accomplished only by a custom validator because no default validator can help us.

Now, creating a custom validator can be done like this:

  1. Click on the Validators node inside the left panel of Tree view.
  2. From the right panel of Tree view, click on the Add button for opening the Add Validator window.

    JBoss Tools 3 Developers Guide

  3. Fill in the Validator-ID field with the validator name and the Validator-Class with the validator class name. If you want to customize the validator class, click on the Validator-Class link. (In our example, we will use the default settings.)
  4. In the Add Validator window, click on the Finish button for generating the new validator.

Edit the validator-generated source code by clicking on the Validator-Class link that appears in the right panel of the Tree view as shown in the following screenshot:

JBoss Tools 3 Developers Guide

Notice that you have to manually insert the behavior of the validate method. For example, we validate the inserted phone number by adding the following code to this method:

import javax.faces.application.FacesMessage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
public void validate(FacesContext arg0, UIComponent arg1, Object arg2)
throws ValidatorException {
// TODO Auto-generated method stub
System.out.println("//validate method//");
String value = ((PhoneNumber)arg2).getAllNumber();
String countryCode = "^[0-9]{1,2}";
String areaCode = "( |-|(){1}[0-9]{3}( |-|)){1}";
String prefixNumber = "( |-)?[0-9]{3}";
String number = "( |-)[0-9]{4}$";
Pattern mask = Pattern.compile(countryCode + areaCode +
prefixNumber + number);
Matcher matcher = mask.matcher(value);
if (!matcher.find()){
FacesMessage message = new FacesMessage();
message.setDetail("Your phone number is not valid!");
message.setSummary("Your phone number is not valid!");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}

Finally, save the project state by selecting the Save option from the File main menu.

In addition to this, JSF Tools allows us to create custom referenced beans (note that referenced beans are used very rarely and they basically are Java Beans available in a JSF scope—the application must create an instance of the referenced bean and place it in the desired scope). For this, select the Referenced Beans node (Tree view) and click the Add button from the right panel. In the Add Referenced Bean wizard, fill up the Referenced-Bean-Name with a name for your referenced bean and the Referenced-Bean-Class with the full name of the referenced bean class. Optionally, click on the Referenced-Bean-Class link if you want to customize the referenced bean stub class. Click Finish.

The Source view

In the Source view, you can see the source of the faces-config.xml document. This source is synchronized with the other two views, so you will always see the reflection of your modifications. This view allows you to modify the configuration file manually or by using the Outline view that displays a tree view of it.

JBoss Tools 3 Developers Guide

Summary

In this article, you have seen how to use JSF Tools for modeling the most important components of a traditional JSF project. You have developed a complete functional JSF project by using the most important skills of JSF Tools like managed beans, converters, validators.

 

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

About the Author :


Anghel Leonard

Anghel Leonard is a senior Java developer with more than 13 years of experience in Java SE, Java EE, and related frameworks. He has written and published more than 50 articles about Java technologies and more than 500 tips and tricks for many programming dedicated websites. In addition, he wrote two books about XML and Java (one for beginners and one for advanced developers) for Albastra, a Romanian publisher, three books for Packt: Jboss Tools 3 Developer Guide, JSF 2.0 Cookbook, and JSF 2.0 Cookbook LITE, and two books for APress: Pro Java 7 NIO 2 and Pro Hibernate and MongoDB. Currently, he's developing web applications using the latest Java technologies on the market (EJB 3.0, CDI, Spring, JSF, Struts, Hibernate, and so on). For the past two years, he has focused on developing rich Internet applications for geographic information systems.

Books From Packt

JBoss Portal Server Development
JBoss Portal Server Development

JBoss Drools Business Rules
JBoss Drools Business Rules

Learning jQuery 1.3
Learning jQuery 1.3

Spring Web Flow 2 Web Development
Spring Web Flow 2 Web Development

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

Django 1.0 Website Development
Django 1.0 Website Development

Drupal 6 Site Builder Solutions
Drupal 6 Site Builder Solutions

Practical Plone 3: A Beginner's Guide to Building Powerful Websites
Practical Plone 3: A Beginner's Guide to Building Powerful Websites

 

Your rating: None Average: 5 (1 vote)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
F
L
D
H
B
a
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