Messages

Selection Tags

JSF has seven tags for making selections:

  • h:selectBooleanCheckbox

  • h:selectManyCheckbox

  • h:selectOneRadio

  • h:selectOneListbox

  • h:selectManyListbox

  • h:selectOneMenu

  • h:selectManyMenu

Table 4-19 shows examples of each tag.

Table 4-19. Selection Tag Examples
Tag Generated HTML Examples
h:selectBooleanCheckbox

<input type="checkbox">

h:selectManyCheckbox

<table>    ...    <label>       <input type="checkbox"/>    </label>    ... </table>

h:selectOneRadio

<table>    ...    <label>       <input type="radio"/>    </label>    ... </table>

h:selectOneListbox

<select>    <option value="Cheese">       Cheese    </option>    ... </select>

h:selectManyListbox

<select multiple>    <option value="Cheese">       Cheese    </option>    ... </select>

h:selectOneMenu

<select size="1">    <option value="Cheese">       Cheese    </option>    ... </select>

h:selectManyMenu

<select multiple size="1">    <option value="Sunday">       Sunday    </option>    ... </select>


The h:selectBooleanCheckbox is the simplest selection tag it renders a checkbox you can wire to a boolean bean property. You can also render a set of checkboxes with h:selectManyCheckbox.

Tags whose names begin with selectOne let you select one item from a collection. The selectOne tags render sets of radio buttons, single-select menus, or listboxes. The selectMany tags render sets of checkboxes, multiselect menus, or listboxes.

All selection tags share an almost identical set of attributes, listed in Table 4-20.

Table 4-20. Attributes for h:selectBooleanCheckbox, h:selectManyCheckbox, h:selectOneRadio, h:selectOneListbox, h:selectManyListbox, h:selectOneMenu, and h:selectManyMenu
Attributes Description
disabledClass CSS class for disabled elements for h:selectOneRadio and h:selectManyCheckbox only.
enabledClass CSS class for enabled elements for h:selectOneRadio and h:selectManyCheckbox only.
layout Specification for how elements are laid out: lineDirection (horizontal) or pageDirection (vertical) for h:selectOneRadio and h:selectManyCheckbox only.
label (JSF 1.2) A description of the component for use in error messages.
binding, converter, converterMessage (JSF 1.2), requiredMessage (JSF 1.2), id, immediate, styleClass, required, rendered, validator, validatorMessage (JSF 1.2), value, valueChangeListener Basic attributes.[a]
accesskey, border, dir, disabled, lang, readonly, style, size, tabindex, title HTML 4.0[b] border is applicable to h:selectOneRadio and h:selectManyCheckbox only. size is applicable to h:selectOneListbox and h:selectManyListbox only.
onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselect DHTML events.[c]


[a] See Table 4-4 on page 97 for information about basic attributes.

[b] See Table 4-5 on page 101 for information about HTML 4.0 attributes.

[c] See Table 4-6 on page 102 for information about DHTML event attributes.

Checkboxes and Radio Buttons

Two JSF tags represent checkboxes:

  • h:selectBooleanCheckbox

  • h:selectManyCheckbox

h:selectBooleanCheckbox represents a single checkbox that you can wire to a boolean bean property. Here is an example:

In your JSF page, you do this:

   <h:selectBooleanCheckbox value="#{form.contactMe}"/>

In your backing bean, provide a read-write property:

   private boolean contactMe;    public void setContactMe(boolean newValue) {       contactMe = newValue;    }    public boolean getContactMe() {       return contactMe;    }

The generated HTML looks something like this:

   <input type="checkbox" name="_id2:_id7"/>

You can create a group of checkboxes with h:selectManyCheckbox. As the tag name implies, you can select one or more of the checkboxes in the group. You specify that group within the body of h:selectManyCheckbox, either with one or more f:selectItem tags or one f:selectItems tag. See "Items" on page 138 for more information about those core tags. For example, here is a group of checkboxes for selecting colors:

The h:selectManyCheckbox tag looks like this:

   <h:selectManyCheckbox value="#{form.colors}">       <f:selectItem itemValue="Red" itemLabel="Red"/>       <f:selectItem itemValue="Blue" itemLabel="Blue"/>       <f:selectItem itemValue="Yellow" itemLabel="Yellow"/>       <f:selectItem itemValue="Green" itemLabel="Green"/>       <f:selectItem itemValue="Orange" itemLabel="Orange"/>    </h:selectManyCheckbox>

The checkboxes are specified with f:selectItem (page 138) or f:selectItems (page 140).

The h:selectManyCheckbox tag generates an HTML table element; for example, here is the generated HTML for our color example:

   <table>       <tr>          <td>             <label for="_id2:_id14">                <input name="_id2:_id14" value="Red" type="checkbox"> Red</input>             </label>          </td>       </tr>       ...    </table>     

Each color is an input element, wrapped in a label for accessibility. That label is placed in a td element.

Radio buttons are implemented with h:selectOneRadio. Here is an example:

The value attribute of the h:selectOneRadio tag specifies the currently selected item. Once again, we use multiple f:selectItem tags to populate the radio buttons:

   <h:selectOneRadio value="#{form.education}">       <f:selectItem itemValue="High School" itemLabel="High School"/>       <f:selectItem itemValue="Bachelor's" itemLabel="Bachelor's"/>       <f:selectItem itemValue="Master's" itemLabel="Master's"/>       <f:selectItem itemValue="Doctorate" itemLabel=Doctorate"/>    </h:selectOneRadio>

Like h:selectManyCheckbox, h:selectOneRadio generates an HTML table. Here is the table generated by the preceding tag:

   <table>       <tr>          <td>             <label for="_id2:_id14">                <input name="_id2:_id14" value="High School" type="radio">                   High School                </input>             </label>          </td>       </tr>       ...    </table>

Besides generating HTML tables, h:selectOneRadio and h:selectManyCheckbox have something else in common a handful of attributes unique to those two tags:

  • border

  • enabledClass

  • disabledClass

  • layout

The border attribute specifies the width of the border. For example, here are radio buttons and checkboxes with borders of 1 and 2, respectively:

enabledClass and disabledClass specify CSS classes used when the checkboxes or radio buttons are enabled or disabled, respectively. For example, the following picture shows an enabled class with an italic font style, blue color, and yellow background:

The layout attribute can be either lineDirection (horizontal) or pageDirection (vertical). For example, the following checkboxes on the left have a pageDirection layout and the checkboxes on the right are lineDirection.

Note

You might wonder why layout attribute values are not horizontal and vertical, instead of lineDirection and pageDirection, respectively. Although lineDirection and pageDirection are indeed horizontal and vertical for Latin-based languages, that is not always the case for other languages. For example, a Chinese browser that displays text top to bottom could regard lineDirection as vertical and pageDirection as horizontal.


Menus and Listboxes

Menus and listboxes are represented by the following tags:

  • h:selectOneListbox

  • h:selectManyListbox

  • h:selectOneMenu

  • h:selectManyMenu

The attributes for the preceding tags are listed in Table 4-20 on page 132, so that discussion is not repeated here.

Menu and listbox tags generate HTML select elements. The menu tags add a size="1" attribute to the select element. That size designation is all that separates menus and listboxes.

Here is a single-select listbox:

The corresponding listbox tag looks like this:

   <h:selectOneListbox value="#{form.year}" size="5">       <f:selectItem itemValue="1900" itemLabel="1900"/>       <f:selectItem itemValue="1901" itemLabel="1901"/>       ...    </h:selectOneListbox>

Notice that we've used the size attribute to specify the number of visible items. The generated HTML looks like this:

   <select name="_id2:_id11" size="5">       <option value="1900">1900</option>       <option value="1901">1901</option>       ...    </select>

Use h:selectManyListbox for multiselect listboxes like this one:

The listbox tag looks like this:

   <h:selectManyListbox value="#{form.languages}">       <f:selectItem itemValue="English" itemLabel="English"/>       <f:selectItem itemValue="French" itemLabel="French"/>       <f:selectItem itemValue="Italian" itemLabel="Italian"/>       <f:selectItem itemValue="Spanish" itemLabel="Spanish"/>       <f:selectItem itemValue="Russian" itemLabel="Russian"/>    </h:selectManyListbox>

This time we do not specify the size attribute, so the listbox grows to accommodate all its items. The generated HTML looks like this:

   <select name="_id2:_id11" multiple>      <option value="English">English</option>      <option value="French">French</option>       ...    </select>

Use h:selectOneMenu and h:selectManyMenu for menus. A single-select menu looks like this:

h:selectOneMenu created the preceding menu:

   <h:selectOneMenu value="#{form.day}">       <f:selectItem itemValue="Sunday" itemLabel="Sunday"/>       <f:selectItem itemValue="Monday" itemLabel="Monday"/>       <f:selectItem itemValue="Tuesday" itemLabel="Tuesday"/>       <f:selectItem itemValue="Wednesday" itemLabel="Wednesday"/>       <f:selectItem itemValue="Thursday" itemLabel="Thursday"/>       <f:selectItem itemValue="Friday" itemLabel="Friday"/>       <f:selectItem itemValue="Saturday" itemLabel="Saturday"/>    </h:selectOneMenu>

