Saturday, April 18, 2009

Facelets Tutorial : UI Component Tag

<< Previous        Next >>


UI Component Tag



Facelets supports two tags that function as components, ui:component  and ui:fragment. The ui:component tag is just like the ui:composition tag, except the fact that, it  insert a new JSF UI Component object into the component tree, which becomes the root for all of the tag’s child elements. The ui:fragment tag is the nontrimming counterpart of ui:component, just as the ui:composition tag has ui:decorate.  The ui:component and ui:fragment tags support two of the Faces common attributes, id and binding, but both are not required attributes. This binding attribute links the component tag to a property of a JavaBean. If that target property did not have a UIComponent instance assigned already, JavaServer Faces will lazily create an instance for you and set it on your JavaBean before continuing with building the tree. These two tags makes component development simpler and faster in JSF. Let us see how to use these tags to create components with some examples.

In the following example, we are going to replace the 'side menu' in the previous example with the ui:component tag. In the previous example the 'side menu' got displayed form the template file insertTemplate.xhtml. Here we will create the menu in a separate xhtml file (sideMenu.xhtml), using the ui:component tag. Finally, we will include this page in the template client (home.xhtml) , inside the ui:define tag. First we need to create a Java class MenuItem which holds the url and label of the items in the side menu.

Create a new Java Class

Now, we will create a Java Class MenuItem.java file. It's a simple Java bean with two attributes url and label and setter/getter methods for these attributes. Right-mouse click on the JavaResources:src folder of JSFFaceletsExample project, select New-> Class to launch the Java Class wizard. In the wizard enter the package name as, com.jsflessons.facelets.example and the Name of the class as MenuItem. Click the Finish button.

package com.jsflessons.facelets.example;
public class MenuItem {
    private String url;
    private String label;
    public String getUrl() {
       return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getLabel() {
        return label;
    }
    public void setLabel(String label) {
        this.label = label;
    }
    public MenuItem() {
        super();
    }
    public MenuItem(String url, String label) {
        super();
        this.url = url;
        this.label = label;
    }
}

Now we will create a backing bean which holds the list of  MenuItems. (click Next to continue)