http://www.developer.com/

Back to article

JBoss Tools 3 Developer Guide


June 3, 2009

JBoss Tools consist of the best Java frameworks and technologies placed together under the same "roof." Discovering JBoss Tools is like exploring a cave; at first everything seems unknown and complicated, but once you become familiar with the main features of the tools, you will start to feel at home.

Throughout this article, you will follow the "learning by example" technique, and you will develop a completely functional JSF application that will represent a JSF registration form as you can see in Figure 1. 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.



Click here for larger image

Figure 1: JSF Registration Form

The example consists of a simple JavaServer Pages (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 (UIs) 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. The JSF features mentioned here are:
  • 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
  • Tool friendly
  • Implementation agnostic
  • Abstracted away from HTTP, HTML, and JSP

Speaking of the 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 default, JSF has the following phases (shown in Figure 2):

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



Click here for larger image

Figure 2: JSF Default Phases

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 Figure 3). After that, click the Next button.



    Click here for larger image

    Figure 3: Create a JSF Project

  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).

    Figure 4 is an example of how to configure your JSF project at this step. At the end, just click the Next button:



    Click here for larger image

    Figure 4: Configure Your JSF Project

    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. Figure 5 shows an example of how to complete this step (click on the Finish button):



    Click here for larger image

    Figure 5: Set the Servlet Version, the Runtime, and the Server

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.

JSF Project Verification

Before starting to develop a JSF application, you can take advantage of an important facility of JSF Tools: the 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 is 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.
  3. Double-click on the faces-config.xml file.

When the editor is available, it will appear as in Figure 6.



Click here for larger image

Figure 6: JSF Tools Editor for Managing faces-config.xml

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 Figure 3). After that, click the Next button.



    Click here for larger image

    Figure 3: Create a JSF Project

  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).
    Figure 4 is an example of how to configure your JSF project at this step. At the end, just click the Next button:



    Click here for larger image

    Figure 4: Configure Your JSF Project

    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. Figure 5 shows an example of how to complete this step (click on the Finish button):



    Click here for larger image

    Figure 5: Set the Servlet Version, the Runtime, and the Server

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.

JSF Project Verification

Before starting to develop a JSF application, you can take advantage of an important facility of JSF Tools: the 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 is 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.
  3. Double-click on the faces-config.xml file.

When the editor is available, it will appear as in Figure 6.



Click here for larger image

Figure 6: JSF Tools Editor for Managing faces-config.xml

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, you 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 (see Figure 7):



    Click here for larger image

    Figure 7: The New View... Option from the Contextual Menu

    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 Figure 8). 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.



    Click here for larger image

    Figure 8: The New View Window

  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 Figure 9. Also, they are present under the registerJSF/WebContent/pages directory in the Package Explorer view.



    Click here for larger image

    Figure 9: The Diagram View Surface

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 Figure 10:



    Click here for larger image

    Figure 10: Result of Clicking on register.jsp and then success.jsp

  3. Save the changes by selecting the 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 Figure 11.



Click here for larger image

Figure 11: The Tree View

Working with Managed Beans

A very powerful facility of the Tree view is the support for managed beans. Now, you 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, you 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 Figure 12):



    Click here for larger image

    Figure 12: The New Managed Bean Window

  3. In this window, you have to specify the scope where the managed bean is active (in this 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 you want to allow JSF Tools to generate the managed bean source code, you 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 this example, you 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 Figure 13.



    Click here for larger image

    Figure 13: The New Managed Bean Window Will Generate the Managed Bean

Now that you 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 Figure 14):



    Click here for larger image

    Figure 14: The Add Property Window

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



    Click here for larger image

    Figure 15: Generating the New Property

    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. Figure 16, Figure 17, and Figure 18 represent the settings that should be made in the Add Property window for mapping these fields to bean properties:



    Click here for larger image

    Figure 16: The Add Property Window for Mapping User Age



    Click here for larger image

    Figure 17: The Add Property Window for Mapping User Birth Date



    Click here for larger image

    Figure 18: The Add Property Window for Mapping User Phone Number

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 learned so far to create this managed bean with JSF Tools (for an alias name, use the phoneNumber text).

In the end, you should have the two managed beans as shown in Figure 19, Figure 20, and Figure 21.



Click here for larger image

Figure 19: Faces Config Editor View of Two Managed Beans



Click here for larger image

Figure 20: Faces Config Editor View of personBean



Click here for larger image

Figure 21: Faces Config Editor View of phoneNumber

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 your 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 Figure 22).



Click here for larger image

Figure 22: The Generated Code Source for Your Beans

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 you to add existing Java Beans to the configuration file. This is a very useful facility because it allows you to import existing Java Beans so that you don't have to recreate them from the start. For this, you select the Managed Beans node (in Tree view) and click the Add button in the right panel. In the New Managed Bean wizard, you 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.

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 your registration form, you 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. you 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 you 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 Figure 23).



    Click here for larger image

    Figure 23: The Add Converter Window

  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 this example, you 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 in the right panel of the Tree view (as shown in Figure 24).



Click here for larger image

Figure 24: Edit the Converter-Generated Source Code

Note that you have to manually insert the behavior of the getAsObject and getAsString methods. For example, you 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 your registration form, you 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 (see Figure 25).



    Click here for larger image

    Figure 25: The Add Validator Window

  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 this example, you 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 Figure 26.



Click here for larger image

Figure 26: Edit the Validator-Generated Source Code

Notice that you have to manually insert the behavior of the validate method. For example, you 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 you 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 (see Figure 27).



Click here for larger image

Figure 27: Using the Outline View

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.

About the Book Excerpt

This article is an excerpt from the book, JBoss Tools 3 Developers Guide, by Anghel Leonard, published by Packt Publishing. The book teaches Java developers how to develop JSF, Struts, Seam, Hibernate, jBPM, ESB, web services, and portal applications rapidly using JBoss Tools for Eclipse and the JBoss Application Server.

About the Author

Anghel Leonard is a senior Java developer with more than 12 years of experience in Java SE, Java EE, and the related frameworks. He has written and published dozens of articles about Java technologies and two books about XML and Java (one for beginners and one for experts).

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date