JSFTags

Standard JSF Tags

Draft

This document is third part in jAstrologer series of JSF tutorials.In first two parts we created simple web application called jAstrologer. You can download it there, if you haven't got through previous two parts.
So far jAstrologer does the following :

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

So far we know how to work with some of most basic JSF tags - inputText,outputText and commandButton. In this tutorial we won't be presenting complete set of tags along with all available attributes-common,HTML or DHTML. You can find it elsewhere,for example in J2EE tutorial. We will instead show how to use some of most commonly used tags in web based forms like links, testAreas, radioButtons, menus or listBoxes. In this section we will do:

  • Modify existing inputText textboxes of name,email and birthday using HTML attributes.
  • Add inputTextArea notes with predefined size for user notes.
  • Add selectOneRadio radiobutton list degree to let user select his highest education earned.
  • Add selectOneMenu dropdownlist sign to define user's zodiac sign.
  • Handle case when user doesn't know his sign and compute it from birthday date.
  • Modify success page by adding navigation link for return to input page.




Contents





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:

  • NetBeans IDE 5.5 (download).
  • Java Standard Development Kit (JDK) version 5.0 (download)
  • Sun Java System Application Server Platform Edition 9 (download)


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


Update existing textfields

Let's prefer slow start,so fist we'll show,how we could improve tags we already have used. We can modify them by setting some boundaries of input values.

  • Open greeting.jsp and modify components this way :
                <p>Enter your name: <h:inputText value="#{UserBean.name}"
                                                     id="name" size="30" required="true"/>
                <h:message for="name" style="color:#369;"/></p>
                <p>Enter your email: <h:inputText value="email"
                                                      id="email" size="50" required="true">
                        <f:validator validatorId="astrologer.EmailValidator" />
                    </h:inputText>
                <h:message for="email" style="color:#369;"/></p>
                <p>Enter your birthday: <h:inputText id="date" value="#{UserBean.birthday}" maxlength="10">
                        <f:converter converterId="astrologer.MyDateConverter" />
                    </h:inputText> <h:message for="date" style="color:#369;" />
                (dd/mm/yyyy)</p>

  • Run jAstrologer and see the result :

Image:modified_JSFTags.png

As you see, textfields are now different length, since we defined 30 letters for name and 50 for email. In birthday textfield you're now restricted to 10 characters,so longer strings could be entered no more. The same way is possible to change textfield's background or foreground colors,font styles and another properties we already know from HTML, since tag inputText accepts all commonly used HTML and DHTML parameters.

Using inputTextArea tag


Now we can do something more and show, how to add inputTextArea tag for larger text data input and set its size.

  • Go to greeting.jsp and add this code just under (dd/mm/yyyy)</p> line.
      <p>Notes:<h:inputTextarea rows="5" cols="50" value="#{UserBean.notes}"/></p>

This tag creates text area for notes with 5 rows of 50 columns each and stores its value into notes property in UserBean. Data from this input are transfered into one String with rows ending by \n sequence.

  • Now we have to create notes property in UserBean . Add private String notes; in bean's property declarations area.
  • Do Refactor > Encapsulate Fields .
  • Input page now looks lite this:

Image:notes_JSFTags.png
Notify that textarea box is sized exactly as we defined, but if you try to enter text longer than 250 characters, slider on the right side will appear.

  • Finally add into success.jsp
<p><h:outputText value="#{UserBean.notes}" /></p>

to display your comments.

Add selectOneRadio tag


Select tags are used for selecting input value(s) from set of predefined values. Basically it could be represented by set of checkboxlist (selectOneRadio), dropdownlist (selectOneMenu/selectManyMenu) or listbox (selectOneListbox / selectManyListbox) . Each of the controls presents set of choice values,which we choose from and this values are each encapsulated by selectItem class instances.

  • First we add checkboxlist for selecting user's education degree. Insert this code above Submit command button's line.
           <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>


The border attribute defines thickness of line around the checkboxlist,you can try to play with different values to see,how it changes. The layout attribute defines if the list is oriented horizontally or vertically,like in this case.

  • Now we should change UserBean by adding degree property for stored education skill. Add private String degree = "Unspecified"; line into declaration area and invoke Refactor > Encapsulate fields.
  • Last action is updating success.jsp.Open page in editor and add this line:
          <b>You have <h:outputText value="#{UserBean.degree}" /> education.</p>
  • Now you can run the application and see the result:

Image:checkboxlist_JSFTags.png
Image:newsuccess_JSFTags.png

Add selectOneMenu tag


Now we already know,how to create selection tag and display selected value in output page. But what if we don't want publish select tag choices in the page,but rather to hide then inside backing bean? Easy help. We'll show now,how to do it and we join pleasant with useful, so we'll create selectOneMenu tag now, which allow us to select user's zodiac sign.

  • Add following code into greeting.jsp right above command button tag
            <p><h:selectOneMenu value="#{UserBean.sign}" required="true" >
                    <f:selectItems value="#{UserBean.signs}"/>
            </h:selectOneMenu></p>


From the code you can see,that in this case we aren't publishing each of select tag's values, but instead we bind to values an array from backing bean. Selected value is again stored in string property.

  • In second step we'll add sign property and signs array into backing bean and create also getters and setters. Add following code.
           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"),
          }; 


Fix imports and encapsulate fields. This way we added sign property and declared array signs,consisting of multiple SelectItem instances.In this case we use simpliest of constructors,only with value parameter and for choice label is used toString() value of the parameter,which is hidden to us.Now we have labels for choices in select tag and only thing that is missing is update success.jsp page.

  • Add this code into success.jsp above degree outputText tag.
          <p>Your zodiac sign is <h:outputText value="#{UserBean.sign}" /></p> 
  • Run jAstrologer application

Image:Final_JSFTags.png

Image:finalsuccess_JSFTags.png

Compute birthsign from birthday date


There's one thing in question now - what if user doesn't know his birthsign? Easy help! We could find out his sign from birth date he already entered! To make it easier, we simply add "I don't know" into signs and if user chooses this choice, we'll compute sign programmatically.

  • Modify property sign declaration to private String sign = "";
  • Add into signs in UserBean "I don't know" choice
          new SelectItem("I don't know"),
  • Update getSign() method this way
          public String getSign() {
             if(sign.equals("I don't know"))
                   tellSign();
             return sign;
          }
  • Add tellSign() method
    public void tellSign(){
       //I'll have to get to 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;
        }
    }
  • Modify Menu tag this by adding label tag next to it
                <p><h:selectOneMenu value="#{UserBean.sign}" required="true" >
                        <f:selectItems value="#{UserBean.signs}"/>
                    </h:selectOneMenu>
                <h:outputLabel value="#{UserBean.message}" style="color:#f00;" /></p> 
  • And finally add into UserBean message property and Encapsulate Fields
         private String message = "";

Link for return to greeting.jsp


All we've done till now is great,but there's still one small flaw. What if we want to return to input page? We need to add some navigation control, which will take us back to greeting.jsp and that's exactly where command link will be involved. We won't use button in this case, since it's output page and navigation between pages is one of link's main purposes.

  • Go to success.jsp and add this code:


               <p><h:outputLink value="#{UserBean.navigate}" >
                    <h:outputText value="#{UserBean.linkText}"/>
               </h:outputLink>

We will store link's text and navigation URL in backing bean, but it could be of course defined directly in page success.jsp.

  • Add following code into UserBean
               private String navigate = "/jAstrologer/faces/greeting.jsp";
               private String linkText = "Back to previous page";

And now it's done.If you click on "Back to previous page" link in success.jsp, you will be redirected back to greetings.jsp and form values will reset.Final page could look for example this way:
Image:Result_JSFTags.png

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo