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, you created a simple
web application called jAstrologer. In the second
installment of the series, you learned how to validate and convert user input. You can
download the project
here if you have not run through the first two installments. This installment demonstrates
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. You
are not limited to using text fields however. There are many JSF tags you can use to further
customize the page. This tutorial focuses on applying some tags that are commonly used in
web-based forms such as links, textAreas, radioButtons, menus,
and listBoxes. For a complete list of JSF tags, see the official
tag library
documentation.
In this tutorial you are going 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 area with a predefined size.
- Add selectOneRadio
to create a radio button list.
- Add selectOneMenu
to create a dropdown list.
- Modify the success.jsp page by adding a navigation link to take you back to the
input page.
Contents

To follow this tutorial, you need the following software and resources.
| NetBeans IDE |
Web and Java EE installation
version 6.1 or
version 6.0 |
| Java Development Kit (JDK) |
version 6 or
version 5 |
| GlassFish |
V2 |
Note: The GlassFish
application server V2 Update Release 2 is optionally included in the Web and Java
EE installation of NetBeans IDE.
Formatting the Text Field
Begin by making simple changes to the already existing JSP tags. Here, you can modify the
inputText
tag by setting boundaries on the input values. Use standard HTML form attributes to control
how the form elements are displayed.
- Open greeting.jsp and make the following changes (in bold)
to the form:
<h:form>
<p>Enter your name:
<h:inputText value="#{UserBean.name}" id="name" size="24" required="true"/>
<h:message for="name" style="color:red" /></p>
<p>Enter your email:
<h:inputText value="email" id="email" size="24" required="true">
<f:validator validatorId="astrologer.EmailValidator" />
</h:inputText>
<h:message for="email" style="color:red" /></p>
<p>Enter your birthday:
<h:inputText value="#{UserBean.birthday}" id="birthday" maxlength="10" required="true">
<f:converter converterId="astrologer.MyDateConverter" />
</h:inputText> (dd/mm/yyyy)
<h:message for="birthday" style="color:red" /></p>
<h:commandButton value="Submit" action="submit" />
</h:form>
- Run the project. You see the following page:

You have set the size of the name and email text fields to 24 characters, and provided a maximum
length for the birthday field. Note that the birthday text field now restricts users from
entering more than 10 characters, which is exactly the number required for the expected format
(i.e., dd/MM/yyyy). The JSF tag inputText accepts all commonly used HTML
and DHTML attributes, so in the same manner you can also make changes to a text field's
font styles and other properties.
Adding a Text Area Using the inputTextArea Tag
You can add a text area to the form using the inputTextArea
tag, and add attributes to modify how the field is displayed. You can also add a notes
field to the UserBean class in order to store the input data, and change success.jsp
to display the data.
- 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" maxlength="10" required="true">
<f:converter converterId="astrologer.MyDateConverter" />
</h:inputText> (dd/mm/yyyy)
<h:message for="birthday" style="color:red" /></p>
<p>Notes:<br>
<h:inputTextarea rows="5" cols="39" value="#{UserBean.notes}"/></p>
<h:commandButton value="Submit" action="submit" />
This tag creates a text area of 5 rows and 39 columns, which a user can type notes. The
value is stored in the notes property in UserBean. The data from the input is
passed to the application as a String.
- In the Projects window, double-click Source Packages > astrologer.user >
UserBean.java to open the class in the Source Editor. Add a notes field
beneath the class definition (changes in bold):
public class UserBean {
private String name;
private Date birthday;
private String notes;
You can type in accessor methods yourself, or the IDE can
generate them for you. To have the IDE generate the methods, right-click on the notes
declaration you just added in the Source Editor and choose Refactor > Encapsulate Fields.
The Encapsulate Fields dialog enables you to specify options for creating getters and
setters. Click Refactor and note that accessors for notes are automatically
generated in the class:
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
- Open success.jsp and add the following (in bold):
<p>Your birthday is <h:outputText value="#{UserBean.birthday}" /></p>
<p>Notes:<br>
<h:outputText value="#{UserBean.notes}" /></p>
</h:form>
- Run the project by right-clicking the project node in the Projects window and choosing
Run. The input form displays with a text area. Type a message in the text area and note
that when you submit the form your message is redisplayed.
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. Several common types of select lists include radio button lists
(selectOneRadio),
dropdown lists (selectOneMenu
/ selectManyMenu),
and list boxes (selectOneListbox
/ selectManyListbox).
Each value is encapsulated by selectItem
class instances.
In this example you create a list of radio buttons and store the value of the option that the
user selects in the degree property. After you add the radio buttons to greeting.jsp,
you add degree to the UserBean class, then modify the output in success.jsp
to display the selected value.
- Open greeting.jsp and add the following lines just above the text area that
you added in the previous step:
<p>Enter your level of education:
<h:selectOneRadio value="#{UserBean.degree}" border="1" layout="pageDirection" >
<f:selectItem itemValue="(not specified)" 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:inputTextarea rows="5" cols="39" 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 how the
list is oriented, i.e., horizontally or vertically, as in this example.
- Open the UserBean class and add the following field to store the value.
private String degree = "(not specified)";
Create getters and setters for the degree field by using the method
demonstrated in the previous step.
Note: In order to set a default option in the
radio button list, you can initialize degree to the value
of the option you want to be set, i.e., "(not specified)". This value
is passed to the selectOneRadio tag using the value parameter.
This is what you accomplished in the previous step:
<h:selectOneRadio value="#{UserBean.degree}" border="1" layout="pageDirection" >
- Open success.jsp and add the following line (in bold) to display
the value stored in degree.
<p>You have a <h:outputText value="#{UserBean.degree}" /> education.</p>
<p>Notes:<br>
<h:outputText value="#{UserBean.notes}" /></p>
- Run the project. The form in the welcome page displays the radio button list you just
created. Enter some sample data and submit the form. Note that when you successfully
complete the form, the new value is displayed in the returned page.

Adding a Dropdown List Using the selectOneMenu Tag
You can create a dropdown list in much the same way as you create radio buttons. To create a
dropdown list, you can substitute the selectOneMenu
and selectItems JSF tags for the selectOneRadio and
selectItem
tags that were used to create the radio button list.
In this exercise you create a dropdown list, but instead of defining the values for the list
items in the JSP page, you define them in an array in the backing bean. We can create an
array called signs and a string sign to store the selected value corresponding
to the user's zodiac sign.
- Open greeting.jsp and add the following lines between the Notes text area and
the radio button list you created in the previous step:
<p>Select your zodiac sign:<br>
<h:selectOneMenu value="#{UserBean.sign}" required="true" >
<f:selectItems value="#{UserBean.signs}"/>
</h:selectOneMenu></p>
You can see that it is not necessary to hard-code each of the list option values within
the JSP page. Instead, bind the values to an array in the UserBean backing bean.
- Open UserBean in the Source Editor and add the following declaration for the
sign field:
private String sign;
Create accessor methods for sign, as described above.
- Add the following array:
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"),
};
- Add any necessary import statements. You can right-click in the Source Editor and choose
Fix Imports (Ctrl-Shift-I). The IDE adds an import statement for javax.faces.model.SelectItem
to the top of the class. You can add accessor methods for the signs array,
as described above.
Here you added the property sign and declared an array signs consisting
of multiple SelectItem
instances. Simple constructors with a single java.lang.Object parameter are
used. An inherent toString() method is applied to retrieve the value of the
selected parameter as a string.
- Open success.jsp and add the following code (in bold):
<p>Your zodiac sign is <h:outputText value="#{UserBean.sign}" /></p>
<p>You have a <h:outputText value="#{UserBean.degree}" /> education.</p>
- Run the application. You can now see a dropdown list in the welcome page.
When you select an option from the list and submit the form, your selection displays in the
returned page.
Compute Sign from Birthdate
There is still one problem - what if the user does not know his or her star sign? It is possible
to determine the sign based on the birthdate the user entered. To facilitate computation of
a user's star sign, modify the zodiac dropdown list to include an "I don't know"
option. Then code in a tellSign method. If the user chooses "I don't know,"
the tellSign method determines the sign according to the birthdate. The tellSign
method includes a message field that displays a message if the date cannot be parsed,
so you also need to add the field to UserBean, as well as a tag to greeting.jsp
in order to display the message.
- Open UserBean and modify the sign field so it is initialized as an
empty string:
private String sign = "";
- Add the following "I don't know" SelectItem to the signs
array:
new SelectItem("Pisces"),
new SelectItem("I don't know"),
- 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;
}
- Implement the following tellSign method in the UserBean class:
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;
}
}
- Add the following message field and create getters
and setters for that field:
private String message = "";
- Open greeting.jsp and add the following tag (in bold) to display
the error message:
<p>Select your zodiac sign:<br>
<h:selectOneMenu value="#{UserBean.sign}" required="true" >
<f:selectItems value="#{UserBean.signs}"/>
</h:selectOneMenu>
<h:outputLabel value="#{UserBean.message}" style="color:red" /></p>
- Run the application. You can now see the "I don't know" option listed in the
zodiac dropdown list. When you select it and submit the form, the application calculates
the zodiac sign based on the input birthday date, and displays this information in the
returned page
Modifying Page Navigation
Now that you have successfully modified the form, you can make one final change that affects
navigation within the application. Specifically, you can add a link in the success page to
allow users to return to the form input page. To do so, you must add navigation control to
success.jsp which takes the user back to greeting.jsp. This requires the
outputLink
tag. Because success.jsp is an output page, use a link and not a button to navigate
between pages.
You could define the link directly in success.jsp, but in this case you can store
the text of the link and the navigation URL in the backing bean.
- Open success.jsp in the Source Editor and add the following code (in bold):
<p>Notes:<br>
<h:outputText value="#{UserBean.notes}" /></p>
<p><h:outputLink value="#{UserBean.navigate}" >
<h:outputText value="#{UserBean.linkText}"/>
</h:outputLink></p>
- Open UserBean and add the following fields and corresponding
accessor methods:
private String navigate = "/jAstrologer/faces/greeting.jsp";
private String linkText = "Back to previous page";
- Run the application. When you click on the "Back to previous page" link in
success.jsp, you are redirected back to greeting.jsp and the form values
are reset:

See Also
Over the course of three tutorials, you built a simple interactive web application using the
JSF Framework. Introduction to the JavaServer Faces Framework
described how to set up a JSF web application named jAstrologer. In Validating
and Converting User Input, you learned how to validate input received from a form and
convert input to a different data type. This tutorial demonstrated how to apply some basic
JSF tags to customize the form, and how to perform simple navigation between pages.
See the official JavaServer
Faces documentation for tutorials, FAQs and articles. The Java
EE 5 Tutorial is a comprehensive resource for learning how to develop web applications.
You can find more information there on how to develop with JSF tags.
For information about using other web frameworks in the NetBeans IDE, and related web development
documentation, see the following resources: