FeaturesPluginsDocs & SupportCommunityPartners

Working With Form Tags in the JSF Framework

This document is the third installment in the jAstrologer series of JSF tutorials. In the first installment of the series, we created a simple web application called jAstrologer. In the second installment of the series we showed how to validate and convert user input. In this installment we show how to use some basic JSF tags to customize the input form.

So far the jAstrologer web application does the following:

  • Presents greeting.jsp, which uses two inputText components to ask for the user's name and birthday.
  • Saves the values entered by the user in the properties of the UserBean backing bean.
  • Validates the input with standard and custom validators, and in the case of birthday uses a custom converter to convert the date.
  • Displays error messages as defined in a custom properties file.
  • Reads the values of the properties from UserBean and displays them in success.jsp.

Our application currently uses a very simple form with text fields to gather user input. But we are not limited to using text fields. There are many JSF tags we can use to further customize the page, but in this tutorial we cannot show how to use and configure all the available JSF tags. Instead, we will show how to use some tags commonly used in web-based forms such as links, textAreas, radioButtons, menus and listBoxes. In this tutorial we will show you how to do the following:

  • Modify the existing inputText textboxes for the name, email and birthday field using HTML attributes.
  • Add inputTextArea to create a text areas with a predefined size.
  • Add selectOneRadio to create a radiobutton list.
  • Add selectOneMenu to create a dropdown list.
  • Modify the success page by adding a navigation link to take you back to the input page.

You can find more information about how to use these and other JSF tags in the Java EE Tutorial.

Prerequisites

This document assumes you have some basic knowledge of, or programming experience with, the following technologies:

Software Needed for the Tutorial

For this tutorial you need to have the following software installed on your computer:

For this tutorial you need to register a local instance of Sun Java System Application Server with the IDE.

Tutorial Exercises

Formatting the Text Field

We will start slowly by showing how we can modify and improve the tags we already have. We can modify the tags by setting some boundaries on the input values. We can use standard HTML form attributes to control how the form elements are displayed.

  1. Open greeting.jsp and make the following changes (in bold) to our form:
    <p>Enter your name: <h:inputText value="#{UserBean.name}" id="name" size="30" required="true"/>
    <h:message for="name" style="color:#f00;" /></p>
    <p>Enter your email: <h:inputText value="#{UserBean.email}" id="email" size="50" required="true">
            <f:validator validatorId="astrologer.EmailValidator" />
        </h:inputText>
    <h:message for="email" style="color:#f00;" /></p>
    <p>Enter your birthday: <h:inputText value="#{UserBean.birthday}" id="birthday" maxlength="10" required="true">
            <f:converter converterId="astrologer.MyDateConverter" />
        </h:inputText> <h:message for="birthday" style="color:#f00;" />
    (dd/mm/yyyy)</p>
    <h:commandButton value="Submit" action="#{UserBean.submit}" />
  2. We will also add some css properties to the page by adding the following to greeting.jsp:
     <style>
        p, input, option, select {font-family:verdana; font-size:10px;}
        </style>
    </head>
  3. Run the project and you see the following page:

What we have done is specify the size of the name and email text fields and specify a maximum length for the birthday field. You can see that the text fields are now different lengths, since we defined 30 characters for name and 50 for email. The birthday text field is now restricted to 10 characters to prevent the user from entering longer strings. In the same way you can change a text field's background or foreground color, the font styles and other properties. The JSF tag inputText accepts all commonly used HTML and DHTML parameters.

Adding a Text Area Using the inputTextArea Tag

We will now add a text area to our form. We will use the inputTextArea tag and add some attributes to modify how the field is displayed. We then modify UserBean to add the field notesto store the input data and modify success.jsp to display the data.

  1. Open greeting.jsp and add the following line (in bold) below the birthday input field:
    <p>Enter your birthday: <h:inputText value="#{UserBean.birthday}" id="birthday" required="true">
        <f:converter converterId="astrologer.MyDateConverter" />
        </h:inputText> <h:message for="birthday" style="color:#f00;" />
    (dd/mm/yyyy)
    <h:message for="birthday" /></p>
    <p>Notes:<h:inputTextarea rows="3" cols="50" value="#{UserBean.notes}"/></p>
    <h:commandButton value="Submit" action="#{UserBean.submit}" />

    This tag creates text area for notes with 3 rows of 50 columns each. The value is stored in the notes property in UserBean. The data from the input is transferred into one String with the ends of the line marked with \n.

  2. Open UserBean.java, add the following field to store notes and generate the getter and setter.
    private String notes;
  3. Open success.jsp and add the following:
        <p>Notes:<br>
             <h:outputText value="#{UserBean.notes}" /></p>
      
  4. Run the project. The input form now has the text area and the success page now displays any text entered in the text area.

Adding a Radio Button Using the selectOneRadio Tag

When you want the user to select input from a set of predefined values you can use select tags in your form. The most common types of select lists are checkbox lists (selectOneRadio), dropdown lists (selectOneMenu / selectManyMenu) and list boxes (selectOneListbox / selectManyListbox). Each value is encapsulated by selectItem class instances.

In this example we will create a list of radio buttons and store the value of the user input in the property degree. After we add the radio buttons to greeting.jsp we will add degree to UserBean.java and modify the output in success.jsp to display the selected value.

  1. Open greeting.jsp and add the following lines above the text area we added in the previous step:
    <p><h:selectOneRadio value="#{UserBean.degree}" border="1" layout="pageDirection" required="true" >
            <f:selectItem itemValue="Unspecified" itemLabel="Unspecified" />
            <f:selectItem itemValue="Basic" itemLabel="Basic"/>
            <f:selectItem itemValue="High school" itemLabel="High school"/>
            <f:selectItem itemValue="College" itemLabel="College"/>
       </h:selectOneRadio></p>
    <p>Notes:<br>
             <h:outputText value="#{UserBean.notes}" /></p>
    The border attribute defines the thickness of line around the checkbox list. You can experiment with different values. The layout attribute defines if the list is oriented horizontally or vertically, as in this example.
  2. Open UserBean and add the following field to store the value of degree and then generate the getter and setter for the field.
    private String degree = "Unspecified";
  3. Open success.jsp and add the following line to display the value stored in degree.
    <p>You have <h:outputText value="#{UserBean.degree}" /> education.</p>
  4. Run the project. The input form now has the radio buttons. After you complete the form and click Submit, the new value is displayed in success.jsp.

Adding a Dropdown List Using the selectOneMenu Tag

You can create a dropdown list in much the same way as creating radio buttons. To create a dropdown list, you can substitute the JSF tags selectOneMenu and selectItems for the selectOneRadio and selectItem tags that were used to create the radio button list.

In this exercise we will show you how to create a dropdown list, but instead of defining the values for the list items in the JSP page we will define the values in an array in our backing bean. We will create an array called signs in the backing bean and a string sign to store the selected value.

  1. Open greeting.jsp and add the following lines below the radio buttons we added in the previous step:
    </h:selectOneRadio></p>
    <p>Select your sign:<br>
    <h:selectOneMenu value="#{UserBean.sign}" required="true" >
        <f:selectItems value="#{UserBean.signs}"/>
    </h:selectOneMenu>
    </p>
    From the code you can see that we do not specify each of the values of the select tag, but instead we bind the values to an array in the backing bean UserBean.
  2. Open UserBean.java backing bean and add the following code for the field sign and the array signs and generate the getters and setters.
    private String sign;
    
    private SelectItem[] signs = {
        new SelectItem("Aries"),
        new SelectItem("Taurus"),
        new SelectItem("Gemini"),
        new SelectItem("Cancer"),
        new SelectItem("Leo"),
        new SelectItem("Virgo"),
        new SelectItem("Libra"),
        new SelectItem("Scorpio"),
        new SelectItem("Sagittarius"),
        new SelectItem("Capricorn"),
        new SelectItem("Aquarius"),
        new SelectItem("Pisces"),
    };
  3. Press Alt-Shift-F to generate any necessary import statements.

    Here we added the property sign and declared an array signs consisting of multiple SelectItem instances. We use very simple constructors with only one value parameter. We use toString() to pass the value of the selected parameter. Now that we have the labels for the choices in a select tag, the next step is to update success.jsp.

  4. Open success.jsp and add the following code (in bold).
    <p>Your zodiac sign is <h:outputText value="#{UserBean.sign}" /></p>
    <p>You have <h:outputText value="#{UserBean.degree}" /> education.</p>
        
  5. Run the application.

Compute Sign from Birthdate

So there is still one problem - what if the user doesn't know their star sign? We can determine the sign based on the birthdate they entered. To do this, we will modify the list of sign options to add an "I don't know" option to the list and add the tellSign method. If the user chooses "I don't know", the tellSign method will determine the sign according to the birthdate. The tellSign method includes a message field that will display a message if the date cannot be parsed, so we also need to add the field to UserBean and add a tag to greeting.jsp to display the message.

  1. Open UserBean and modify the sign field to set the field to null:
    private String sign = "";
  2. Add the following "I don't know" SelectItem to the signs array:
    new SelectItem("Pisces"),
    new SelectItem("I don't know"),
        
  3. Modify the getSign method in UserBean by adding the following (in bold):
    public String getSign() {
         if(sign.equals("I don't know"))
               tellSign();
         return sign;
    }
  4. Add the following tellSign method to UserBean:
    public void tellSign(){
           //Get the tag's value directly in page, unconverted to Date
            int month = getBirthday().getMonth() + 1;
            int day = getBirthday().getDate();
            if((day < 1)||(day > 31)||(month < 1)||(month > 12))
                setMessage("Error during date parsing - day or month out of range!");
            switch(month){
                case 1:
                    if(day < 21) {
                        setSign("Capricorn");
                    }
                    else
                        setSign("Aquarius");
                    return;
                case 2:
                    if(day < 21) {
                        setSign("Aquarius");
                    }
                    else
                        setSign("Pisces");
                    return;
                case 3:
                    if(day < 21) {
                        setSign("Pisces");
                    }
                    else
                        setSign("Aries");
                    return;
                case 4:
                    if(day < 21) {
                        setSign("Aries");
                    }
                    else
                        setSign("Taurus");
                    return;
                case 5:
                    if(day < 22) {
                        setSign("Taurus");
                    }
                    else
                        setSign("Gemini");
                    return;
                case 6:
                    if(day < 22) {
                        setSign("Gemini");
                    }
                    else
                        setSign("Cancer");
                    return;
                case 7:
                    if(day < 23) {
                        setSign("Cancer");
                    }
                    else
                        setSign("Leo");
                    return;
                case 8:
                    if(day < 23) {
                        setSign("Leo");
                    }
                    else
                        setSign("Virgo");
                    return;
                case 9:
                    if(day < 23) {
                        setSign("Virgo");
                    }
                    else
                        setSign("Libra");
                    return;
                case 10:
                    if(day < 24) {
                        setSign("Libra");
                    }
                    else
                        setSign("Scorpio");
                    return;
                case 11:
                    if(day < 23) {
                        setSign("Scorpio");
                    }
                    else
                        setSign("Sagittarius");
                    return;
                case 12:
                    if(day < 22) {
                        setSign("Sagittarius");
                    }
                    else
                        setSign("Capricorn");
                    return;
            }
        }
  5. Add the following message field and create getters and setters for the field:
    private String message = "";
  6. Open greeting.jsp and add the following tag (in bold) to display our error message:
    <h:selectOneMenu value="#{UserBean.sign}" required="true" >
        <f:selectItems value="#{UserBean.signs}"/>
    </h:selectOneMenu>
    <h:outputLabel value="#{UserBean.message}" style="color:#f00;" />
    </p>

Modifying Page Navigation

Now that we have successfully modified our form, we need to make one more small change to modify the navigation in our form. We want to add a link in the success page to take us back to the form input page. We need to add some navigation control to success.jsp which will take us back to greeting.jsp To do this we will use the outputLink tag. We do not want to use a button in this case because success.jsp is an output page and we should use a link to navigate between pages.

We could define the link directly in success.jsp, but in this case we will store the text of the link and the navigation URL in the backing bean.

  1. Open success.jsp in the Source Editor and add the following code (in bold):
    <h:outputText value="#{UserBean.notes}" /></p>
        <p><h:outputLink value="#{UserBean.navigate}" >
            <h:outputText value="#{UserBean.linkText}"/>
        </h:outputLink></p>
    </h:form>
  2. Open UserBean.java and add the following fields and generate getters and setter for the fields:
    private String navigate = "/jAstrologer/faces/greeting.jsp";
    private String linkText = "Back to previous page";
    Note: If you started the tutorial by downloading the project, you may need to change the value of the navigate field. The value should be /<PROJECT_NAME/faces/greeting.jsp.
  3. Run the application.

And that should do it! If you click on the "Back to previous page" link in success.jsp, you will be redirected back to greetings.jsp and the form values are reset.


jAstrologer greetings page with input form jAstrologer success page displaying input data


See the Java EE 5 Tutorial for a full description of developing web applications.



Next Steps

For more information about using NetBeans IDE to develop web applications, see the following resources:

Bookmark this page

del.icio.us furl simpy slashdot technorati digg
Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Virtual Box - full virtualizer  Open ESB - The Open Enterprise Service Bus Powered by