Here is the generated HTML:

   <select name="_id2:_id17" size="1">       <option value="Sunday">Sunday</option>       ...    </select>

h:selectManyMenu is used for multiselect menus. That tag generates HTML, which looks like this:

   <select name="_id2:_id17" multiple size="1">       <option value="Sunday">Sunday</option>       ...    </select>

That HTML does not yield consistent results among browsers. For example, here is h:selectManyMenu on Internet Explorer (left) and Netscape (right):

Note

In HTML, the distinction between menus and listboxes is artificial. Menus and listboxes are both HTML select elements. The only distinction: Menus always have a size="1" attribute.

Browsers consistently render single-select menus as drop-down lists, as expected. But they do not consistently render multiple select menus, specified with size="1" and multiple attributes. Instead of rendering a drop-down list with multiple selection, as you might expect, some browsers render absurdities such as tiny scrollbars that are nearly impossible to manipulate (Windows IE 6) or no scrollbar at all, leaving you to navigate with arrow keys (Firefox 1.5).


Starting with "Selection Tags" on page 130, we have consistently used multiple f:selectItem to populate select components. Now that we are familiar with the fundamentals of selection tags, we take a closer look at f:selectItem and the related f:selectItems tags.

Items

All selection tags except h:selectBooleanCheckbox use f:selectItem or f:selectItems to specify their items. Next, we look at those core tags, starting with f:selectItem.

The f:selectItem Tag

You use f:selectItem to specify single selection items, like this:

   <h:selectOneMenu value="#{form.condiments}">       <f:selectItem itemValue="Cheese" itemLabel="Cheese"/>       <f:selectItem itemValue="Pickle" itemLabel="Pickle"/>       <f:selectItem itemValue="Mustard" itemLabel="Mustard"/>       <f:selectItem itemValue="Lettuce" itemLabel="Lettuce"/>       <f:selectItem itemValue="Onions" itemLabel="Onions"/>    </h:selectOneMenu>

The values Cheese, Pickle, etc. are transmitted as request parameter values when a selection is made from the menu and the menu's form is subsequently submitted. The itemLabel values are used as labels for the menu items. Sometimes you want to specify different values for request parameter values and item labels:

   <h:selectOneMenu value="#{form.condiments}">       <f:selectItem itemValue="1" itemLabel="Cheese"/>       <f:selectItem itemValue="2" itemLabel="Pickle"/>       <f:selectItem itemValue="3" itemLabel="Mustard"/>       <f:selectItem itemValue="4" itemLabel="Lettuce"/>       <f:selectItem itemValue="5" itemLabel="Onions"/>    </h:selectOneMenu>

In the preceding code, the item values are strings. "Binding the value Attribute" on page 145 shows you how to use different data types for item values.

In addition to labels and values, you can also supply item descriptions and specify an item's disabled state:

     <f:selectItem itemLabel="Cheese" itemValue="#{form.cheeseValue}"            itemDescription="used to be milk"            itemDisabled="true"/>

Item descriptions are for tools only they do not affect the generated HTML. The itemDisabled attribute, however, is passed to HTML. The f:selectItem tag has the attributes shown in Table 4-21.

Table 4-21. Attributes for f:selectItem
Attribute Description
binding Component binding see Chapter 2 for more information about component bindings
id Component ID
itemDescription Description used by tools only
itemDisabled Boolean value that sets the item's disabled HTML attribute
itemLabel Text shown by the item
itemValue Item's value, which is passed to the server as a request parameter
value Value expression that points to a SelectItem instance
escape (JSF 1.2) true if special characters in the value should be converted to character entities (default), false if the value should be emitted without change


You can use f:selectItem's value attribute to access SelectItem instances created in a bean:

   <f:selectItem value="#{form.cheeseItem}"/>

The value expression for the value attribute points to a method that returns a javax.faces.model.SelectItem instance:

   public SelectItem getCheeseItem()  {       return new SelectItem("Cheese");    }

javax.faces.model.SelectItem

  • SelectItem(Object value)

    Creates a SelectItem with a value. The item label is obtained by applying toString() to the value.

  • SelectItem(Object value, String label)

    Creates a SelectItem with a value and a label.

  • SelectItem(Object value, String label, String description)

    Creates a SelectItem with a value, label, and description.

  • SelectItem(Object value, String label, String description, boolean disabled)

    Creates a SelectItem with a value, label, description, and disabled state.


The f:selectItems Tag

As we saw in "The f:selectItem Tag" on page 138, f:selectItem is versatile, but it is tedious for specifying more than a few items. The first code fragment shown in that section can be reduced to the following with f:selectItems:

   <h:selectOneRadio value="#{form.condiments}>       <f:selectItems value="#{form.condimentItems}"/>    </h:selectOneRadio>

The value expression #{form.condimentItems} could point to an array of SelectItem instances:

   private static SelectItem[] condimentItems = {       new SelectItem(1, "Cheese"),       new SelectItem(2, "Pickle"),       new SelectItem(3, "Mustard"),       new SelectItem(4, "Lettuce"),       new SelectItem(5, "Onions")    };       public SelectItem[] getCondimentItems() {          return condimentItems;       }

The f:selectItems value attribute must be a value expression that points to one of the following:

  • A single SelectItem instance

  • A collection of SelectItem instances

  • An array of SelectItem instances

  • A map whose entries represent SelectItem labels and values

Note

Can't remember what you can specify for the f:selectItems value attribute? It's a SCAM: Single select item; Collection of select items; Array of select items; Map.


Note

A single f:selectItems tag is usually better than multiple f:selectItem tags. If the number of items changes, you have to modify only Java code if you use f:selectItems, whereas f:selectItem may require you to modify both Java code and JSF pages.


If you specify a map, the JSF implementation creates a SelectItem instance for every entry in the map. The entry's key is used as the item's label, and the entry's value is used as the item's value. For example, here are condiments specified with a map:

   private Map<String, Object> condimentItem = null;        public Map<String, Object> getCondimentItems() {       if (condimentItem == null) {           condimentItem = new LinkedHashMap<String, Object>();           condimentItem.put("Cheese",   1); // label, value           condimentItem.put("Pickle",   2);           condimentItem.put("Mustard", 3);           condimentItem.put("Lettuce", 4);           condimentItem.put("Onions",   5);       }       return condimentItem;    }

Note that you cannot specify item descriptions or disabled status when you use a map.

If you use SelectItem, you couple your code to the JSF API. You avoid that coupling when you use a Map, which makes it an attractive alternative. However, pay attention to these issues.

  1. You will generally want to use a LinkedHashMap, not a TreeMap or HashMap. In a LinkedHashMap, you can control the order of the items because items are visited in the order in which they were inserted. If you use a TreeMap, the labels that are presented to the user (which are the keys of the map) are sorted alphabetically. That may or may not be what you want. For example, days of the week would be neatly arranged as Friday Monday Saturday Sunday Thursday Tuesday Wednesday. If you use a HashMap, the items are ordered randomly.

  2. Map keys are turned into item labels and map values into item values. When a user selects an item, your backing bean receives a value in your map, not a key. For example, in the example above, if the backing bean receives a value of 5, you would need to iterate through the entries if you wanted to find the matching "Onions". Since the value is probably more meaningful to your application than the label, this is usually not a problem, just something to be aware of.

Item Groups

You can group menu or listbox items together, like this:

Here are the JSF tags that define the listbox:

   <h:selectManyListbox>       <f:selectItems value="#{form.menuItems}"/>    </h:selectManyListbox>

The menuItems property is a SelectItem array:

  public SelectItem[] getMenuItems() { return menuItems; }

The menuItems array is instantiated like this:

  private static SelectItem[] menuItems = { burgers, beverages, condiments };     

The burgers, beverages, and condiments variables are SelectItemGroup instances that are instantiated like this:

   private SelectItemGroup burgers =       new SelectItemGroup("Burgers",    // value          "burgers on the menu",         // description          false,                         // disabled          burgerItems);                  // select items    private SelectItemGroup beverages =       new SelectItemGroup("Beverages",  // value          "beverages on the menu",       // description          false,                         // disabled          beverageItems);                // select items    private SelectItemGroup condiments =       new SelectItemGroup("Condiments",  // value          "condiments on the menu",       // description          false,                          // disabled          condimentItems);                // select items

Notice that we are using SelectItemGroups to populate an array of SelectItems. We can do that because SelectItemGroup extends SelectItem. The groups are created and initialized like this:

   private SelectItem[] burgerItems = {       new SelectItem("Qwarter pounder"),       new SelectItem("Single"),       new SelectItem("Veggie"),    };    private SelectItem[] beverageItems = {       new SelectItem("Coke"),       new SelectItem("Pepsi"),       new SelectItem("Water"),       new SelectItem("Coffee"),       new SelectItem("Tea"),    };    private SelectItem[] condimentItems = {        new SelectItem("cheese"),        new SelectItem("pickle"),        new SelectItem("mustard"),        new SelectItem("lettuce"),        new SelectItem("onions"),    };

SelectItemGroup instances encode HTML optgroup elements. For example, the preceding code generates the following HTML:

  <select name="_id0:_id1" multiple size="16">      <optgroup label="Burgers">         <option value="1"  selected>Qwarter pounder</option>         <option value="2">Single</option>         <option value="3">Veggie</option>      </optgroup>      <optgroup label="Beverages">         <option value="4"  selected>Coke</option>         <option value="5">Pepsi</option>         <option value="6">Water</option>         <option value="7">Coffee</option>         <option value="8">Tea</option>      </optgroup>      <optgroup label="Condiments">         <option value="9">cheese</option>         <option value="10">pickle</option>         <option value="11">mustard</option>         <option value="12">lettuce</option>         <option value="13">onions</option>      </optgroup>   </select>

Note

The HTML 4.01 specification does not allow nested optgroup elements, which would be useful for things like cascading menus. The specification does mention that future HTML versions may support that behavior.


javax.faces.model.SelectItemGroup


  • SelectItemGroup(String label)

    Creates a group with a label but no selection items.

  • SelectItemGroup(String label, String description, boolean disabled, SelectItem[] items)

    Creates a group with a label, a description (which is ignored by the JSF Reference Implementation), a boolean that disables all the items when true, and an array of select items used to populate the group.

  • setSelectItems(SelectItem[] items)

    Sets a group's array of SelectItems.

Binding the value Attribute

In all likelihood, whether you are using a set of checkboxes, a menu, or a listbox, you will want to keep track of selected items. For that purpose, you can exploit selectOne and selectMany tags, which have value attributes that represent selected items. For example, you can specify a selected item with the h:selectOneRadio value attribute, like this:

   <h:selectOneRadio value="#{form.beverage}">       <f:selectItems value="#{form.beverageItems}"/>    </h:selectOneRadio>

The #{form.beverage} value expression refers to the beverage property of a bean named form. That property is implemented like this:

   private Integer beverage;    public Integer getBeverage() {       return beverage;    }    public void setBeverage(Integer newValue) {       beverage = newValue;    }

Notice that the beverage property type is Integer. That means the radio buttons must have Integer values. Those radio buttons are specified with f:selectItems, with a value attribute that points to the beverageItems property of the form bean:

   private static SelectItem[] beverageItems = {       new SelectItem(1, "Water"),  // value, label       new SelectItem(2, "Cola"),       new SelectItem(3, "Orange Juice")    };    public SelectItem[] getBeverageItems() {       return beverage;    }

In the preceding example, we chose the Integer type to represent beverages. You can choose any type you like as long as the properties for items and selected item have matching types. An enumerated type would be a better choice in this case (see Listing 4-14 for an example).

You can keep track of multiple selections with a selectMany tag. These tags also have a value attribute that lets you specify one or more selected items. That attribute's value must be an array or list of convertible types.

Now we take a look at some different data types. We will use h:selectManyListbox to let a user choose multiple condiments:

   <h:selectManyListbox value="#{form.condiments}">       <f:selectItems value="#{form.condimentItems}"/>    </h:selectManyListbox>

Here are the condimentItems and condiments properties:

   private static SelectItem[] condimentItems = {       new SelectItem(1, "Cheese"),       new SelectItem(2, "Pickle"),       new SelectItem(3, "Mustard"),       new SelectItem(4, "Lettuce"),       new SelectItem(5, "Onions"),   };   public SelectItem[] getCondimentItems() {      return condimentItems;   }   private Integer[] condiments;   public void setCondiments(Integer[] newValue) {      condiments = newValue;   }   public Integer[] getCondiments() {      return condiments;   }

Instead of an Integer array for the condiments property, we could have used the corresponding primitive type, int:

   private int[] condiments;    public void setCondiments(int[] newValue) {       condiments = newValue;    }    public int[] getCondiments() {       return condiments;    }

If you use strings for item values, you can use a string array or list of strings for your selected items property:

   private static SelectItem[] condimentItems = {       new SelectItem("cheese", "Cheese"),       new SelectItem("pickle", "Pickle"),       new SelectItem("mustard", "Mustard"),       new SelectItem("lettuce", "Lettuce"),       new SelectItem("onions", "Onions"),    };    public SelectItem[] getCondimentItems() {       return condimentItems;    }    private String[] condiments;    public void setCondiments(String[] newValue) {       condiments = newValue;    }    public String[] getCondiments() {       return condiments;    }

The preceding condiments property is an array of strings. You could use a collection instead:

   private static Collection<SelectItem> condiments;    static {       condiments = new ArrayListList<SelectItem>();       condiments.add(new SelectItem("cheese", "Cheese"));       condiments.add(new SelectItem("pickle", "Pickle"));       condiments.add(new SelectItem("mustard", "Mustard"));       condiments.add(new SelectItem("lettuce", "Lettuce"));       condiments.add(new SelectItem("onions", "Onions"));    }    public List getCondiments() { return condiments; }

All Together: Checkboxes, Radio Buttons, Menus, and Listboxes

We close out our section on selection tags with an example that exercises nearly all those tags. That example, shown in Figure 4-7, implements a form requesting personal information. We use an h:selectBooleanCheckbox to determine whether the user wants to receive email, and h:selectOneMenu lets the user select the best day of the week for us to call.

Figure 4-7. Using checkboxes, radio buttons, menus, and listboxes


The year listbox is implemented with h:selectOneListbox; the language check-boxes are implemented with h:selectManyCheckbox; the education level is implemented with h:selectOneRadio.

When the user submits the form, JSF navigation takes us to a JSF page that shows the data the user entered.

The directory structure for the application shown in Figure 4-7 is shown in Figure 4-8. The JSF pages, RegisterForm bean, faces configuration file, and resource bundle are shown in Listing 4-12 through Listing 4-16.

Figure 4-8. The directory structure of the personal information example


Listing 4-12. select/web/index.jsp

  1. <html>   2.    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>   3.    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>   4.    <f:view>   5.       <head>   6.          <link href="styles.css" rel="stylesheet" type="text/css"/>   7.          <title>   8.             <h:outputText value="#{msgs.indexWindowTitle}"/>   9.          </title>  10.       </head>  11.  12.       <body>  13.          <h:outputText value="#{msgs.indexPageTitle}" style/>  14.          <h:form>  15.             <table>  16.                <tr>  17.                   <td>  18.                      <h:outputText value="#{msgs.namePrompt}"/>  19.                   </td>  20.                   <td>  21.                      <h:inputText value="#{form.name}"/>  22.                   </td>  23.                </tr>  24.                <tr>  25.                   <td>  26.                      <h:outputText value="#{msgs.contactMePrompt}"/>  27.                   </td>  28.                   <td>  29.                      <h:selectBooleanCheckbox value="#{form.contactMe}"/>  30.                   </td>  31.                </tr>  32.                <tr>  33.                   <td>  34.                      <h:outputText value="#{msgs.bestDayPrompt}"/>  35.                   </td>  36.                   <td>  37.                      <h:selectManyMenu value="#{form.bestDaysToContact}">  38.                         <f:selectItems value="#{form.daysOfTheWeekItems}"/>  39.                      </h:selectManyMenu>  40.                   </td>  41.                </tr>  42.                <tr>  43.                   <td>  44.                      <h:outputText value="#{msgs.yearOfBirthPrompt}"/>  45.                   </td>  46.                   <td>  47.                      <h:selectOneListbox size="5" value="#{form.yearOfBirth}">  48.                         <f:selectItems value="#{form.yearItems}"/>  49.                      </h:selectOneListbox>  50.                   </td>  51.                </tr>  52.                <tr>  53.                   <td>  54.                      <h:outputText value="#{msgs.colorPrompt}"/>  55.                   </td>  56.                   <td>  57.                      <h:selectManyCheckbox value="#{form.colors}">  58.                         <f:selectItems value="#{form.colorItems}"/>  59.                      </h:selectManyCheckbox>  60.                   </td>  61.                </tr>  62.                <tr>  63.                   <td>  64.                      <h:outputText value="#{msgs.languagePrompt}"/>  65.                   </td>  66.                   <td>  67.                      <h:selectManyListbox value="#{form.languages}">  68.                         <f:selectItems value="#{form.languageItems}"/>  69.                      </h:selectManyListbox>  70.                   </td>  71.                </tr>  72.                <tr>  73.                   <td>  74.                      <h:outputText value="#{msgs.educationPrompt}"/>  75.                   </td>  76.                   <td>  77.                      <h:selectOneRadio value="#{form.education}"  78.                         layout="pageDirection">  79.                         <f:selectItems value="#{form.educationItems}"/>  80.                      </h:selectOneRadio>  81.                   </td>  82.                </tr>  83.             </table>  84.             <h:commandButton value="#{msgs.buttonPrompt}"  85.                action="showInformation"/>  86.          </h:form>  87.          <h:messages/>  88.       </body>  89.    </f:view>  90. </html>     

Listing 4-13. select/web/showInformation.jsp

  1. <html>   2.    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>   3.    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>   4.    <f:view>   5.       <head>   6.          <link href="styles.css" rel="stylesheet" type="text/css"/>   7.          <title>   8.             <h:outputText value="#{msgs.indexWindowTitle}"/>   9.          </title>  10.       </head>  11.  12.       <body>  13.          <h:outputFormat value="#{msgs.thankYouLabel}">  14.             <f:param value="#{form.name}"/>  15.          </h:outputFormat>  16.          <p>  17.          <table>  18.             <tr>  19.                <td><h:outputText value="#{msgs.contactMeLabel}"/></td>  20.                <td><h:outputText value="#{form.contactMe}"/></td>  21.             </tr>  22.  23.             <tr>  24.                <td><h:outputText value="#{msgs.bestDayLabel}"/></td>  25.                <td><h:outputText value="#{form.bestDaysConcatenated}"/></td>  26.             </tr>  27.  28.             <tr>  29.                <td><h:outputText value="#{msgs.yearOfBirthLabel}"/></td>  30.                <td><h:outputText value="#{form.yearOfBirth}"/></td>  31.             </tr>  32.  33.             <tr>  34.                <td><h:outputText value="#{msgs.languageLabel}"/></td>  35.                <td><h:outputText value="#{form.languagesConcatenated}"/></td>  36.             </tr>  37.  38.             <tr>  39.                <td><h:outputText value="#{msgs.colorLabel}"/></td>  40.                <td><h:outputText value="#{form.colorsConcatenated}"/></td>  41.             </tr>  42.  43.             <tr>  44.                <td><h:outputText value="#{msgs.educationLabel}"/></td>  45.                <td><h:outputText value="#{form.education}"/></td>  46.             </tr>  47.          </table>  48.       </body>  49.    </f:view>  50. </html>     

Listing 4-14. select/src/java/com/corejsf/RegisterForm.java

  1. package com.corejsf;   2.   3. import java.text.DateFormatSymbols;   4. import java.util.ArrayList;   5. import java.util.Calendar;   6. import java.util.Collection;   7. import java.util.HashMap;   8. import java.util.LinkedHashMap;   9. import java.util.Map;  10.  11. import javax.faces.model.SelectItem;  12.  13. public class RegisterForm {  14.    enum Education { HIGH_SCHOOL, BACHELOR, MASTER, DOCTOR };  15.  16.    private String name;  17.    private boolean contactMe;  18.    private Integer[] bestDaysToContact;  19.    private Integer yearOfBirth;  20.    private String[] colors;  21.    private String[] languages;  22.    private Education education;  23.  24.    // PROPERTY: name  25.    public String getName() {  26.       return name;  27.    }  28.    public void setName(String newValue) {  29.       name = newValue;  30.    }  31.  32.    // PROPERTY: contactMe  33.    public boolean getContactMe() {  34.       return contactMe;  35.    }  36.    public void setContactMe(boolean newValue) {  37.       contactMe = newValue;  38.    }  39.  40.    // PROPERTY: bestDaysToContact  41.    public Integer[] getBestDaysToContact() {  42.       return bestDaysToContact;  43.    }  44.    public void setBestDaysToContact(Integer[] newValue) {  45.       bestDaysToContact = newValue;  46.    }  47.  48.    // PROPERTY: yearOfBirth  49.    public Integer getYearOfBirth() {  50.       return yearOfBirth;  51.    }  52.    public void setYearOfBirth(Integer newValue) {  53.       yearOfBirth = newValue;  54.    }  55.  56.    // PROPERTY: colors  57.    public String[] getColors() {  58.       return colors;  59.    }  60.    public void setColors(String[] newValue) {  61.       colors = newValue;  62.    }  63.  64.    // PROPERTY: languages  65.    public String[] getLanguages() {  66.       return languages;  67.    }  68.    public void setLanguages(String[] newValue) {  69.       languages = newValue;  70.    }  71.  72.    // PROPERTY: education  73.    public Education getEducation() {  74.       return education;  75.    }  76.  77.    public void setEducation(Education newValue) {  78.       education = newValue;  79.    }  80.  81.    // PROPERTY: yearItems  82.    public Collection<SelectItem> getYearItems() {  83.       return birthYears;  84.    }  85.  86.    // PROPERTY: daysOfTheWeekItems  87.    public SelectItem[] getDaysOfTheWeekItems() {  88.       return daysOfTheWeek;  89.    }  90.  91.    // PROPERTY: languageItems  92.    public Map<String, Object> getLanguageItems() {  93.       return languageItems;  94.    }  95.  96.    // PROPERTY: colorItems  97.    public SelectItem[] getColorItems() {  98.       return colorItems;  99.    } 100. 101.    // PROPERTY: educationItems 102.    public SelectItem[] getEducationItems() { 103.       return educationItems; 104.    } 105. 106.    // PROPERTY: bestDaysConcatenated 107.    public String getBestDaysConcatenated() { 108.       return concatenate(bestDaysToContact); 109.    } 110. 111.    // PROPERTY: languagesConcatenated 112.    public String getLanguagesConcatenated() { 113.       return concatenate(languages); 114.    } 115. 116.    // PROPERTY: colorsConcatenated 117.    public String getColorsConcatenated() { 118.       return concatenate(colors); 119.    } 120. 121.    private static String concatenate(Object[] values) { 122.       if (values == null) 123.          return ""; 124.       StringBuilder r = new StringBuilder(); 125.       for (Object value : values) { 126.          if (r.length()> 0) 127.             r.append(','); 128.          r.append(value.toString()); 129.       } 130.       return r.toString(); 131.    } 132. 133.    private static SelectItem[] colorItems = { 134.       new SelectItem("Red"), 135.       new SelectItem("Blue"), 136.       new SelectItem("Yellow"), 137.       new SelectItem("Green"), 138.       new SelectItem("Orange") 139.    }; 140. 141.    private static SelectItem[] educationItems = { 142.       new SelectItem(Education.HIGH_SCHOOL, "High School"), 143.       new SelectItem(Education.BACHELOR, "Bachelor's"), 144.       new SelectItem(Education.MASTER, "Master's"), 145.       new SelectItem(Education.DOCTOR, "Doctorate") }; 146. 147.    private static Map<String, Object> languageItems; 148.    static { 149.       languageItems = new LinkedHashMap<String, Object>(); 150.       languageItems.put("English", "en"); // item, value 151.       languageItems.put("French", "fr"); 152.       languageItems.put("Russian", "ru"); 153.       languageItems.put("Italian", "it"); 154.       languageItems.put("Spanish", "es"); 155.    } 156. 157.    private static Collection<SelectItem> birthYears; 158.    static { 159.       birthYears = new ArrayList<SelectItem>(); 160.       for (int i = 1900; i < 2000; ++i) { 161.          birthYears.add(new SelectItem(i)); 162.       } 163.    } 164. 165.    private static SelectItem[] daysOfTheWeek; 166.    static { 167.       DateFormatSymbols symbols = new DateFormatSymbols(); 168.       String[] weekdays = symbols.getWeekdays(); 169.       daysOfTheWeek = new SelectItem[7]; 170.       for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) { 171.          daysOfTheWeek[i - 1] = new SelectItem(new Integer(i), weekdays[i]); 172.       } 173.     } 174.  }     

Listing 4-15. select/src/java/com/corejsf/messages.properties

  1. indexWindowTitle=Checkboxes, Radio buttons, Menus, and Listboxes   2. indexPageTitle=Please fill out the following information   3.   4. namePrompt=Name:   5. contactMePrompt=Contact me   6. bestDayPrompt=What's the best day to contact you?   7. yearOfBirthPrompt=What year were you born?   8. buttonPrompt=Submit information   9. languagePrompt=Select the languages you speak:  10. educationPrompt=Select your highest education level:  11. emailAppPrompt=Select your email application:  12. colorPrompt=Select your favorite colors:  13.  14. thankYouLabel=Thank you {0}, for your information  15. contactMeLabel=Contact me:  16. bestDayLabel=Best day to contact you:  17. yearOfBirthLabel=Your year of birth:  18. colorLabel=Colors:  19. languageLabel=Languages:  20. educationLabel=Education:

Listing 4-16. select/web/WEB-INF/faces-config.xml

  1. <?xml version="1.0"?>   2. <faces-config xmlns="http://java.sun.com/xml/ns/javaee"   3.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   4.    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   5.         http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"   6.    version="1.2">   7.    <navigation-rule>   8.       <navigation-case>   9.          <from-outcome>showInformation</from-outcome>  10.          <to-view-id>/showInformation.jsp</to-view-id>  11.       </navigation-case>  12.    </navigation-rule>  13.    <managed-bean>  14.       <managed-bean-name>form</managed-bean-name>  15.       <managed-bean-class>com.corejsf.RegisterForm</managed-bean-class>  16.       <managed-bean-scope>session</managed-bean-scope>  17.    </managed-bean>  18.    <application>  19.       <resource-bundle>  20.          <base-name>com.corejsf.messages</base-name>  21.          <var>msgs</var>  22.       </resource-bundle>  23.    </application>  24. </faces-config>     



Core JavaServerT Faces
Core JavaServer(TM) Faces (2nd Edition)
ISBN: 0131738860
EAN: 2147483647
Year: 2004
Pages: 84

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net