Programming Java Server Faces Applications

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Programming Java Server Faces Applications as PDF for free.

More details

  • Words: 9,017
  • Pages: 34
All rights reserved. Reproduction and/or distribution in whole or in part in electronic, paper or other forms without written permission is prohibited.

Developing Web−based User Interfaces Using JavaServer Faces SkillSoft Corporation. (c) 2005. Copying Prohibited.

Reprinted for Sridhar Poduri, Verizon [email protected] Reprinted with permission as a subscription benefit of Books24x7, http://www.books24x7.com/

i

Table of Contents Chapter 2: Programming JavaServer Faces Applications............................................................1 JSF Binding Expressions................................................................................................................2 Value Binding Expressions.....................................................................................................2 Method Binding Expressions..................................................................................................4 Introducing the JSF Custom Tag Library.......................................................................................5 The Core Custom Tag Library................................................................................................5 The HTML Custom Tag Library..............................................................................................7 Page Navigation in JSF Applications.............................................................................................9 Specifying Navigation Rules...................................................................................................9 Performing Simple Page Navigation.....................................................................................10 Performing Conditional Page Navigation..............................................................................12 Handling Events in JSF Applications...........................................................................................22 Handling Action Events in a Backing Bean...........................................................................22 Handling Action Events in an Event Listener........................................................................25 Handling Value Changed Events..........................................................................................29

Chapter 2: Programming JavaServer Faces Applications The JavaServer Faces (JSF) framework uses binding expressions that constitute an Expression Language (EL) to associate User Interface (UI) components with the properties and methods of backing 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 framework contains a core and an HTML custom tag library. The JSF framework provides a navigation model that helps navigate among the Web pages of a Web application. As a developer, you need to define navigation rules in the faces configuration file. The JSF framework also provides an event−handling model that you can use to handle events that arise because of end−user action on JSF components. This chapter introduces JSF expressions and explains how to use them in JSF pages. It describes the JSF custom tags present in the JSF core and HTML tag libraries and how to perform page navigation and handle events in JSF applications.

Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

JSF Binding Expressions A JSF page uses custom tags to include JSF components. The custom tags can contain binding expressions to bind a component with a property or method of a backing bean. The syntax of binding expressions is based on the JavaServer Pages (JSP) 2.0 EL with a minor difference. In JSP, 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. For example, the OutputText component that displays the current stock information of companies can retrieve 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 the backing 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. For example, output components such as OutputText contain a rendered attribute with a boolean value that determines whether the component should be displayed or not. You can use a value binding expression for the rendered attribute to check a condition with a backing bean. If the result returns a true 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 Map objects of a backing bean. For example, if a backing bean contains an address property of type List or String array, you can access the first element of the List or array using a value binding expression, as shown: #{binderBean.address[0]}

If a backing bean contains a Map object called cities, you can access a value of the Map object using a value binding expression, as shown: #{binderBean.cities["key"]}

Listing 2−1 shows the content of the BackingBean class that contains the properties of the type String array, List, and Map objects: Listing 2−1: 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

Developing Web−based User Interfaces Using JavaServer Faces

3

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 binding expression. Listing 2−2 shows the valuebinding.jsp page that uses value binding expressions to display the properties of the BackingBean class using OutputText components: Listing 2−2: The valuebinding.jsp Page

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> Using Value Binding Expressions

Accessing List property of backing bean

First Address:
Second Address:

Accessing Array property of backing bean

First zip code:
Second zip code:

Accessing Map property of backing bean

First City:
Second City:


The above listing creates the valuebinding.jsp page that uses value binding expressions to display the properties of a backing bean using OutputText components. Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

4

When you access the valuebinding.jsp page from a browser, the page displays the property values of the backing bean, as shown in Figure 2−1:

Figure 2−1: Output of the valuebinding.jsp Page

Method Binding Expressions A method binding expression binds the value of a JSF component to the result that a public method of a backing bean returns. You can also pass parameters to the backing bean method using a method binding expression. Table 2−1 describes the attributes of JSF custom tags that accept method binding expressions and the corresponding method syntax: Table 2−1: Attributes Supporting Method Binding Expressions Attribute action

validator

actionListener

Description Associates a method that returns the outcome of an action. Associates a method that performs data validation. Associates a method that handles action events.

Method Syntax public String <methodName>();

public void <methodName> (javax.faces.event.ActionEvent);

public void <methodName> (javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object); valueChangeListener Associates a public void <methodName> method that handles (javax.faces.event.ValueChangeEvent); value change events.

Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Introducing the JSF Custom Tag Library The JSF custom tag library contains the HTML and core custom tag libraries. A custom tag library is a collection of custom tags that you can use to perform repetitive tasks on JSP pages. A custom tag contains: • 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 .tld extension, which contains information about the tag, such as tag name, prefix, version, and attributes.

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 the tagPrefix 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 and core JSF custom tag libraries: <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

The Core Custom Tag Library The core custom tag library contains tags to perform tasks, such as event handling, conversion, and validation, on JSF pages. It also contains the JSF container tags and tags to pass parameters and configure 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 2−2 describes the tags of the core custom tag library: Table 2−2: The Core Custom Tag Library Category Reprinted for v697042, Verizon

Tag

Description SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

Tag Container Event handling



Attribute configuration



Data conversion



Facet



Internationalization and localization



Parameter passing



Validator







Selectable component item



Reprinted for v697042, Verizon

6

Encloses all JSF custom tags. Registers an event listener that handles action events. Registers an event listener that handles value−changed events. Adds attributes to its parent component. The component that a parent tag renders is called its parent component. Registers a converter with the parent component. Registers an instance of the DateTimeConverter class with its parent component. The DateTimeConverter class is a converter for the date and time values that the java.util.Date class represents. Registers a number converter with its parent component. Declares subordinate components for a parent UI component. Loads a resource bundle on a JSF page. Resource bundles are property files that contain key value pairs to display locale−specific messages in applications. Passes parameter values to its parent component. You can also use this tag to add query strings to a URL. Registers a validator with its parent component. Registers an instance of the DoubleRangeValidator class with its parent component. The DoubleRangeValidator class represents a validator that validates a double value within a specified minimum and maximum range. Registers an instance of the LengthValidator class with its parent component. The LengthValidator class represents a validator that validates the number of characters in a String object. Registers an instance of the LongRangeValidator class with its parent component. The LongRangeValidator class represents a validator that validates a long value within a specified minimum and maximum range. Is an item of a selectable component, such as a radio button, a checkbox, a menu, or a list. Is a set of items of multiple selectable components from which SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

Container



Output



7

an end user can select multiple items. Includes the content of an external JSF page in the current JSF page. You can include an external JSF page in the current page using the <jsp:include> tag within the tag. Renders a component that displays the 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 tag library to render HTML UI components on Web pages. The html_basic.tld file is the TLD file that defines the tags of this tag library. This file is inside the jsf−impl.jar file. You can group the tags that the 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 read−only data on Web pages. • Command tags: Include the command button and command hyperlink UI components. • Selection tags: Includes end−user selectable UI components, such as radio buttons and check boxes. Selection tags can be further grouped into single− and multiple−selection tags. You can select only one item from the selectable UI components that the single selection tags render. For the selectable UI components that the multiple−selection tags render, you can select multiple items. • Other tags: Includes miscellaneous UI components, such a layout, error, and message components.

Table 2−3 describes the tags of the HTML custom tag library: Table 2−3: The HTML Custom Tag Library Category Input

Output

Tag



Reprinted for v697042, Verizon

Description 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. Renders parameterized messages. A parameterized message is stored in a resource bundle and contains placeholders for the parameters. The tag uses the tags to provide values for the parameters at runtime. A JSF resource bundle is a .properties file that contains key−value entries. Renders an HTML label. You can use the for attribute of this tag to specify the ID of an input SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

8

component to display a label for the component. Renders an HTML anchor element. The value attribute of this tag specifies the href attribute of the element. Renders text on a Web page. The value attribute of this tag can retrieve the text value to be displayed from a backing bean property using a value binding expression. Command Renders a push button that triggers an event when clicked. Renders a hyperlink that triggers an event when clicked. Single selection Renders a check box whose value can be either true or false. Renders a group of radio buttons from which an end user can select a radio button. Renders a scrollable menu from which an end user can select a single item. Renders a list box in which an end user can select a single item. Multiple−selection Renders a group of check boxes from which an end user can select one or more check boxes. Renders a scrollable menu from which an end user can select multiple items. Renders a list box from which an end user can select multiple items. Other Is an input form that allows an end user to input data and submit it to the server. You must enclose all tags that render editable UI components, such as text field and text area, within the tag. Displays an image on a JSF page. Displays error messages, such as validation and conversion error messages, on a JSF page. Renders JSF components in a table with a specified 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.

Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Page Navigation in JSF Applications All Web applications require the page navigation feature using which an end user can navigate from one 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 to implement, is unmanageable when the volume of Web pages in a Web application grows. This is because 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 links on all the Web pages that refer to the updated Web page. The JSF framework provides a page navigation model in which a navigation handler manages page navigation. In this model, you can define a navigation rule in the JSF configuration file. An end user can click the UICommand components that the and tags render to perform page navigation.

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


The tag can contain the optional <description> tag to describe the navigation rule. The and tags specify a display name and an icon for the navigation rule. The tag identifies the origin page to which the navigation rule is applied. For example, if you need to apply the navigation rule to the main.jsp JSF page, use the tag, as shown: <description>Navigation rule of main.jsp main.jsp − − − − − − − − −

Note

The tag is optional. If you do not specify the tag, the navigation rule is applied to all pages of the application. You can also specify that a navigation 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 the destination page for navigation. When the outcome of processing the tag matches the condition specified in the tag, the destination page appears. The definition of the tag is:


The tag contains the <description>, , and tags that specify a description, a display name, and an icon for the tag. IDEs use the values 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 which the navigation rule applies.

Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

10

• 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 another JSF page.

Performing Simple Page Navigation In simple page navigation, when an end user clicks a particular button or hyperlink, it always results in the display of a particular page. For example, a back hyperlink or button that displays the previous Web page performs simple page navigation. In a Web application, you can create two Web pages that use a button and a hyperlink to perform simple page navigation. You can create a main.jsp JSF page that contains the tag to display a button. Listing 2−3 shows the content of the main.jsp file: Listing 2−3: The main.jsp File <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> Input Fields

The 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 tag displays a hyperlink to navigate back to the main.jsp JSF page. Listing 2−4 shows the content of the page1.jsp file: Listing 2−4: The page1.jsp File

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> Page Navigation Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

11





The above listing creates the page1.jsp file that displays a hyperlink labeled Back. Both the main.jsp and page1.jsp files do not contain any navigation information. You need to specify the navigation information in the faces−config.xml file. In the faces−config.xml file, you need to include two tags that specify the navigation rule for each JSF page. Listing 2−5 shows the faces−config.xml file that contains navigation rules for the main.jsp and page1.jsp JSF pages: Listing 2−5: Navigation Rules in the faces−config.xml File

/main.jsp display /page1.jsp /page1.jsp back /main.jsp

The above listing creates the faces−config.xml file that specifies navigation rules for the main.jsp and page1.jsp JSF pages. To test navigation between the main.jsp and page1.jsp JSF pages: 1. Access the main.jsp page from the browser. The page displays the Start button, as shown in Figure 2−2:

Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

12

Figure 2−2: Output of the main.jsp JSF Page 2. Click Start. The browser displays the output of the page1.jsp JSF page, as shown in Figure 2−3:

Figure 2−3: Output of the page1.jsp JSF Page 3. Click Back to navigate back to the main.jsp JSF page.

Performing Conditional Page Navigation In conditional page navigation, an end user clicking a button or a hyperlink may result in navigation to different pages based on the outcome of page processing. For example, two outcomes are possible when an end user clicks a button to submit logon information, such as user name and password. End−user authentication may or may not succeed. Based on the outcome, you can display 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 when the outcome of processing the page is a success. The code to define this navigation case is: success greeting.jsp

A navigation case to display the error.jsp JSF page when the outcome of processing the logon.jsp page is incorrect is: Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

13

error error.jsp


You can also specify a default navigation case, in which all outcomes of page processing, except success, displays the error.jsp JSF page, as shown in Listing 2−6: Listing 2−6: A Default Navigation Case logon.jsp success greeting.jsp error.jsp

The above listing shows a default navigation case for a navigation rule that specifies that all outcomes 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 from−view−id and from−outcome but a different to−view−id that points to different pages, the last navigation rule is applicable. To implement conditional page navigation in JSF, you can create a logon module of a Web application. To create the module:

1. Create the logon page. 2. Create the welcome page. 3. Create the error page. 4. Create the logon properties file. 5. Create the backing bean. 6. Create the faces configuration file. 7. Create the deployment descriptor file. 8. Package and test the module.

Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

14

Creating the Logon Page You can create a logon page that accepts end−user logon information and submits the information to a backing bean. On the logon page, you can display the user name field, a password field, and a submit button using the , , and tags. You can use value binding expressions to associate the user name and password UI components with the userName and password properties of a backing bean. Similarly, associate the submit button component with the validate() method of the backing bean. Listing 2−7 shows a logon.jsp file that creates the logon page of the logon module: Listing 2−7: The logon.jsp File

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> Logon Page

Logon Page





The above listing creates the logon.jsp file that displays a logon page with a user name field, a password 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 an end user is authenticated. On the welcome page, you can use the tag to display the end−user name stored in the userName property of the backing bean. You can also add a Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

15

tag with a logout action to display a hyperlink for navigating back to the logon page. Listing 2−8 shows the greeting.jsp file of the logon module: Listing 2−8: The greeting.jsp File

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> Greeting Page

Greeting Page



Hello ! You have been successfully authenticated.





The above listing creates the greeting.jsp file that displays a personalized greeting message and a hyperlink 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 authentication fails. On the error page, you can display the invalid user name and password values stored in the userName and password properties of the backing bean. To enable end users to navigate back to the logon page, you can include a tag with a logout action. Listing 2−9 shows the content of the error.jsp file that renders the error page of the logon module: Listing 2−9: The error.jsp File

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> Error Page

Error Page



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



Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

16



The above listing creates the error.jsp file that displays an authentication error message and a hyperlink 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. The backing bean of the module can authenticate the end−user specified user name and password values with the values stored in the properties file. You can create a Logon.properties file with user name and password values, as shown: admin=password Matthew=rockstar Alice=pass123 Mark=tutorialpass Laura=programmer

This listing creates the Logon.properties file that contains user name and password values as key−value pairs. Creating the Backing Bean The backing bean of the logon module validates end−user specified user name and password values. The backing bean contains the userName and password properties and implements the accessor and mutator methods of the properties. The backing bean contains a validate() method in which the logon credentials are authenticated with the values stored in the Logon.properties file. Listing 2−10 shows the content of the LogonBean.java file, which is the backing bean class of the logon module: Listing 2−10: 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"); Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

17

/*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 valu 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 end−user specified user name 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 calls the mutator methods of the userName and password properties. This stores the end−user specified values in the userName and password properties. The JSF framework also evaluates the action attribute of the tag present on the logon page and subsequently calls the validate() method of the backing bean. The validate() method performs authentication and, based on the result, returns a String value success or failure. These String values are the outcome of logon page processing. Based on the outcome, you can define navigation rules in the faces configuration file. Creating the Faces Configuration File You can specify the navigation rules of the logon module in the faces configuration file. You also need 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 applies to the logon.jsp page with two conditional navigation cases. The first navigation case will display the greeting.jsp page if the outcome of processing the logon.jsp page is success. The second navigation 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 rule displays the logon.jsp page if the outcome of processing a page is logout. Listing 2−11 shows the faces−config.xml file of the logon module: Listing 2−11: The faces−config.xml File

/logon.jsp success /greeting.jsp failure Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

18

/error.jsp
* logout /logon.jsp <managed−bean> <managed−bean−name>logonBean <managed−bean−class>logon.LogonBean <managed−bean−scope>session


The above listing creates the faces−config.xml file of the logon module that contains two navigation rules and a backing bean declaration. Creating the Deployment Descriptor File The deployment descriptor file declares the faces servlet and maps URL patterns to the faces servlet. It also specifies the name and location of the faces configuration file. Listing 2−12 creates the web.xml deployment descriptor file of the logon module: Listing 2−12: The web.xml File

<web−app> <servlet> <servlet−name>Faces <servlet−class>javax.faces.webapp.FacesServlet 1 <servlet−mapping> <servlet−name>Faces /logon/* <listener> <listener−class>com.sun.faces.config.ConfigureListener <param−name>javax.faces.CONFIG_FILES <param−value>/WEB−INF/faces−config.xml

The above listing creates the web.xml deployment descriptor file of the logon module that declares the faces servlet and the faces configuration file and maps a URL pattern to the faces servlet. Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

19

Packaging and Testing the Module To test a JSF application, you need to compile the Java files and package the application files as a WAR file. To package the logon module: 1. Compile the LogonBean.java file. 2. Create a logonmodule directory and copy the logon.jsp, greeting.jsp, and error.jsp files to it. 3. Create a WEB−INF directory in the logonmodule directory. 4. Copy the faces−config.xml and web.xml files to the WEB−INF directory. 5. Create a classes directory in the WEB−INF directory and copy the Logon.properties file to the classes directory. 6. Create a logon directory in the classes directory and copy the LogonModule.class file to the logon directory.

Figure 2−4 shows the directory structure of the logon module:

Figure 2−4: The Structure of the Logon Module Directory 7. Open the command prompt window and type the following command from the logonmodule directory: jar −cvf logonmodule.war.

This command creates the logonmodule.war file.

Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

20

You can test the logon module in the Tomcat container. Before testing the module, ensure that the jsf−api.jar, jsf−impl.jar, commons−beanutils.jar, commons−digester.jar, and jstl.jar files are present in the /shared/lib directory. To test the module: 1. Copy the logonmodule.war file to the /webapps directory. 2. Start the Tomcat container. 3. Open a browser window and type the following URL in the address bar of the browser window: http://localhost:8080/logonmodule/logon/logon.jsp

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

Figure 2−5: Output of the Logon Page 4. Click Logon. The browser displays the error page of the module, as shown in Figure 2−6:

Figure 2−6: Output of the Error Page 5. Click Logon page to navigate back to the logon page of the module. 6. Specify valid user−name and password values that are present in the Logon.properties file and click Logon. The browser displays the greeting page of the module, as shown in Figure 2−7: Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

21

Figure 2−7: Output of the Greeting Page 7. Select Logout to log off from the module.

Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Handling Events in JSF Applications The JSF framework implements an event−handling mechanism that is similar to the mechanism used to handle events in JavaBeans. In JSF, an end user clicking a button, selecting a hyperlink, or selecting an item from a menu can trigger an event. An event class represents an event and all event classes of JSF extend the javax.faces.event.FacesEvent class. A component such as the button, 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 to handle the events that the source raises. A listener class contains a notification method. When an event source raises an event, the JSF framework invokes the notification method of the listener class 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 the ActionSource interface. JSF components that implement the ActionSource interface and can trigger an action event are the HtmlCommandButton and HtmlCommandLink UICommand components. • Value changed event: Occurs when an end user changes the value of an UI component that the UIInput class or one of its subclasses represents.

You can handle events in JSF by:

• Implementing an event−handling 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 a backing bean, you need to implement an event−handling method in the backing bean. You can associate the method with a JSF component using a method binding expression. When the component triggers an event, the JSF framework invokes the event−handling method of the backing bean. For example, you can create a JSF application to play a game where an end−user can guess a number and check whether the number matches with the one that the application generates. On the JSF page of the application, you can display a text field and a button. An end user can specify a number in the text field and click the button to play the game. A backing bean method of the application can handle the action event that arises when an end user clicks the button. You can also add a command link to the JSF page that reloads the game. You can associate the link with a backing bean method using a method binding expression. In the backing bean method, you can handle the action event that arises when an end user selects the link. Listing 2−13 shows the content of the game.jsp JSF page that displays the UI components of the number−guessing game application: Listing 2−13: The game.jsp Page

Number Game <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

23

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

Guess a single digit number



The above listing creates the game.jsp JSF page of the number−guessing game application. This JSF page contains the following tags to display UI components:

: Displays a HtmlInputText UI component that represents a text field. This UI component accepts a number from an end user. • : Displays a HtmlCommandButton UI component that represents a button. 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 to guess a number. • : Displays a HtmlCommandLink component that represents a link to reload the game.

The backing bean of the number−guessing game application contains the userNumber, result, and attempt 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 are associated with the result and attempt properties. The backing bean also contains the play() and load() action listener methods. The play() action listener method contains code to play the game and sets the result and attempt properties. The load() action listener method invalidates the current session to start a new game. Listing 2−14 shows the content of the GameBean.java file that creates the backing bean of the application: Listing 2−14: The GameBean.java File

package game; import java.util.*; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

24

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 number our number."); 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 does no number. 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(fal Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

25

session.invalidate(); } }

The above listing creates the GameBean.java file that compares an end−user−specified number with 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 Figure 2−8:

Figure 2−8: Output of the game.jsp File Specify a single−digit number and click Play to play the game. The browser displays the result and the number of attempts. Figure 2−9 shows the result of playing the number−guessing game:

Figure 2−9: Result of the Number−Guessing Game When you associate a component with the event−handling method of a backing bean, the JSF framework creates a default listener that handles action events for the component. This listener invokes the event−handling method of the backing bean for an end−user action. Instead of relying on the default action event listener, you can define your own action event listener to handle action events in JSF.

Handling Action Events in an Event Listener An action event listener handles the action events of JSF components. In the JSF framework, the FacesListener interface represents an event listener. Based on the type of events that an event listener handles, two interfaces implement the FacesListener interface. They are: • ActionListener: Handles action events. • ValueChangeListener: Handles value changed events. Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

26

To create an action event listener, you need to implement the ActionListener interface in your listener class. The ActionListener event contains the processAction() method. When a component triggers an action event, the JSF framework calls this method and passes an ActionEvent object as the method argument. In the listener class, you need to include event−handling code in this method. You can convert the number−guessing 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 the number−guessing application, the Play button and the Reload game link trigger action events. As a result, you need to include the tag within both the and tags. The tag contains a type attribute that specifies the fully qualified name of the event listener that handles the action event: Listing 2−15 shows the content of the numbergame.jsp file that declares event listeners to handle events in the number−guessing application: Listing 2−15: The numbergame.jsp File Number Game <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

Guess a single digit number



The above listing creates the numbergame.jsp file that registers action listeners for the UI components that the and tags render. Because the modified number−guessing application contains an event listener, the backing bean of the application does not contain event−handling code. The backing bean declares the userNumber, attempt, and result properties and implements the corresponding accessor and mutator methods of these properties. Listing 2−16 shows the content of the modified GameBean.java backing bean file: Listing 2−16: The Modified GameBean.java File package game; import java.util.*; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

27

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 mutator methods of the userNumber, attempt, and result properties. To create the listener class of the number−guessing application, you need to: 1. Implement the ActionListener interface in the listener class. 2. Generate a random number in the class constructor. 3. Override the processAction() method. In this method, obtain the ID of the UI component that raises an action event. In the number−guessing application, either the Play button or the Reload page link can trigger an event. 4. If the Play button raises an event, retrieve the end−user−specified number and compare it to the randomly generated number. 5. Call the getValueBinding() method to retrieve a ValueBinding object that represents a value binding expression for the result and attempt properties. 6. Use the ValueBinding objects to set the result and attempt properties. 7. If the Reload page link raises an event, invalidate the current session. 8. Implement the getValueBinding() method that returns a ValueBinding object. Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

28

Listing 2−17 shows the content of the GameListener.java file that handles events for the number−guessing application. Listing 2−17: 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}").getValue( /*Convert number to primitive int type*/ int tempNumber=Integer.parseInt(userNumber); /*Retrieve ValueBinding objects for the result and attempt properties*/ resultBinding= 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 your n our 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) Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

29

{

/*Set result and attempt properties*/ result="Sorry! You specified "+userNumber+", but your number do our 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().getSes session.invalidate(); i=0; }

} /*Method that returns a ValueBinding object for a particular value binding expression*/ private static ValueBinding getValueBinding(String valueRef) { /*Create an ApplicationFactory object*/ ApplicationFactory factory = (ApplicationFactory)FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY) /*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 the number−guessing application. Access the numbergame.jsp JSF file to specify a number and click Play. The GameListener event handler handles the action event that the Play button triggers to display the result and the attempts, as shown in Figure 2−10:

Figure 2−10: The Result of the Game on the Browser

Handling Value Changed Events A value−change event occurs when an end user changes the value of a UI component on a JSF page. You can handle a value change event by implementing an event−handling method in the backing bean or implementing a value change listener class. A value change listener class must implement the ValueChangeListener interface and override the processValueChange() method of the interface. You need to implement a value change event−handling method in a backing bean with the following signature: Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

30

public void <Method Name>(ValueChangeEvent vce) { }

You can associate the event−handling method with a UI component using a method binding expression 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 end user can select a song title from a menu to view information about the song, such as singer name and song duration. In the song list application, you can display a selectable menu with values populated from the ArrayList property of a backing bean. You can associate the menu with a backing bean event−handling method using the valueChangeListener attribute. When an end user selects a song title from a menu, the JSF page needs to submit the information to the server. You can include a JavaScript code that submits the information in the onchange attribute. To display information about an end−user−selected song, you can use a tag. Listing 2−18 shows the song.jsp file that displays a menu from which an end user can select a song title to view information about the song: Listing 2−18: The song.jsp File

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> Song Detail



The above listing creates the song.jsp file that renders a menu of song titles that an end user can select to view song information. In the backing bean of the song list application, you need to declare an ArrayList property that contains the song titles to display. You can populate the ArrayList with the song title in the backing bean class constructor. In the value change event−handling method, you need to call the getExternalContext() method that returns an ExternalContext object. An ExternalContext object provides access to the request and response objects of the application. You can call the getRequest() method of the ExternalContext class to retrieve the HttpServletRequest object and extract the end−user−selected song title. After retrieving the song title, you can set the songDetail attribute of the backing bean with information about the song. Listing 2−19 shows the SongBean.java file of the song list application: Listing 2−19: The SongBean.java File

package song; import javax.faces.context.FacesContext; import javax.faces.context.ExternalContext; import java.util.*; Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

import import import public {

31

javax.faces.model.SelectItem; javax.faces.event.ValueChangeEvent; javax.faces.event.AbortProcessingException; 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 envir ExternalContext 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 handles the value change events of the application. When you access the song.jsp file, the browser displays a menu with song titles, as shown in Figure 2−11: Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Developing Web−based User Interfaces Using JavaServer Faces

32

Figure 2−11: The Song Title Menu Select a song title from the menu. The browser displays information about the song, as shown in Figure 2−12:

Figure 2−12: Song Information

Reprinted for v697042, Verizon

SkillSoft, SkillSoft Corporation (c) 2005, Copying Prohibited

Related Documents