Programming Java Server Faces Applications

download Programming Java Server Faces Applications

of 34

Transcript of Programming Java Server Faces Applications

  • 8/14/2019 Programming Java Server Faces Applications

    1/34

    All rights reserved. Reproduction and/or distribution in whole or inpart in electronic, paper or other forms without written permission

    is prohibited.

    Developing Webbased User Interfaces UsingJavaServer Faces

    SkillSoft Corporation. (c) 2005. Copying Prohibited.

    Reprinted for Sridhar Poduri, [email protected]

    Reprinted with permission as a subscription benefit of Books24x7,http://www.books24x7.com/

    http://www.books24x7.com/http://www.books24x7.com/
  • 8/14/2019 Programming Java Server Faces Applications

    2/34

    Table of ContentsChapter 2: Programming JavaServer Faces Applications............................................................1

    JSF Binding Expressions................................................................................................................2Value Binding Expressions.....................................................................................................2Method Binding Expressions..................................................................................................4

    Introducing the JSF Custom Tag Library.......................................................................................5The Core Custom Tag Library................................................................................................5The HTML Custom Tag Library..............................................................................................7

    Page Navigation in JSF Applications.............................................................................................9Specifying Navigation Rules...................................................................................................9Performing Simple Page Navigation.....................................................................................10Performing Conditional Page Navigation..............................................................................12

    Handling Events in JSF Applications...........................................................................................22Handling Action Events in a Backing Bean...........................................................................22Handling Action Events in an Event Listener........................................................................25Handling Value Changed Events..........................................................................................29

    i

  • 8/14/2019 Programming Java Server Faces Applications

    3/34

    Chapter 2: Programming JavaServer FacesApplicationsThe JavaServer Faces (JSF) framework uses binding expressions that constitute an ExpressionLanguage (EL) to associate User Interface (UI) components with the properties and methods ofbacking beans. You can use binding expressions in the custom tags of JSF custom tag libraries.These custom tag libraries include the JSF components of a JSF page. The JSF frameworkcontains a core and an HTML custom tag library.

    The JSF framework provides a navigation model that helps navigate among the Web pages of aWeb application. As a developer, you need to define navigation rules in the faces configuration file.The JSF framework also provides an eventhandling model that you can use to handle events thatarise because of enduser action on JSF components.

    This chapter introduces JSF expressions and explains how to use them in JSF pages. It describesthe JSF custom tags present in the JSF core and HTML tag libraries and how to perform pagenavigation and handle events in JSF applications.

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    4/34

    JSF Binding ExpressionsA JSF page uses custom tags to include JSF components. The custom tags can contain bindingexpressions to bind a component with a property or method of a backing bean. The syntax ofbinding expressions is based on the JavaServer Pages (JSP) 2.0 EL with a minor difference. InJSP, the expression delimiters are "${}" while in JSF, they are "#{}". A binding expression can be a:

    Value binding expression: Binds a JSF component to a property of a backing bean.

    Method binding expression: Binds a JSF component to a method of a backing bean.

    Value Binding Expressions

    A value binding expression binds the value of JSF components to the results of a backing bean. Forexample, the OutputText component that displays the current stock information of companies canretrieve the value of the stock from a backing bean using a value binding expression, as shown:

    Note The value binding expression "#{stock.stockValue}" is equivalent to the expression"#{stock["stockValue"]}".

    For this value binding expression, the JSF framework calls the getStockValue() method of thebacking bean represented as stock and inserts the result in the value attribute.

    You can use a value binding expression to compute other attributes of a JSF component. Forexample, output components such as OutputText contain a rendered attribute with a boolean valuethat determines whether the component should be displayed or not. You can use a value bindingexpression for the rendered attribute to check a condition with a backing bean. If the result returns atrue boolean value, then the stock value appears. The following code shows how to use the

    rendered attribute to display a value using a value binding expression:

    You can use a value binding expression to access the properties of the type array, List, and Mapobjects of a backing bean. For example, if a backing bean contains an address property of type Listor String array, you can access the first element of the List or array using a value bindingexpression, as shown:

    #{binderBean.address[0]}

    If a backing bean contains a Map object called cities, you can access a value of the Map objectusing a value binding expression, as shown:

    #{binderBean.cities["key"]}

    Listing 21 shows the content of the BackingBean class that contains the properties of the typeString array, List, and Map objects:

    Listing 21: The BackingBean Class

    package valuebinding;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class BackingBean{

    /*Declare bean properties*/

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    5/34

    private String[] zip = {"94025", "94618"};private List address;private Map cities;/*Initialize properties in Bean constructor*/public BackingBean(){

    /*Initialize ArrayList*/address = new ArrayList();address.add("589 Darwin Ln.");address.add("2500 bridge road");

    /*Initialize HashMap*/cities = new HashMap();cities.put("94025", "Menlo Park");cities.put("94618", "Oakland");

    }/*Accessor method for address*/public List getAddress() {

    return address;}/*Accessor method for zip*/public String[] getZip() {

    return zip;}/*Accessor method for cities*/public Map getCities() {

    return cities;

    }}

    The above listing creates a BackingBean class that contains the properties of the type array, Map,and List objects.

    You can access the properties of the BackingBean class on a JSF page using a value bindingexpression.

    Listing 22 shows the valuebinding.jsp page that uses value binding expressions to display theproperties of the BackingBean class using OutputText components:

    Listing 22: The valuebinding.jsp Page

    Using Value Binding Expressions
    Accessing List property of backing beanFirst Address:
    Second Address:

    Accessing Array property of backing beanFirst zip code:
    Second zip code:

    Accessing Map property of backing beanFirst City:
    Second City:

    The above listing creates the valuebinding.jsp page that uses value binding expressions to displaythe properties of a backing bean using OutputText components.

    Developing Webbased User Interfaces Using JavaServer Faces 3

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    6/34

    When you access the valuebinding.jsp page from a browser, the page displays the property valuesof the backing bean, as shown in Figure 21:

    Figure 21: Output of the valuebinding.jsp Page

    Method Binding ExpressionsA method binding expression binds the value of a JSF component to the result that a public methodof a backing bean returns. You can also pass parameters to the backing bean method using amethod binding expression.

    Table 21 describes the attributes of JSF custom tags that accept method binding expressions andthe corresponding method syntax:

    Table 21: Attributes Supporting Method Binding Expressions

    Attribute Description Method Syntax

    action Associates amethod that returnsthe outcome of anaction.

    public String ();

    validator Associates amethod thatperforms datavalidation.

    public void (javax.faces.event.ActionEvent);

    actionListener Associates amethod that handlesaction events.

    public void (javax.faces.context.FacesContext,javax.faces.component.UIComponent,java.lang.Object);

    valueChangeListener Associates a

    method that handlesvalue changeevents.

    public void

    (javax.faces.event.ValueChangeEvent);

    Developing Webbased User Interfaces Using JavaServer Faces 4

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    7/34

    Introducing the JSF Custom Tag LibraryThe JSF custom tag library contains the HTML and core custom tag libraries. A custom tag library isa collection of custom tags that you can use to perform repetitive tasks on JSP pages. A custom tagcontains:

    A tag handler: Is a Java class that implements the tag. For example, a custom tag that

    inserts the current date on a JSP page contains a tag handler that evaluates the date.

    A tag: Is the custom tag on the JSP page. For the current date custom tag, you can use the tag to include the custom tag on the JSP page.

    A Tag Library Descriptor (TLD) file: An XML file defining the custom tag. It has the .tldextension, which contains information about the tag, such as tag name, prefix, version, andattributes.

    You must include a reference to the JSF custom tag library to use the tags of the library on a JSF

    page. You can include the reference using the JSP taglib directive. The taglib directive contains:

    An uri attribute: Specifies the location of the tag library.

    A prefix attribute: Specifies a character or a word to refer to a tag. For example, for thetagPrefix prefix, a tag is referred to as < tagPrefix :current_date >.

    Note You can use any character or name as the prefix of a custom tag library. As a convention,

    you should use f and h for the core and HTML JSF tag libraries, respectively.

    You can use the following taglib directives on a JSF page to include references to the HTML andcore JSF custom tag libraries:

    The Core Custom Tag Library

    The core custom tag library contains tags to perform tasks, such as event handling, conversion, andvalidation, on JSF pages. It also contains the JSF container tags and tags to pass parameters andconfigure attributes. The tags of the core custom tag library are not bound to a specific renderer.This enables multiple renderers, such as HTML and Wireless Markup Language (WML) renderers,to use the tags.

    Table 22 describes the tags of the core custom tag library:

    Table 22: The Core Custom Tag Library

    Category Tag Description

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    8/34

    Tag Container Encloses all JSF custom tags.

    Event handling Registers an event listener thathandles action events.

    Registers an event listener thathandles valuechanged events.

    Attribute configuration Adds attributes to its parentcomponent. The component that a

    parent tag renders is called itsparent component.

    Data conversion Registers a converter with theparent component.

    Registers an instance of theDateTimeConverter class with itsparent component. TheDateTimeConverter class is aconverter for the date and timevalues that the java.util.Date classrepresents.

    Registers a number converter withits parent component.

    Facet Declares subordinate componentsfor a parent UI component.

    Internationalization andlocalization

    Loads a resource bundle on a JSFpage. Resource bundles areproperty files that contain key valuepairs to display localespecificmessages in applications.

    Parameter passing Passes parameter values to itsparent component. You can alsouse this tag to add query strings toa URL.

    Validator Registers a validator with its parent

    component. Registers an instance of theDoubleRangeValidator class withits parent component. TheDoubleRangeValidator classrepresents a validator that validatesa double value within a specifiedminimum and maximum range.

    Registers an instance of theLengthValidator class with itsparent component. TheLengthValidator class represents avalidator that validates the number

    of characters in a String object. Registers an instance of theLongRangeValidator class with itsparent component. TheLongRangeValidator classrepresents a validator that validatesa long value within a specifiedminimum and maximum range.

    Selectable component item Is an item of a selectablecomponent, such as a radio button,a checkbox, a menu, or a list.

    Is a set of items of multipleselectable components from which

    Developing Webbased User Interfaces Using JavaServer Faces 6

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    9/34

    an end user can select multipleitems.

    Container Includes the content of an externalJSF page in the current JSF page.You can include an external JSFpage in the current page using the tag within the tag.

    Output Renders a component that displaysthe content included in its body.

    The HTML Custom Tag Library

    The HTML custom tag library contains tags that represent UI components. You can use this taglibrary to render HTML UI components on Web pages. The html_basic.tld file is the TLD file thatdefines the tags of this tag library. This file is inside the jsfimpl.jar file. You can group the tags thatthe html_basic.tld TLD file defines into:

    Input tags: Include UI components that can accept input data from end users.

    Output tags: Include UI components that display readonly data on Web pages.

    Command tags: Include the command button and command hyperlink UI components.

    Selection tags: Includes enduser selectable UI components, such as radio buttons andcheck boxes. Selection tags can be further grouped into single and multipleselection tags.You can select only one item from the selectable UI components that the single selectiontags render. For the selectable UI components that the multipleselection tags render, youcan select multiple items.

    Other tags: Includes miscellaneous UI components, such a layout, error, and messagecomponents.

    Table 23 describes the tags of the HTML custom tag library:

    Table 23: The HTML Custom Tag Library

    Category Tag Description

    Input Renders an input text field that accepts a string.

    Renders an input password field that masks input

    characters. Renders a hidden text field.

    Renders a multiline text area.

    Output Renders parameterized messages. Aparameterized message is stored in a resourcebundle and contains placeholders for theparameters. The tag uses the tags to provide values for theparameters at runtime. A JSF resource bundle is a.properties file that contains keyvalue entries.

    Renders an HTML label. You can use the forattribute of this tag to specify the ID of an input

    Developing Webbased User Interfaces Using JavaServer Faces 7

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    10/34

    component to display a label for the component.

    Renders an HTML anchor element. The valueattribute of this tag specifies the href attribute of the element.

    Renders text on a Web page. The value attribute ofthis tag can retrieve the text value to be displayedfrom a backing bean property using a value binding

    expression.Command Renders a push button that triggers an event whenclicked.

    Renders a hyperlink that triggers an event whenclicked.

    Single selection Renders a check box whose value can be eithertrue or false.

    Renders a group of radio buttons from which anend user can select a radio button.

    Renders a scrollable menu from which an end usercan select a single item.

    Renders a list box in which an end user can select

    a single item.Multipleselection Renders a group of check boxes from which anend user can select one or more check boxes.

    Renders a scrollable menu from which an end usercan select multiple items.

    Renders a list box from which an end user canselect multiple items.

    Other Is an input form that allows an end user to inputdata and submit it to the server. You must encloseall tags that render editable UI components, suchas text field and text area, within the tag.

    Displays an image on a JSF page.

    Displays error messages, such as validation andconversion error messages, on a JSF page.

    Renders JSF components in a table with aspecified number of columns.

    Groups a set of components.

    Renders a table that contains columns that the tags represent.

    Is a column within an HtmlDataTable component.

    Developing Webbased User Interfaces Using JavaServer Faces 8

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    11/34

    Page Navigation in JSF ApplicationsAll Web applications require the page navigation feature using which an end user can navigate fromone Web page to another. J2EE Web applications rely on the hyperlinks that the HTML () tag renders and the tag to perform page navigation. This process, though easy toimplement, is unmanageable when the volume of Web pages in a Web application grows. This isbecause the tags on Web pages contain the URL of the destination that a hyperlink represents.

    Similarly, a Web page with a form contains the destination URL in the action attribute of the tag. If you need to add Web pages or change destination Web pages, you need to update the linkson all the Web pages that refer to the updated Web page. The JSF framework provides a pagenavigation model in which a navigation handler manages page navigation. In this model, you candefine a navigation rule in the JSF configuration file. An end user can click the UICommandcomponents that the and tags render to perform pagenavigation.

    Specifying Navigation Rules

    A navigation rule is a set of configuration information that specifies an origin and a destination pagefor navigation in the JSF configuration file. You need to specify a navigation rule for each page thatallows an end user to navigate to another page. The tag of a JSF configurationfile defines a navigation rule. The definition of the tag is:

    The tag can contain the optional tag to describe the navigationrule. The and tags specify a display name and an icon for the navigationrule. The tag identifies the origin page to which the navigation rule is applied. Forexample, if you need to apply the navigation rule to the main.jsp JSF page, use the tag, as shown:

    Navigation rule of main.jspmain.jsp

    Note The tag is optional. If you do not specify the tag, the navigationrule is applied to all pages of the application. You can also specify that anavigation rule should be applied to all the pages of an application using the tag, as shown:

    *

    The tag contains the tag that specifies a condition and thedestination page for navigation. When the outcome of processing the tag matchesthe condition specified in the tag, the destination page appears. The definition ofthe tag is:

    The tag contains the , , and tags thatspecify a description, a display name, and an icon for the tag. IDEs use thevalues of the and tags to visually represent the tag. The tag also contains:

    The tag: Specifies the value of the action attribute of the component to whichthe navigation rule applies.

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    12/34

    The tag: Specifies the outcome.

    The tag: Specifies the destination page for the navigation rule.

    The tag: Specifies that the navigation rule should redirect the request to anotherJSF page.

    Performing Simple Page Navigation

    In simple page navigation, when an end user clicks a particular button or hyperlink, it always resultsin the display of a particular page. For example, a back hyperlink or button that displays theprevious Web page performs simple page navigation.

    In a Web application, you can create two Web pages that use a button and a hyperlink to performsimple page navigation. You can create a main.jsp JSF page that contains the tag to display a button.

    Listing 23 shows the content of the main.jsp file:

    Listing 23: The main.jsp File

    Input FieldsThe JSF Tutorial

    The above listing creates the main.jsp page that displays a button labeled Start.

    Now, you can create the page1.jsp JSF page that contains the tag. This tagdisplays a hyperlink to navigate back to the main.jsp JSF page.

    Listing 24 shows the content of the page1.jsp file:

    Listing 24: The page1.jsp File

    Page Navigation

    Developing Webbased User Interfaces Using JavaServer Faces 10

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    13/34

  • 8/14/2019 Programming Java Server Faces Applications

    14/34

    Figure 22: Output of the main.jsp JSF Page

    Click Start. The browser displays the output of the page1.jsp JSF page, as shown in Figure23:

    Figure 23: Output of the page1.jsp JSF Page

    2.

    Click Back to navigate back to the main.jsp JSF page.3.

    Performing Conditional Page Navigation

    In conditional page navigation, an end user clicking a button or a hyperlink may result in navigationto different pages based on the outcome of page processing. For example, two outcomes arepossible when an end user clicks a button to submit logon information, such as user name andpassword. Enduser authentication may or may not succeed. Based on the outcome, you candisplay either a welcome page or an error page using conditional page navigation.

    In conditional page navigation, you need to define multiple navigation cases for a navigation rule.The code that defines a navigation rule for the logon.jsp JSF page is:

    logon.jsp

    For this navigation rule, you can define a navigation case to display the greeting.jsp JSF file whenthe outcome of processing the page is a success. The code to define this navigation case is:

    successgreeting.jsp

    A navigation case to display the error.jsp JSF page when the outcome of processing the logon.jsppage is incorrect is:

    Developing Webbased User Interfaces Using JavaServer Faces 12

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    15/34

    errorerror.jsp

    You can also specify a default navigation case, in which all outcomes of page processing, exceptsuccess, displays the error.jsp JSF page, as shown in Listing 26:

    Listing 26: A Default Navigation Case

    logon.jspsuccessgreeting.jsperror.jsp

    The above listing shows a default navigation case for a navigation rule that specifies that alloutcomes except success should result in the display of the error.jsp JSF page.

    Note If a faces configuration file contains multiple navigation rules with the same fromviewid andfromoutcome but a different toviewid that points to different pages, the last navigation ruleis applicable.

    To implement conditional page navigation in JSF, you can create a logon module of a Webapplication. To create the module:

    Create the logon page.1.

    Create the welcome page.2.

    Create the error page.3.

    Create the logon properties file.4.

    Create the backing bean.5.

    Create the faces configuration file.6.

    Create the deployment descriptor file.7.

    Package and test the module.8.

    Developing Webbased User Interfaces Using JavaServer Faces 13

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    16/34

    Creating the Logon Page

    You can create a logon page that accepts enduser logon information and submits the informationto a backing bean. On the logon page, you can display the user name field, a password field, and asubmit button using the , , and tags. You canuse value binding expressions to associate the user name and password UI components with theuserName and password properties of a backing bean. Similarly, associate the submit buttoncomponent with the validate() method of the backing bean.

    Listing 27 shows a logon.jsp file that creates the logon page of the logon module:

    Listing 27: The logon.jsp File

    Logon PageLogon Page

    The above listing creates the logon.jsp file that displays a logon page with a user name field, apassword field, and a submit button.

    Creating the Welcome Page

    You can create a welcome page for the logon module that displays a welcome message when anend user is authenticated. On the welcome page, you can use the tag to display theenduser name stored in the userName property of the backing bean. You can also add a

    Developing Webbased User Interfaces Using JavaServer Faces 14

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    17/34

    tag with a logout action to display a hyperlink for navigating back to the logonpage.

    Listing 28 shows the greeting.jsp file of the logon module:

    Listing 28: The greeting.jsp File

    Greeting PageGreeting PageHello ! You have been successfullyauthenticated.

    The above listing creates the greeting.jsp file that displays a personalized greeting message and ahyperlink to navigate back to the logon page.

    Creating the Error Page

    You can create an error page for the logon module to display an error message when authenticationfails. On the error page, you can display the invalid user name and password values stored in theuserName and password properties of the backing bean. To enable end users to navigate back tothe logon page, you can include a tag with a logout action.

    Listing 29 shows the content of the error.jsp file that renders the error page of the logon module:

    Listing 29: The error.jsp File

    Error Page

    Error PageEither your user name () or password() is invalid. Please logon again.

    Developing Webbased User Interfaces Using JavaServer Faces 15

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    18/34

    The above listing creates the error.jsp file that displays an authentication error message and ahyperlink to navigate back to the logon page.

    Creating the Logon Properties File

    You can create a properties file to store the user name and password values of end users. Thebacking bean of the module can authenticate the enduser specified user name and passwordvalues with the values stored in the properties file.

    You can create a Logon.properties file with user name and password values, as shown:

    admin=passwordMatthew=rockstarAlice=pass123Mark=tutorialpassLaura=programmer

    This listing creates the Logon.properties file that contains user name and password values as

    keyvalue pairs.

    Creating the Backing Bean

    The backing bean of the logon module validates enduser specified user name and passwordvalues. The backing bean contains the userName and password properties and implements theaccessor and mutator methods of the properties. The backing bean contains a validate() method inwhich the logon credentials are authenticated with the values stored in the Logon.properties file.

    Listing 210 shows the content of the LogonBean.java file, which is the backing bean class of thelogon module:

    Listing 210: The LogonBean.java File

    package logon;import java.util.*;public class LogonBean{

    /*Property declaration*/private String userName;private String password;public LogonBean(){}/*Accessor method for user name*/public String getUserName() {

    return userName;}/*Mutator method for user name*/public void setUserName(String userName) {

    this.userName=userName;}/*Accessor method for password*/public String getPassword() {

    return password;}/*Mutator method for password*/public void setPassword(String password) {

    this.password=password;}/*Validates logon credentials*/public String validate(){

    String flag="failure";/*Load the Logon.properties file*/ResourceBundle logonCredential = ResourceBundle.getBundle("Logon");

    Developing Webbased User Interfaces Using JavaServer Faces 16

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    19/34

    /*Retrieve the keys as an Enumeration object*/Enumeration keys = logonCredential.getKeys();while (keys.hasMoreElements()){

    /*For each key entry, retrieve the key and its value*/String key = (String)keys.nextElement();String value = logonCredential.getString(key);/*Compare key/value with end user specified user name and password if (userName.equalsIgnoreCase(key)&&password.equals(value)){

    /*Return success if value matches*/flag="success";return flag;

    }}/*Return failure if values do not match*/return flag;

    }}

    The above listing creates the LogonBean.java file that authenticates the enduser specified username and password values with the values stored in the Logon.properties file.

    When an end user submits a user name and password on the logon page, the JSF framework callsthe mutator methods of the userName and password properties. This stores the enduser specifiedvalues in the userName and password properties. The JSF framework also evaluates the actionattribute of the tag present on the logon page and subsequently calls thevalidate() method of the backing bean. The validate() method performs authentication and, basedon the result, returns a String value success or failure. These String values are the outcome oflogon page processing. Based on the outcome, you can define navigation rules in the facesconfiguration file.

    Creating the Faces Configuration File

    You can specify the navigation rules of the logon module in the faces configuration file. You alsoneed to declare the LogonBean backing bean in this configuration file.

    You can create two navigation rules in the faces configuration file. The first navigation rule appliesto the logon.jsp page with two conditional navigation cases. The first navigation case will display thegreeting.jsp page if the outcome of processing the logon.jsp page is success. The secondnavigation case displays the error.jsp page for the failure outcome.

    The second navigation rule applies to all pages. The navigation case of the second navigation ruledisplays the logon.jsp page if the outcome of processing a page is logout.

    Listing 211 shows the facesconfig.xml file of the logon module:

    Listing 211: The facesconfig.xml File

    /logon.jspsuccess/greeting.jspfailure

    Developing Webbased User Interfaces Using JavaServer Faces 17

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    20/34

    /error.jsp*

    logout/logon.jsplogonBeanlogon.LogonBeansession

    The above listing creates the facesconfig.xml file of the logon module that contains two navigationrules and a backing bean declaration.

    Creating the Deployment Descriptor File

    The deployment descriptor file declares the faces servlet and maps URL patterns to the facesservlet. It also specifies the name and location of the faces configuration file.

    Listing 212 creates the web.xml deployment descriptor file of the logon module:

    Listing 212: The web.xml File

    Facesjavax.faces.webapp.FacesServlet 1 Faces/logon/*

    com.sun.faces.config.ConfigureListenerjavax.faces.CONFIG_FILES/WEBINF/facesconfig.xml

    The above listing creates the web.xml deployment descriptor file of the logon module that declaresthe faces servlet and the faces configuration file and maps a URL pattern to the faces servlet.

    Developing Webbased User Interfaces Using JavaServer Faces 18

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    21/34

    Packaging and Testing the Module

    To test a JSF application, you need to compile the Java files and package the application files as aWAR file. To package the logon module:

    Compile the LogonBean.java file.1.

    Create a logonmodule directory and copy the logon.jsp, greeting.jsp, and error.jsp files to it.2.

    Create a WEBINF directory in the logonmodule directory.3.

    Copy the facesconfig.xml and web.xml files to the WEBINF directory.4.

    Create a classes directory in the WEBINF directory and copy the Logon.properties file tothe classes directory.

    5.

    Create a logon directory in the classes directory and copy the LogonModule.class file to thelogon directory.

    6.

    Figure 24 shows the directory structure of the logon module:

    Figure 24: The Structure of the Logon Module Directory

    Open the command prompt window and type the following command from the logonmoduledirectory:

    jar cvf logonmodule.war.

    7.

    This command creates the logonmodule.war file.

    Developing Webbased User Interfaces Using JavaServer Faces 19

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    22/34

    You can test the logon module in the Tomcat container. Before testing the module, ensure that thejsfapi.jar, jsfimpl.jar, commonsbeanutils.jar, commonsdigester.jar, and jstl.jar files are presentin the /shared/lib directory. To test the module:

    Copy the logonmodule.war file to the /webapps directory.1.

    Start the Tomcat container.2.

    Open a browser window and type the following URL in the address bar of the browserwindow:

    http://localhost:8080/logonmodule/logon/logon.jsp

    The browser displays the logon page of the module. Specify a user name and a password inthe User Name and Password fields, as shown in Figure 25:

    Figure 25: Output of the Logon Page

    3.

    Click Logon. The browser displays the error page of the module, as shown in Figure 26:

    Figure 26: Output of the Error Page

    4.

    Click Logon page to navigate back to the logon page of the module.5.

    Specify valid username and password values that are present in the Logon.properties fileand click Logon. The browser displays the greeting page of the module, as shown in Figure27:

    6.

    Developing Webbased User Interfaces Using JavaServer Faces 20

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    23/34

    Figure 27: Output of the Greeting Page

    Select Logout to log off from the module.7.

    Developing Webbased User Interfaces Using JavaServer Faces 21

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    24/34

    Handling Events in JSF ApplicationsThe JSF framework implements an eventhandling mechanism that is similar to the mechanismused to handle events in JavaBeans. In JSF, an end user clicking a button, selecting a hyperlink, orselecting an item from a menu can trigger an event. An event class represents an event and allevent classes of JSF extend the javax.faces.event.FacesEvent class. A component such as thebutton, hyperlink, or menu that triggers the event is called the event source.

    In JSF, listener classes handle events. You need to register a listener class with an event source tohandle the events that the source raises. A listener class contains a notification method. When anevent source raises an event, the JSF framework invokes the notification method of the listenerclass and passes an instance of the event class as an argument to the method.

    Based on the type of action that an end user performs, there are two types of events. They are:

    Action event: Occurs when an end user activates a component that implements theActionSource interface. JSF components that implement the ActionSource interface and cantrigger an action event are the HtmlCommandButton and HtmlCommandLink UICommandcomponents.

    Value changed event: Occurs when an end user changes the value of an UI component thatthe UIInput class or one of its subclasses represents.

    You can handle events in JSF by:

    Implementing an eventhandling method in a backing bean.

    Implementing an event listener class.

    Handling Action Events in a Backing Bean

    You can handle events in a backing bean that JSF components trigger. To handle events in abacking bean, you need to implement an eventhandling method in the backing bean. You canassociate the method with a JSF component using a method binding expression. When thecomponent triggers an event, the JSF framework invokes the eventhandling method of the backingbean.

    For example, you can create a JSF application to play a game where an enduser can guess anumber and check whether the number matches with the one that the application generates. On theJSF page of the application, you can display a text field and a button. An end user can specify anumber in the text field and click the button to play the game. A backing bean method of theapplication can handle the action event that arises when an end user clicks the button. You can alsoadd a command link to the JSF page that reloads the game. You can associate the link with abacking bean method using a method binding expression. In the backing bean method, you canhandle the action event that arises when an end user selects the link.

    Listing 213 shows the content of the game.jsp JSF page that displays the UI components of thenumberguessing game application:

    Listing 213: The game.jsp Page

    Number Game

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    25/34

    Guess a single digit number

    The above listing creates the game.jsp JSF page of the numberguessing game application. ThisJSF page contains the following tags to display UI components:

    : Displays a HtmlInputText UI component that represents a text field. This UIcomponent accepts a number from an end user.

    : Displays a HtmlCommandButton UI component that represents abutton. This UI component submits the data of the JSF page to the server.

    : Displays the result of the game.

    : Displays the number of attempts that an end user makes toguess a number.

    : Displays a HtmlCommandLink component that represents a link toreload the game.

    The backing bean of the numberguessing game application contains the userNumber, result, andattempt properties. The tag of the JSF page is associated with the userNumber

    properties while the < h:outputText id="result"> and < h:outputText id="attempt"> tags areassociated with the result and attempt properties. The backing bean also contains the play() andload() action listener methods. The play() action listener method contains code to play the gameand sets the result and attempt properties. The load() action listener method invalidates the currentsession to start a new game.

    Listing 214 shows the content of the GameBean.java file that creates the backing bean of theapplication:

    Listing 214: The GameBean.java File

    package game;import java.util.*;import javax.faces.context.FacesContext;import javax.servlet.http.HttpSession;

    Developing Webbased User Interfaces Using JavaServer Faces 23

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    26/34

    public class GameBean{

    /*Property declaration*/private String userNumber;private String result;private String attempt;private int generatedNumber;int i=0;public GameBean(){

    /*Generate a random number*/generatedNumber = (int)(Math.random()*10);

    }/*Accessor method for user number*/public String getUserNumber() {

    return userNumber;}/*Mutator method for user number*/public void setUserNumber(String userNumber) {

    this.userNumber=userNumber;}/*Accessor method for result*/public String getResult() {

    return result;}/*Mutator method for result*/

    public void setResult(String result) {this.result=result;

    }/*Accessor method for attempt*/public String getAttempt() {

    return attempt;}/*Mutator method for result*/public void setAttempt(String attempt) {

    this.attempt=attempt;}/*Implement the play() method*/public void play(){

    i++;int tempNumber=Integer.parseInt(userNumber);

    /*If user specified number is equal to generated number*/if (tempNumber==generatedNumber){

    /*Set result and attempt properties*/setResult("Congratulation! You specified "+userNumber+" and your nuournumber.");setAttempt("You have attempted "+i+" times");

    }/*If user specified number is less than generated number*/else if(tempNumbergeneratedNumber){

    /*Set result and attempt properties*/setResult("Sorry! You specified "+userNumber+", but your number doenumber.Enter a lower number.");setAttempt("You have attempted "+i+" times");

    }}public void load(){

    /*Invalidate session*/FacesContext context = FacesContext.getCurrentInstance();HttpSession session = (HttpSession) context.getExternalContext().getSession

    Developing Webbased User Interfaces Using JavaServer Faces 24

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    27/34

    session.invalidate();}

    }

    The above listing creates the GameBean.java file that compares an enduserspecified numberwith a randomly generated number. Based on the result and the number of attempts, the setResult()and setAttempt() methods set the result and attempt properties.

    When you access the game.jsp file, the browser displays the output of the file, as shown in Figure28:

    Figure 28: Output of the game.jsp FileSpecify a singledigit number and click Play to play the game. The browser displays the result andthe number of attempts. Figure 29 shows the result of playing the numberguessing game:

    Figure 29: Result of the NumberGuessing GameWhen you associate a component with the eventhandling method of a backing bean, the JSFframework creates a default listener that handles action events for the component. This listener

    invokes the eventhandling method of the backing bean for an enduser action. Instead of relyingon the default action event listener, you can define your own action event listener to handle actionevents in JSF.

    Handling Action Events in an Event Listener

    An action event listener handles the action events of JSF components. In the JSF framework, theFacesListener interface represents an event listener. Based on the type of events that an eventlistener handles, two interfaces implement the FacesListener interface. They are:

    ActionListener: Handles action events.

    ValueChangeListener: Handles value changed events.

    Developing Webbased User Interfaces Using JavaServer Faces 25

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    28/34

    To create an action event listener, you need to implement the ActionListener interface in yourlistener class. The ActionListener event contains the processAction() method. When a componenttriggers an action event, the JSF framework calls this method and passes an ActionEvent object asthe method argument. In the listener class, you need to include eventhandling code in this method.

    You can convert the numberguessing application to use an event listener instead of using the

    backing bean methods to handle events. To use the event listener, you need to include the tag within the UI component tags that trigger action events. In thenumberguessing application, the Play button and the Reload game link trigger action events. As aresult, you need to include the tag within both the and tags. The tag contains a type attribute that specifies the fullyqualified name of the event listener that handles the action event:

    Listing 215 shows the content of the numbergame.jsp file that declares event listeners to handleevents in the numberguessing application:

    Listing 215: The numbergame.jsp File

    Number Game

    Guess a single digit number

    The above listing creates the numbergame.jsp file that registers action listeners for the UIcomponents that the and tags render.

    Because the modified numberguessing application contains an event listener, the backing bean ofthe application does not contain eventhandling code. The backing bean declares the userNumber,attempt, and result properties and implements the corresponding accessor and mutator methods ofthese properties.

    Listing 216 shows the content of the modified GameBean.java backing bean file:

    Listing 216: The Modified GameBean.java File

    package game;import java.util.*;import javax.faces.context.FacesContext;import javax.servlet.http.HttpSession;

    Developing Webbased User Interfaces Using JavaServer Faces 26

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    29/34

    public class GameBean{

    /*Property declaration*/private String userNumber;private String result;private String attempt;public GameBean(){}/*Accessor method for user number*/

    public String getUserNumber() {return userNumber;

    }/*Mutator method for user number*/public void setUserNumber(String userNumber) {

    this.userNumber = userNumber;}/*Accessor method for result*/public String getResult() {

    return result;}/*Mutator method for result*/public void setResult(String result) {

    this.result=result;}/*Accessor method for attempt*/

    public String getAttempt() {return attempt;

    }/*Mutator method for result*/public void setAttempt(String attempt) {

    this.attempt=attempt;}

    }

    The above listing shows the modified GameBean.java file that declares the accessor and mutatormethods of the userNumber, attempt, and result properties.

    To create the listener class of the numberguessing application, you need to:

    Implement the ActionListener interface in the listener class.1.

    Generate a random number in the class constructor.2.

    Override the processAction() method. In this method, obtain the ID of the UI component thatraises an action event. In the numberguessing application, either the Play button or theReload page link can trigger an event.

    3.

    If the Play button raises an event, retrieve the enduserspecified number and compare it to

    the randomly generated number.

    4.

    Call the getValueBinding() method to retrieve a ValueBinding object that represents a valuebinding expression for the result and attempt properties.

    5.

    Use the ValueBinding objects to set the result and attempt properties.6.

    If the Reload page link raises an event, invalidate the current session.7.

    Implement the getValueBinding() method that returns a ValueBinding object.8.

    Developing Webbased User Interfaces Using JavaServer Faces 27

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    30/34

    Listing 217 shows the content of the GameListener.java file that handles events for thenumberguessing application.

    Listing 217: The GameListener Class

    package game;import java.util.*;import javax.faces.event.AbortProcessingException;import javax.faces.event.ActionEvent;import javax.faces.event.ActionListener;import javax.faces.context.FacesContext;import javax.faces.el.ValueBinding;import javax.faces.FactoryFinder;import javax.servlet.http.HttpSession;import javax.faces.application.ApplicationFactory;import javax.faces.application.Application;public class GameListener implements ActionListener{

    private String userNumber;private String result;private String attempt;private int generatedNumber;private ValueBinding resultBinding, attemptBinding;

    private int i;/*Class constructor*/public GameListener(){

    /*Generate single digit random number*/generatedNumber = (int)(Math.random()*10);

    }public void processAction(ActionEvent event) throws AbortProcessingException{

    /*Retrieve the command ID that generates an event*/String command= event.getComponent().getId();/*If button generates event*/if(command.equals("submit")){

    i++;/*Generate a random number*/

    String current = event.getComponent().getId();/*Retrieve the FacesContext object of the current application*/FacesContext facesContext = FacesContext.getCurrentInstance();/*Retrieve end user specified number*/userNumber =(String)getValueBinding("#{gameBean.userNumber}").getVa/*Convert number to primitive int type*/int tempNumber=Integer.parseInt(userNumber);/*Retrieve ValueBinding objects for the result and attempt propertiresultBinding= getValueBinding("#{gameBean.result}");attemptBinding=getValueBinding("#{gameBean.attempt}");/*if user specified number is equal to generated number*/if (tempNumber==generatedNumber){

    /*Set result and attempt properties*/result="Congratulation! You specified "+userNumber+" and yoour number.";

    resultBinding.setValue(facesContext, result);attempt="You have attempted "+i+" times";attemptBinding.setValue(facesContext, attempt);

    }/*If user specified number is less than generated number*/else if(tempNumbergeneratedNumber)

    Developing Webbased User Interfaces Using JavaServer Faces 28

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    31/34

    {/*Set result and attempt properties*/result="Sorry! You specified "+userNumber+", but your numbeour number. Enter a lower number.";attempt="You have attempted "+i+" times";resultBinding.setValue(facesContext, result);attemptBinding.setValue(facesContext, attempt);System.out.println(attempt+" inside greater");

    }}

    else if (command.equals("link")){

    /*Invalidate session*/FacesContext context = FacesContext.getCurrentInstance();HttpSession session = (HttpSession) context.getExternalContext().gesession.invalidate();i=0;

    }}/*Method that returns a ValueBinding object for a particular value binding expressiprivate static ValueBinding getValueBinding(String valueRef){

    /*Create an ApplicationFactory object*/ApplicationFactory factory =(ApplicationFactory)FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACT/*Obtain a Application object that represents the JSF application*/

    Application application = factory.getApplication();/*Call the createValueBinding() method to create a ValueBindin object*/return application.createValueBinding(valueRef);

    }}

    The above listing creates the GameListener class that handles action events in thenumberguessing application.

    Access the numbergame.jsp JSF file to specify a number and click Play. The GameListener eventhandler handles the action event that the Play button triggers to display the result and the attempts,as shown in Figure 210:

    Figure 210: The Result of the Game on the BrowserHandling Value Changed Events

    A valuechange event occurs when an end user changes the value of a UI component on a JSFpage. You can handle a value change event by implementing an eventhandling method in thebacking bean or implementing a value change listener class. A value change listener class mustimplement the ValueChangeListener interface and override the processValueChange() method ofthe interface.

    You need to implement a value change eventhandling method in a backing bean with the followingsignature:

    Developing Webbased User Interfaces Using JavaServer Faces 29

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    32/34

    public void (ValueChangeEvent vce){}

    You can associate the eventhandling method with a UI component using a method bindingexpression in the valueChangeListener attribute of the component tag, as shown:

    valueChangeListener="#{backingBean.processValueChange}"

    To implement value change event handling, you can create a song list application in which an enduser can select a song title from a menu to view information about the song, such as singer nameand song duration. In the song list application, you can display a selectable menu with valuespopulated from the ArrayList property of a backing bean. You can associate the menu with abacking bean eventhandling method using the valueChangeListener attribute. When an end userselects a song title from a menu, the JSF page needs to submit the information to the server. Youcan include a JavaScript code that submits the information in the onchange attribute. To displayinformation about an enduserselected song, you can use a tag.

    Listing 218 shows the song.jsp file that displays a menu from which an end user can select a songtitle to view information about the song:

    Listing 218: The song.jsp File

    Song Detail

    The above listing creates the song.jsp file that renders a menu of song titles that an end user canselect to view song information.

    In the backing bean of the song list application, you need to declare an ArrayList property thatcontains the song titles to display. You can populate the ArrayList with the song title in the backing

    bean class constructor. In the value change eventhandling method, you need to call thegetExternalContext() method that returns an ExternalContext object. An ExternalContext objectprovides access to the request and response objects of the application. You can call thegetRequest() method of the ExternalContext class to retrieve the HttpServletRequest object andextract the enduserselected song title. After retrieving the song title, you can set the songDetailattribute of the backing bean with information about the song.

    Listing 219 shows the SongBean.java file of the song list application:

    Listing 219: The SongBean.java File

    package song;import javax.faces.context.FacesContext;import javax.faces.context.ExternalContext;import java.util.*;

    Developing Webbased User Interfaces Using JavaServer Faces 30

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    33/34

    import javax.faces.model.SelectItem;import javax.faces.event.ValueChangeEvent;import javax.faces.event.AbortProcessingException;public class SongBean{

    /*Stores the song titles*/ArrayList songList = new ArrayList();/*Stores song description*/HashMap desc = new HashMap();String selectedSong;

    String songDetail = "Select a song to view information";/*Backing bean constructor*/public SongBean(){

    /*Populate songLists ArrayList with song titles*/songList.add(new SelectItem("mm000", "Midnight Melodies", "m"));songList.add(new SelectItem("rc000", "Rock Cradle", "r"));songList.add(new SelectItem("pc000", "Purple Clouds", "p"));/*Populate desc HasMap with song description*/desc.put("mm000", "Genre: Blues, Singer: Bobby Smith, Duration: 5.35");desc.put("rc000", "Genre: Rock, Singer: Albert Simpson, Duration: 7.10");desc.put("pc000", "Genre: Reggae, Singer: Craig Hash, Duration: 4.45");

    }/*Accessor method for selectedSong property*/public String getSelectedSong () {

    return selectedSong;

    }Mutator method for selectedSong property*/public void setSelectedSong (String selectedSong) {

    this.selectedSong = selectedSong;}/*Accessor method for songList property*/public ArrayList getSongList() {

    return songList;}/*Mutator method for songList property*/public void setSongList(ArrayList songList) {

    this.songList = songList;}/*Accessor method for songDetail property*/public String getSongDetail() {

    return songDetail;

    }/*Mutator method for songDetail property*/public void setSongDetail(String songDetail){

    this.songDetail = songDetail;}/*Value change listener method*/public void processValueChange(ValueChangeEvent vce){

    /*Obtain ExternalContext object that represent information of the runtime eExternalContext exc= FacesContext.getCurrentInstance().getExternalContext();/*Retrieve the client request as an ttpServletRequest object*/javax.servlet.http.HttpServletRequest req= (javax.servlet.http.HttpServletRequest)(exc.getRequest());/*Retrieve end user selected song sent as request parameter*/

    String key = req.getParameter("songForm:songList");/*Set the songDetail property*/setSongDetail((String)desc.get(key));/*Render the response*/FacesContext.getCurrentInstance().renderResponse();

    }}

    The above listing creates the SongBean backing bean class of the song list application that handlesthe value change events of the application.

    When you access the song.jsp file, the browser displays a menu with song titles, as shown in Figure211:

    Developing Webbased User Interfaces Using JavaServer Faces 31

    Reprinted for v697042, Verizon SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

  • 8/14/2019 Programming Java Server Faces Applications

    34/34

    Figure 211: The Song Title MenuSelect a song title from the menu. The browser displays information about the song, as shown inFigure 212:

    Figure 212: Song Information

    Developing Webbased User Interfaces Using JavaServer Faces 32